2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
40 // Check if our config file is writeable or not
41 function is_INCWritable($inc) {
43 $fqfn = sprintf("%sinc/%s.php", PATH, $inc);
45 // Abort by simple test
46 if ((FILE_READABLE($fqfn)) && (!is_writeable($fqfn))) {
50 // Test if we can append data
51 $fp = @fopen($fqfn, 'a');
52 if ($inc == "dummy") {
55 return @unlink($fqfn);
57 // Close all other files
62 // Open a table (you may want to add some header stuff here)
63 function OPEN_TABLE($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
66 // Count tables so we can generate CSS classes for every table... :-)
68 // Class is empty so count one up and create a class
69 $table_cnt++; $CLASS = "class".$table_cnt;
71 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
73 // Shall I add the classes to TABLE and TD or only to TD?
74 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
77 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
80 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
82 // Vertical align is given
83 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
84 $OUT .= ">\n<TR>\n<TD";
85 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
86 $OUT .= " class=\"".$CLASS."\">";
90 // Close a table (you may want to add some footer stuff here)
91 function CLOSE_TABLE($ADD="") {
92 OUTPUT_HTML(" </TD>\n</TR>");
93 if (!empty($ADD)) OUTPUT_HTML($ADD);
94 OUTPUT_HTML("</TABLE>");
97 // Output HTML code directly or "render" it. You addionally switch the new-line character off
98 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
99 // Some global variables
100 global $OUTPUT, $footer, $CSS;
102 // Do we have HTML-Code here?
104 // Yes, so we handle it as you have configured
108 // That's why you don't need any \n at the end of your HTML code... :-)
109 if (_OB_CACHING == "on") {
110 // Output into PHP's internal buffer
113 // That's why you don't need any \n at the end of your HTML code... :-)
114 if ($NEW_LINE) echo "\n";
116 // Render mode for old or lame servers...
119 // That's why you don't need any \n at the end of your HTML code... :-)
120 if ($NEW_LINE) $OUTPUT .= "\n";
125 // If we are switching from render to direct output rendered code
126 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
128 // The same as above... ^
130 if ($NEW_LINE) echo "\n";
134 // Huh, something goes wrong or maybe you have edited config.php ???
135 die ("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
138 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
139 // Output cached HTML code
140 $OUTPUT = ob_get_contents();
142 // Clear output buffer for later output
145 // Extension "rewrite" installed?
146 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
147 $OUTPUT = REWRITE_LINKS($OUTPUT);
150 // Compile and run finished rendered HTML code
151 while (strpos($OUTPUT, '{!') > 0) {
152 // Prepare the content and eval() it...
154 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
157 // Was that eval okay?
158 if (empty($newContent)) {
159 // Something went wrong!
160 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
162 $OUTPUT = $newContent;
165 // Output code here, DO NOT REMOVE! ;-)
167 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
168 // Rewrite links when rewrite extension is active
169 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
170 $OUTPUT = REWRITE_LINKS($OUTPUT);
173 // Compile and run finished rendered HTML code
174 while (strpos($OUTPUT, '{!') > 0) {
175 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
179 // Output code here, DO NOT REMOVE! ;-)
184 // Output the raw HTML code
185 function OUTPUT_RAW ($HTML) {
186 // Output stripped HTML code to avoid broken JavaScript code, etc.
187 echo stripslashes(stripslashes($HTML));
189 // Flush the output if only _OB_CACHING is not "on"
190 if (_OB_CACHING != "on") {
196 // Add a fatal error message to the queue array
197 function ADD_FATAL ($message, $extra="") {
200 // Regular text message to add to $FATAL
203 // $message is text with a mask plus extras to insert into the text
204 $FATAL[] = sprintf($message, $extra);
208 // Load a template file and return it's content (only it's name; do not use ' or ")
209 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
210 // Add more variables which you want to use in your template files
211 global $DATA, $_CONFIG, $username;
213 // Make all template names lowercase
214 $template = strtolower($template);
216 // Count the template load
217 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
218 $_CONFIG['num_templates']++;
222 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
224 // @DEPRECATED Try to remove this if() block
225 if ($template == "member_support_form") {
226 // Support request of a member
227 $result = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
228 array($GLOBALS['userid']), __FILE__, __LINE__);
230 // @TODO Merge this data into $content
231 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
234 $gender = TRANSLATE_GENDER($gender);
236 // Insert data if content is an array
237 if (is_array($content)) {
238 // Please switch to $content[bla] in all your templates! Direct
239 // variables are deprecated as of 09/13/2008.
240 $content['gender'] = $gender;
241 $content['surname'] = $surname;
242 $content['family'] = $family;
243 $content['email'] = $email;
247 SQL_FREERESULT($result);
250 // Generate date/time string
251 $date_time = MAKE_DATETIME(time(), "1");
254 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
257 // Check for admin/guest/member templates
258 if (strpos($template, "admin_") > -1) {
259 // Admin template found
261 } elseif (strpos($template, "guest_") > -1) {
262 // Guest template found
264 } elseif (strpos($template, "member_") > -1) {
265 // Member template found
267 } elseif (strpos($template, "install_") > -1) {
268 // Installation template found
270 } elseif (strpos($template, "ext_") > -1) {
271 // Extension template found
273 } elseif (strpos($template, "la_") > -1) {
274 // "Logical-area" template found
277 // Test for extension
278 $test = substr($template, 0, strpos($template, "_"));
279 if (EXT_IS_ACTIVE($test)) {
280 // Set extra path to extension's name
285 ////////////////////////
286 // Generate file name //
287 ////////////////////////
288 $file = $BASE.$MODE.$template.".tpl";
290 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
291 // Select what depended header/footer template file for admin/guest/member area
292 $file2 = sprintf("%s%s%s_%s.tpl",
296 SQL_ESCAPE($GLOBALS['what'])
300 if (FILE_READABLE($file2)) $file = $file2;
302 // Remove variable from memory
306 // Does the special template exists?
307 if (!FILE_READABLE($file)) {
308 // Reset to default template
309 $file = $BASE.$template.".tpl";
312 // Now does the final template exists?
313 if (FILE_READABLE($file)) {
314 // The local file does exists so we load it. :)
315 $tmpl_file = implode("", file($file));
317 // Replace ' to our own chars to preventing them being quoted
318 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
320 // Do we have to compile the code?
322 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
324 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
327 // Simply return loaded code
331 // Add surrounding HTML comments to help finding bugs faster
332 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
333 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
334 // Only admins shall see this warning or when installation mode is active
335 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
336 (".basename($file).")<br />
339 <pre>".print_r($content, true)."</pre>
341 <pre>".print_r($DATA, true)."</pre>
345 // Do we have some content to output or return?
347 // Not empty so let's put it out! ;)
349 // Return the HTML code
355 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
356 // Warning, empty output!
357 return "E:".$template."<br />\n";
361 // Send mail out to an email address
362 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
363 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
365 // Compile subject line (for POINTS constant etc.)
366 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
370 if ((!eregi("@", $TO)) && ($TO > 0)) {
371 // Value detected, is the message extension installed?
372 if (EXT_IS_ACTIVE("msg")) {
373 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
376 // Load email address
377 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
378 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
380 // Does the user exist?
381 if (SQL_NUMROWS($result_email)) {
382 // Load email address
383 list($TO) = SQL_FETCHROW($result_email);
390 SQL_FREERESULT($result_email);
392 } elseif ("$TO" == "0") {
396 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
398 // Check for PHPMailer or debug-mode
399 if (!CHECK_PHPMAILER_USAGE()) {
400 // Not in PHPMailer-Mode
402 // Load email header template
403 $FROM = LOAD_EMAIL_TEMPLATE("header");
406 $FROM .= LOAD_EMAIL_TEMPLATE("header");
408 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
410 // Load email header template
411 $FROM = LOAD_EMAIL_TEMPLATE("header");
414 $FROM .= LOAD_EMAIL_TEMPLATE("header");
419 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
422 // Fix HTML parameter (default is no!)
423 if (empty($HTML)) $HTML = "N";
424 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
425 // In debug mode we want to display the mail instead of sending it away so we can debug this part
427 ".htmlentities(trim($FROM))."
429 Subject : ".$SUBJECT."
434 if (defined('DEBUG_MAIL')) DEBUG_LOG(__FUNCTION__.":to={$TO},subject={$SUBJECT},msg={$MSG}");
435 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
436 // Send mail as HTML away
437 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
438 } elseif (!empty($TO)) {
440 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
441 } elseif ($HTML == "N") {
443 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
447 // Check if legacy or PHPMailer command
449 function CHECK_PHPMAILER_USAGE() {
450 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
454 * Send out a raw email with PHPMailer class or legacy mail() command
456 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
457 // Shall we use PHPMailer class or legacy mode?
458 if (CHECK_PHPMAILER_USAGE()) {
459 // Use PHPMailer class with SMTP enabled
460 require_once(PATH."inc/phpmailer/class.phpmailer.php");
461 require_once(PATH."inc/phpmailer/class.smtp.php");
464 $mail = new PHPMailer();
465 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
468 $mail->SMTPAuth = true;
469 $mail->Host = SMTP_HOSTNAME;
471 $mail->Username = SMTP_USER;
472 $mail->Password = SMTP_PASSWORD;
474 $mail->From = WEBMASTER;
478 $mail->FromName = MAIN_TITLE;
479 $mail->Subject = $subject;
480 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
482 $mail->AltBody = "Your mail program required HTML support to read this mail!";
483 $mail->WordWrap = 70;
486 $mail->Body = html_entity_decode($msg);
488 $mail->AddAddress($to, "");
489 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
490 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
491 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
494 // Use legacy mail() command
495 @mail($to, $subject, html_entity_decode($msg), $from);
500 // Generate a password in a specified length or use default password length
501 function GEN_PASS($LEN = 0) {
503 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
505 // Initialize array with all allowed chars
506 $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,-,+,_,/");
508 // Initialize randomizer
509 mt_srand((double) microtime() * 1000000);
511 // Start creating password
513 for ($i = 0; $i < $LEN; $i++) {
514 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
517 // When the size is below 40 we can also add additional security by scrambling it
518 if (strlen($PASS) <= 40) {
519 // Also scramble the password
520 $PASS = scrambleString($PASS);
523 // Return the password
527 function MAKE_DATETIME ($time, $mode="0")
531 return NEVER_HAPPENED;
533 // Filter out numbers
534 $time = bigintval($time);
537 switch (GET_LANGUAGE())
539 case "de": // German date / time format
541 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
542 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
543 case "2": $ret = date("d.m.Y|H:i", $time); break;
544 case "3": $ret = date("d.m.Y", $time); break;
548 default: // Default is the US date / time format!
550 case "0": $ret = date("r", $time); break;
551 case "1": $ret = date("Y-m-d - g:i A", $time); break;
552 case "2": $ret = date("y-m-d|H:i", $time); break;
553 case "3": $ret = date("y-m-d", $time); break;
559 // Translates the american decimal dot into a german comma
560 function TRANSLATE_COMMA ($dotted, $cut=true) {
563 // Default is 3 you can change this in admin area "Misc -> Misc Options"
564 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
565 $maxComma = $_CONFIG['max_comma'];
569 // Test for commata if in cut-mode
570 $com = explode(".", $dotted);
571 if (count($com) > 1) {
572 // Commata found, so only zeros?
573 if ($com[1] == str_repeat("0", strlen($com[1]))) {
574 // Only zeros, so display only one
578 // Don't display commatas even if there are none... ;-)
584 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
587 switch (GET_LANGUAGE()) {
589 $dotted = number_format($dotted, $maxComma, ",", ".");
593 $dotted = number_format($dotted, $maxComma, ".", ",");
597 // Return translated value
602 function DEREFERER ($URL) {
603 // Don't de-refer our own links!
604 if (substr($URL, 0, strlen(URL)) != URL) {
605 // De-refer this link
606 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
614 function TRANSLATE_GENDER ($gender) {
617 case "M": $ret = GENDER_M; break;
618 case "F": $ret = GENDER_F; break;
619 case "C": $ret = GENDER_C; break;
620 default : $ret = $gender; break;
625 function FRAMETESTER($URL) {
626 // Prepare frametester URL
627 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
629 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
631 return $frametesterUrl;
634 function SELECTION_COUNT($array) {
636 if (is_array($array)) {
637 foreach ($array as $key => $sel) {
638 if (!empty($sel)) $ret++;
644 function IMG_CODE ($code, $type, $DATA, $uid) {
645 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
648 function TRANSLATE_STATUS($status) {
652 $ret = ACCOUNT_UNCONFIRMED;
656 $ret = ACCOUNT_CONFIRMED;
660 $ret = ACCOUNT_LOCKED;
665 $ret = ACCOUNT_DELETED;
669 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
675 function GET_LANGUAGE() {
676 if (!empty($_GET['mx_lang'])) {
677 // Accept only first 2 chars
678 $lang = substr($_GET['mx_lang'], 0, 2);
684 // Set default return value to default language from config
687 // Check GET variable and cookie
689 // Check if main language file does exist
690 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
691 // Okay found, so let's update cookies
694 } elseif (!isSessionVariableSet('mx_lang')) {
695 // Return stored value from cookie
696 $ret = get_session('mx_lang');
698 // Fixes a warning before the session has the mx_lang constant
699 if (empty($ret)) $ret = DEFAULT_LANG;
704 function SET_LANGUAGE($lang) {
707 // Accept only first 2 chars!
708 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
711 set_session("mx_lang", $lang);
714 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
715 global $DATA, $_CONFIG, $REPLACER;
717 // Make sure all template names are lowercase!
718 $template = strtolower($template);
720 // Default "nickname" if extension is not installed
723 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
724 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
726 // Prepare IP number and User Agent
727 $REMOTE_ADDR = GET_REMOTE_ADDR();
728 $HTTP_USER_AGENT = GET_USER_AGENT();
733 // Is the admin logged in?
736 $ADMIN = GET_ADMIN_EMAIL(get_session('admin_login'));
739 // Neutral email address is default
742 // Expiration in a nice output format
743 if ($_CONFIG['auto_purge'] == 0) {
744 // Will never expire!
745 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
746 } elseif (function_exists('CREATE_FANCY_TIME')) {
747 // Create nice date string
748 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
751 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
754 // Is content an array?
755 if (is_array($content)) {
756 // Add expiration to array, $EXPIRATION is now deprecated!
757 $content['expiration'] = $EXPIRATION;
761 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template}<br />\n";
763 if (EXT_IS_ACTIVE("nickname")) {
764 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
766 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
767 array(bigintval($UID)), __FILE__, __LINE__);
769 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
771 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
772 array(bigintval($UID)), __FILE__, __LINE__);
775 // Is content an array?
776 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content[]=".gettype($content)."<br />\n";
777 if (is_array($content)) {
778 // Fetch and migrate data
779 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
780 $content = array_merge($content, SQL_FETCHARRAY($result));
781 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
785 SQL_FREERESULT($result);
788 // Translate M to male or F to female if present
789 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
791 // Overwrite email from data if present
792 if (isset($content['email'])) $email = $content['email'];
794 // Store email for some functions in global data array
795 $DATA['email'] = $email;
798 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
800 // Check for admin/guest/member templates
801 if (strpos($template, "admin_") > -1) {
802 // Admin template found
803 $file = $BASE."admin/".$template.".tpl";
804 } elseif (strpos($template, "guest_") > -1) {
805 // Guest template found
806 $file = $BASE."guest/".$template.".tpl";
807 } elseif (strpos($template, "member_") > -1) {
808 // Member template found
809 $file = $BASE."member/".$template.".tpl";
811 // Test for extension
812 $test = substr($template, 0, strpos($template, "_"));
813 if (EXT_IS_ACTIVE($test)) {
814 // Set extra path to extension's name
815 $file = $BASE.$test."/".$template.".tpl";
817 // No special filename
818 $file = $BASE.$template.".tpl";
822 // Does the special template exists?
823 if (!FILE_READABLE($file)) {
824 // Reset to default template
825 $file = $BASE.$template.".tpl";
828 // Now does the final template exists?
830 if (FILE_READABLE($file)) {
831 // The local file does exists so we load it. :)
832 $tmpl_file = implode("", file($file));
833 $tmpl_file = addslashes($tmpl_file);
836 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
838 } elseif (!empty($template)) {
839 // Template file not found!
840 $newContent = TEMPLATE_404.": ".$template."<br />
842 <pre>".print_r($content, true)."</pre>
844 <pre>".print_r($DATA, true)."</pre>
847 // Debug mode not active? Then remove the HTML tags
848 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
850 // No template name supplied!
851 $newContent = NO_TEMPLATE_SUPPLIED;
854 // Is there some content?
855 if (empty($newContent)) {
857 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
858 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
861 // Return compiled content
862 return COMPILE_CODE($newContent);
865 function MAKE_TIME($H, $M, $S, $stamp) {
866 // Extract day, month and year from given timestamp
867 $DAY = date("d", $stamp);
868 $MONTH = date("m", $stamp);
869 $YEAR = date('Y', $stamp);
871 // Create timestamp for wished time which depends on extracted date
872 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
875 function LOAD_URL($URL, $addUrlData=true) {
876 global $CSS, $_CONFIG, $footer;
878 // Check if http(s):// is there
879 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
880 // Make all URLs full-qualified
884 // Compile out URI codes
885 $URL = COMPILE_CODE($URL);
888 $OUTPUT = ob_get_contents();
890 // Clear it only if there is content
891 if (!empty($OUTPUT)) {
895 // Add some data to URL if cookies are not accepted
896 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
898 // Probe for bot from search engine
899 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
900 // Search engine bot detected so let's rewrite many chars for the link
901 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
903 // Output new location link as anchor
904 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
905 } elseif (!headers_sent()) {
906 // Load URL when headers are not sent
909 debug_print_backtrace();
910 die("</pre>URL={$URL}");
912 @header ("Location: ".str_replace("&", "&", $URL));
914 // Output error message
915 include(PATH."inc/header.php");
916 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
917 include(PATH."inc/footer.php");
922 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
923 global $SEC_CHARS, $URL_CHARS;
924 // Is the code a string?
925 if (!is_string($code)) {
926 // Silently return it
932 // Select smaller set of chars to replace when we e.g. want to compile URLs
933 if (!$full) $ARRAY = $URL_CHARS;
937 // BEFORE 0.2.1 : Language and data constants
938 // WITH 0.2.1+ : Only language constants
939 $code = str_replace('{--','".', str_replace('--}','."', $code));
941 // BEFORE 0.2.1 : Not used
942 // WITH 0.2.1+ : Data constants
943 $code = str_replace('{!','".', str_replace("!}", '."', $code));
946 // Compile QUOT and other non-HTML codes
947 foreach ($ARRAY['to'] as $k => $to) {
948 // Do the reversed thing as in inc/libs/security_functions.php
949 $code = str_replace($to, $ARRAY['from'][$k], $code);
952 // But shall I keep simple quotes for later use?
953 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
955 // Find $content[bla][blub] entries
956 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
958 // Are some matches found?
959 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
960 // Replace all matches
961 $matchesFound = array();
962 foreach ($matches[0] as $key => $match) {
963 // Fuzzy look has failed by default
966 // Fuzzy look on match if already found
967 foreach ($matchesFound as $found => $set) {
969 $test = substr($found, 0, strlen($match));
971 // Does this entry exist?
972 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
973 if ($test == $match) {
975 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
982 if ($fuzzyFound) continue;
984 // Take all string elements
985 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
986 // Replace it in the code
987 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
988 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
989 $code = str_replace($match, "\".".$newMatch.".\"", $code);
990 $matchesFound[$key."_".$matches[4][$key]] = 1;
991 $matchesFound[$match] = 1;
992 } elseif (!isset($matchesFound[$match])) {
994 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
995 $code = str_replace($match, "\".".$match.".\"", $code);
996 $matchesFound[$match] = 1;
1001 // Return compiled code
1005 /************************************************************************
1007 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1008 * $a_sort sortiert: *
1010 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1011 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1012 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1013 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1014 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1016 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1017 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1018 * Sie, dass es doch nicht so schwer ist! :-) *
1020 ************************************************************************/
1021 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1024 while ($primary_key < count($a_sort)) {
1025 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1026 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1029 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1030 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1031 } elseif ($key != $key2) {
1032 // Sort numbers (E.g.: 9 < 10)
1033 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1034 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1038 // We have found two different values, so let's sort whole array
1039 foreach ($dummy as $sort_key => $sort_val) {
1040 $t = $dummy[$sort_key][$key];
1041 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1042 $dummy[$sort_key][$key2] = $t;
1053 // Write back sorted array
1057 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1059 global $MONTH_DESCR; $OUT = "";
1062 // This is a yes/no selection only!
1063 if ($id > 0) $prefix .= "[".$id."]";
1064 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1068 // Begin with regular selection box here
1069 if (!empty($prefix)) $prefix .= "_";
1071 if ($id > 0) $type2 .= "[".$id."]";
1072 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1077 for ($idx = 1; $idx < 32; $idx++)
1079 $OUT .= "<OPTION value=\"".$idx."\"";
1080 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1081 $OUT .= ">".$idx."</OPTION>\n";
1085 case "month": // Month
1086 foreach ($MONTH_DESCR as $month => $descr)
1088 $OUT .= "<OPTION value=\"".$month."\"";
1089 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1090 $OUT .= ">".$descr."</OPTION>\n";
1094 case "year": // Year
1096 $YEAR = date('Y', time());
1098 // Check if the default value is larger than minimum and bigger than actual year
1099 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1101 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1103 $OUT .= "<OPTION value=\"".$idx."\"";
1104 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1105 $OUT .= ">".$idx."</OPTION>\n";
1108 elseif ($DEFAULT == -1)
1110 // Current year minus 1
1111 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1113 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1118 // Get current year and subtract 16 (for erotic content)
1119 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1120 $YEAR = date('Y', time()) - 16;
1121 for ($idx = 1930; $idx <= $YEAR; $idx++)
1123 $OUT .= "<OPTION value=\"".$idx."\"";
1124 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1125 $OUT .= ">".$idx."</OPTION>\n";
1132 for ($idx = 0; $idx < 60; $idx+=5) {
1133 if (strlen($idx) == 1) $idx = "0".$idx;
1134 $OUT .= "<OPTION value=\"".$idx."\"";
1135 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1136 $OUT .= ">".$idx."</OPTION>\n";
1141 for ($idx = 0; $idx < 24; $idx++) {
1142 if (strlen($idx) == 1) $idx = "0".$idx;
1143 $OUT .= "<OPTION value=\"".$idx."\"";
1144 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1145 $OUT .= ">".$idx."</OPTION>\n";
1150 $OUT .= "<OPTION value=\"Y\"";
1151 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1152 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1153 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1154 $OUT .= ">".NO."</OPTION>\n";
1157 $OUT .= " </SELECT>\n";
1161 function TRANSLATE_YESNO($yn)
1165 case 'Y': $yn = YES; break;
1166 case 'N': $yn = NO; break;
1167 default : $yn = "??? (".$yn.")"; break;
1172 // Deprecated : $length
1175 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1178 // Fix missing _MAX constant
1179 if (!defined('_MAX')) define('_MAX', 15235);
1181 // Build server string
1182 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1185 $keys = SITE_KEY.":".DATE_KEY;
1186 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1187 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1188 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1189 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1191 // Build string from misc data
1192 $data = $code.":".$uid.":".$DATA;
1194 // Add more additional data
1195 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1196 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1197 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1198 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1199 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1200 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1202 // Calculate number for generating the code
1203 $a = $code + _ADD - 1;
1205 if (isset($_CONFIG['master_hash'])) {
1206 // Generate hash with master salt from modula of number with the prime number and other data
1207 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1209 // Create number from hash
1210 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1212 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1213 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1215 // Create number from hash
1216 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1219 // At least 10 numbers shall be secure enought!
1220 $len = $_CONFIG['code_length'];
1221 if ($len == 0) $len = $length;
1222 if ($len == 0) $len = 10;
1224 // Cut off requested counts of number
1225 $return = substr(str_replace('.', "", $rcode), 0, $len);
1227 // Done building code
1230 // Does only allow numbers
1231 function bigintval($num, $castValue = true) {
1232 // Filter all numbers out
1233 $ret = preg_replace("/[^0123456789]/", "", $num);
1236 if ($castValue) $ret = (double)$ret;
1238 // Has the whole value changed?
1239 if ("".$ret."" != "".$num."") {
1241 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1247 // Insert the code in $img_code into jpeg or PNG image
1248 function GENERATE_IMAGE($img_code, $header=true) {
1251 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1252 // Stop execution of function here because of over-sized code length
1254 } elseif (!$header) {
1255 // Return in an HTML code code
1256 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1260 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1261 if (FILE_READABLE($img)) {
1262 // Switch image type
1263 switch ($_CONFIG['img_type'])
1266 // Okay, load image and hide all errors
1267 $image = @imagecreatefromjpeg($img);
1271 // Okay, load image and hide all errors
1272 $image = @imagecreatefrompng($img);
1276 // Exit function here
1280 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1281 $text_color = imagecolorallocate($image, 0, 0, 0);
1283 // Insert code into image
1284 imagestring($image, 5, 14, 2, $img_code, $text_color);
1286 // Return to browser
1287 header ("Content-Type: image/".$_CONFIG['img_type']);
1289 // Output image with matching image factory
1290 switch ($_CONFIG['img_type']) {
1291 case "jpg": imagejpeg($image); break;
1292 case "png": imagepng($image); break;
1295 // Remove image from memory
1296 imagedestroy($image);
1298 // Create selection box or array of splitted timestamp
1299 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1302 // Calculate 2-seconds timestamp
1303 $stamp = round($timestamp);
1305 // Do we have a leap year?
1307 $TEST = date('Y', time()) / 4;
1308 $M1 = date("m", time());
1309 $M2 = date("m", (time() + $stamp));
1311 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1312 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = $_CONFIG['one_day'];
1314 // First of all years...
1315 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1317 $M = abs(floor($stamp / 2628000 - $Y * 12));
1319 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / $_CONFIG['one_day']) / 7) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) / 7)));
1321 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day'])) - $W * 7));
1323 $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));
1325 $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));
1326 // And at last seconds...
1327 $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));
1329 // Is seconds zero and time is < 60 seconds?
1330 if (($s == 0) && ($stamp < 60)) {
1332 $s = round($timestamp);
1336 // Now we convert them in seconds...
1338 if ($return_array) {
1339 // Just put all data in an array for later use
1351 $OUT = "<DIV align=\"".$align."\">\n";
1352 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1355 if (ereg('Y', $display) || (empty($display))) {
1356 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1359 if (ereg("M", $display) || (empty($display))) {
1360 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1363 if (ereg("W", $display) || (empty($display))) {
1364 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1367 if (ereg("D", $display) || (empty($display))) {
1368 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1371 if (ereg("h", $display) || (empty($display))) {
1372 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1375 if (ereg("m", $display) || (empty($display))) {
1376 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1379 if (ereg("s", $display) || (empty($display))) {
1380 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1386 if (ereg('Y', $display) || (empty($display))) {
1387 // Generate year selection
1388 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1389 for ($idx = 0; $idx <= 10; $idx++) {
1390 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1391 if ($idx == $Y) $OUT .= " selected default";
1392 $OUT .= ">".$idx."</OPTION>\n";
1394 $OUT .= " </SELECT></TD>\n";
1396 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1399 if (ereg("M", $display) || (empty($display))) {
1400 // Generate month selection
1401 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1402 for ($idx = 0; $idx <= 11; $idx++)
1404 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1405 if ($idx == $M) $OUT .= " selected default";
1406 $OUT .= ">".$idx."</OPTION>\n";
1408 $OUT .= " </SELECT></TD>\n";
1410 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1413 if (ereg("W", $display) || (empty($display))) {
1414 // Generate week selection
1415 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1416 for ($idx = 0; $idx <= 4; $idx++) {
1417 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1418 if ($idx == $W) $OUT .= " selected default";
1419 $OUT .= ">".$idx."</OPTION>\n";
1421 $OUT .= " </SELECT></TD>\n";
1423 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1426 if (ereg("D", $display) || (empty($display))) {
1427 // Generate day selection
1428 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1429 for ($idx = 0; $idx <= 31; $idx++) {
1430 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1431 if ($idx == $D) $OUT .= " selected default";
1432 $OUT .= ">".$idx."</OPTION>\n";
1434 $OUT .= " </SELECT></TD>\n";
1436 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1439 if (ereg("h", $display) || (empty($display))) {
1440 // Generate hour selection
1441 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1442 for ($idx = 0; $idx <= 23; $idx++) {
1443 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1444 if ($idx == $h) $OUT .= " selected default";
1445 $OUT .= ">".$idx."</OPTION>\n";
1447 $OUT .= " </SELECT></TD>\n";
1449 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1452 if (ereg("m", $display) || (empty($display))) {
1453 // Generate minute selection
1454 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1455 for ($idx = 0; $idx <= 59; $idx++) {
1456 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1457 if ($idx == $m) $OUT .= " selected default";
1458 $OUT .= ">".$idx."</OPTION>\n";
1460 $OUT .= " </SELECT></TD>\n";
1462 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1465 if (ereg("s", $display) || (empty($display))) {
1466 // Generate second selection
1467 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1468 for ($idx = 0; $idx <= 45; $idx += 15) {
1469 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1470 if ($idx == $s) $OUT .= " selected default";
1471 $OUT .= ">".$idx."</OPTION>\n";
1473 $OUT .= " </SELECT></TD>\n";
1475 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1478 $OUT .= "</TABLE>\n";
1480 // Return generated HTML code
1485 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1489 // Do we have a leap year?
1491 $TEST = date('Y', time()) / 4;
1492 $M1 = date("m", time());
1493 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1494 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = $_CONFIG['one_day'];
1495 // First add years...
1496 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1498 $ret += $POST[$prefix."_mo"] * 2628000;
1500 $ret += $POST[$prefix."_we"] * 604800;
1502 $ret += $POST[$prefix."_da"] * 86400;
1504 $ret += $POST[$prefix."_ho"] * 3600;
1506 $ret += $POST[$prefix."_mi"] * 60;
1507 // And at last seconds...
1508 $ret += $POST[$prefix."_se"];
1509 // Return calculated value
1512 // Sends out mail to all administrators
1513 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1514 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1515 // Trim template name
1516 $template = trim($template);
1518 // Load email template
1519 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1521 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1522 // Older version detected!
1523 return SEND_ADMIN_EMAILS($subj, $msg);
1526 // Check which admin shall receive this mail
1527 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1528 array($template), __FILE__, __LINE__);
1529 if (SQL_NUMROWS($result) == 0) {
1530 // Create new entry (to all admins)
1531 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1532 array($template), __FILE__, __LINE__);
1534 // Load admin IDs...
1536 while(list($aid) = SQL_FETCHROW($result)) {
1541 SQL_FREERESULT($result);
1543 // "implode" IDs and query string
1544 $aid = implode(",", $aids);
1546 // Add line to userlog
1547 USERLOG_ADD_LINE($subj, $msg, $UID);
1549 } elseif ($aid == "0") {
1550 // Select all email adresses
1551 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1553 // If Admin-ID is not "to-all" select
1554 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1558 // Load email addresses and send away
1559 while (list($email) = SQL_FETCHROW($result)) {
1560 SEND_EMAIL($email, $subj, $msg);
1564 SQL_FREERESULT($result);
1567 function CREATE_FANCY_TIME($stamp) {
1568 // Get data array with years/months/weeks/days/...
1569 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1571 foreach($data as $k => $v) {
1573 // Value is greater than 0 "eval" data to return string
1574 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1580 // Do we have something there?
1581 if (strlen($ret) > 0) {
1582 // Remove leading commata and space
1583 $ret = substr($ret, 2);
1586 $ret = "0 "._SECONDS;
1589 // Return fancy time string
1593 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1594 $SEP = ""; $TOP = "";
1597 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1601 for ($page = 1; $page <= $PAGES; $page++) {
1602 // Is the page currently selected or shall we generate a link to it?
1603 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1604 // Is currently selected, so only highlight it
1605 $NAV .= "<STRONG>-";
1607 // Open anchor tag and add base URL
1608 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1610 // Add userid when we shall show all mails from a single member
1611 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1613 // Close open anchor tag
1617 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1618 // Is currently selected, so only highlight it
1619 $NAV .= "-</STRONG>";
1625 // Add seperator if we have not yet reached total pages
1626 if ($page < $PAGES) $NAV .= " | ";
1629 // Define constants only once
1630 if (!defined('__NAV_OUTPUT')) {
1631 define('__NAV_OUTPUT' , $NAV);
1632 define('__NAV_COLSPAN', $colspan);
1633 define('__NAV_TOP' , $TOP);
1634 define('__NAV_SEP' , $SEP);
1637 // Load navigation template
1638 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1641 // Return generated HTML-Code
1649 // Extract host from script name
1650 function EXTRACT_HOST (&$script) {
1651 // Use default SERVER_URL by default... ;) So?
1654 // Is this URL valid?
1655 if (substr($script, 0, 7) == "http://") {
1656 // Use the hostname from script URL as new hostname
1657 $url = substr($script, 7);
1658 $extract = explode("/", $url);
1660 // Done extracting the URL :)
1663 // Extract host name
1664 $host = str_replace("http://", "", $url);
1665 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1667 // Generate relative URL
1668 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1669 if (substr(strtolower($script), 0, 7) == "http://") {
1670 // But only if http:// is in front!
1671 $script = substr($script, (strlen($url) + 7));
1672 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1674 $script = substr($script, (strlen($url) + 8));
1677 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1678 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1684 // Send a GET request
1685 function GET_URL ($script) {
1686 // Compile the script name
1687 $script = COMPILE_CODE($script);
1689 // Extract host name from script
1690 $host = EXTRACT_HOST($script);
1692 // Generate GET request header
1693 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1694 $request .= "Host: " . $host . "\r\n";
1695 $request .= "Referer: " . URL . "/admin.php\r\n";
1696 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1697 $request .= "Content-Type: text/plain\r\n";
1698 $request .= "Cache-Control: no-cache\r\n";
1699 $request .= "Connection: Close\r\n\r\n";
1701 // Send the raw request
1702 $response = SEND_RAW_REQUEST($host, $request);
1704 // Return the result to the caller function
1708 // Send a POST request
1709 function POST_URL ($script, $postData) {
1710 // Is postData an array?
1711 if (!is_array($postData)) {
1713 return array("", "", "");
1716 // Compile the script name
1717 $script = COMPILE_CODE($script);
1719 // Extract host name from script
1720 $host = EXTRACT_HOST($script);
1722 // Construct request
1723 $data = http_build_query($postData, '','&');
1725 // Generate POST request header
1726 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1727 $request .= "Host: " . $host . "\r\n";
1728 $request .= "Referer: " . URL . "/admin.php\r\n";
1729 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1730 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1731 $request .= "Content-length: " . strlen($data) . "\r\n";
1732 $request .= "Cache-Control: no-cache\r\n";
1733 $request .= "Connection: Close\r\n\r\n";
1736 // Send the raw request
1737 $response = SEND_RAW_REQUEST($host, $request);
1739 // Return the result to the caller function
1743 // Sends a raw request to another host
1744 function SEND_RAW_REQUEST ($host, $request) {
1748 $response = array("", "", "");
1750 // Default is not to use proxy
1753 // Are proxy settins set?
1754 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1760 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1762 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1764 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1768 if (!is_resource($fp)) {
1775 // Generate CONNECT request header
1776 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1777 $proxyTunnel .= "Host: ".$host."\r\n";
1779 // Use login data to proxy? (username at least!)
1780 if (!empty($_CONFIG['proxy_username'])) {
1782 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1783 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1786 // Add last new-line
1787 $proxyTunnel .= "\r\n";
1788 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1791 fputs($fp, $proxyTunnel);
1795 // No response received
1799 // Read the first line
1800 $resp = trim(fgets($fp, 10240));
1801 $respArray = explode(" ", $resp);
1802 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1803 // Invalid response!
1809 fputs($fp, $request);
1813 $response[] = trim(fgets($fp, 1024));
1819 // Skip first empty lines
1821 foreach ($resp as $idx => $line) {
1823 $line = trim($line);
1825 // Is this line empty?
1828 array_shift($response);
1830 // Abort on first non-empty line
1835 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1837 // Proxy agent found?
1838 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1839 // Proxy header detected, so remove two lines
1840 array_shift($response);
1841 array_shift($response);
1844 // Was the request successfull?
1845 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1846 // Not found / access forbidden
1847 $response = array("", "", "");
1853 // Taken from www.php.net eregi() user comments
1854 function VALIDATE_EMAIL($email) {
1856 $email = COMPILE_CODE($email);
1858 // Check first part of email address
1859 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1862 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1865 $regex = "^".$first."@".$domain."$";
1867 // Return check result
1868 return eregi($regex, $email);
1870 // Function taken from user comments on www.php.net / function eregi()
1871 function VALIDATE_URL ($URL, $compile=true) {
1872 // Trim URL a little
1873 $URL = trim(urldecode($URL));
1874 //* DEBUG: */ echo $URL."<br />";
1876 // Compile some chars out...
1877 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1878 //* DEBUG: */ echo $URL."<br />";
1880 // Check for the extension filter
1881 if (EXT_IS_ACTIVE("filter")) {
1882 // Use the extension's filter set
1883 return FILTER_VALIDATE_URL($URL, false);
1886 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1887 // https:// in front of the URLs
1888 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1891 function MEMBER_ACTION_LINKS($uid, $status="") {
1892 // Define all main targets
1893 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1895 // Begin of navigation links
1896 $eval = "\$OUT = \"[ ";
1898 foreach ($TARGETS as $tar) {
1899 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1900 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1901 if (($tar == "lock_user") && ($status == "LOCKED")) {
1902 // Locked accounts shall be unlocked
1903 $eval .= "UNLOCK_USER";
1905 // All other status is fine
1906 $eval .= strtoupper($tar);
1908 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1909 if (($tar == "lock_user") && ($status == "LOCKED")) {
1910 // Locked accounts shall be unlocked
1911 $eval .= "UNLOCK_USER";
1913 // All other status is fine
1914 $eval .= strtoupper($tar);
1916 $eval .= ".\"</A></SPAN> | ";
1919 // Finish navigation link
1920 $eval = substr($eval, 0, -7)."]\";";
1926 // Function for backward-compatiblity
1927 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1928 // Load it from the register extension
1929 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1931 // Generate an email link
1932 function CREATE_EMAIL_LINK($email, $table="admins") {
1933 // Default email link (INSECURE! Spammer can read this by harvester programs)
1934 $EMAIL = "mailto:".$email;
1936 // Check for several extensions
1937 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1938 // Create email link for contacting admin in guest area
1939 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1940 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1941 // Create email link for contacting a member within admin area (or later in other areas, too?)
1942 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1943 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1944 // Create email link to contact sponsor within admin area (or like the link above?)
1945 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1948 // Shall I close the link when there is no admin?
1949 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1951 // Return email link
1954 // Generate a hash for extra-security for all passwords
1955 function generateHash ($plainText, $salt = "") {
1956 global $_CONFIG, $_SERVER;
1958 // Is the required extension "sql_patches" there and a salt is not given?
1959 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
1960 // Extension sql_patches is missing/outdated so we return the plain text
1964 // Do we miss an arry element here?
1965 if (!isset($_CONFIG['file_hash'])) {
1967 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1968 debug_print_backtrace();
1972 // When the salt is empty build a new one, else use the first x configured characters as the salt
1974 // Build server string
1975 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1978 $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'];
1981 $data = $plainText.":".uniqid(rand(), true).":".time();
1983 // Calculate number for generating the code
1984 $a = time() + _ADD - 1;
1986 // Generate SHA1 sum from modula of number and the prime number
1987 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1988 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1989 $sha1 = scrambleString($sha1);
1990 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1991 //* DEBUG: */ $sha1b = descrambleString($sha1);
1992 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1994 // Generate the password salt string
1995 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1996 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1999 $salt = substr($salt, 0, $_CONFIG['salt_length']);
2000 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2004 return $salt.sha1($salt.$plainText);
2007 function scrambleString($str) {
2013 // Final check, in case of failture it will return unscrambled string
2014 if (strlen($str) > 40) {
2015 // The string is to long
2017 } elseif (strlen($str) == 40) {
2019 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2021 // Generate new numbers
2022 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2025 // Scramble string here
2026 //* DEBUG: */ echo "***Original=".$str."***<br />";
2027 for ($idx = 0; $idx < strlen($str); $idx++) {
2028 // Get char on scrambled position
2029 $char = substr($str, $scrambleNums[$idx], 1);
2031 // Add it to final output string
2032 $scrambled .= $char;
2035 // Return scrambled string
2036 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2040 function descrambleString($str) {
2042 // Scramble only 40 chars long strings
2043 if (strlen($str) != 40) return $str;
2045 // Load numbers from config
2046 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2049 if (count($scrambleNums) != 40) return $str;
2051 // Begin descrambling
2052 $orig = str_repeat(" ", 40);
2053 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2054 for ($idx = 0; $idx < 40; $idx++) {
2055 $char = substr($str, $idx, 1);
2056 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2059 // Return scrambled string
2060 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2064 function genScrambleString($len) {
2065 // Prepare randomizer and array for the numbers
2066 mt_srand((double) microtime() * 1000000);
2067 $scrambleNumbers = array();
2069 // First we need to setup randomized numbers from 0 to 31
2070 for ($idx = 0; $idx < $len; $idx++) {
2072 $rand = mt_rand(0, ($len -1));
2074 // Check for it by creating more numbers
2075 while (array_key_exists($rand, $scrambleNumbers)) {
2076 $rand = mt_rand(0, ($len -1));
2080 $scrambleNumbers[$rand] = $rand;
2083 // So let's create the string for storing it in database
2084 $scrambleString = implode(":", $scrambleNumbers);
2085 return $scrambleString;
2087 // Append data like session ID referral ID to the given URL which would
2088 // normally be stored in cookies
2089 function ADD_URL_DATA($URL) {
2093 // Determine URL binder
2095 if (strpos($URL, "?") !== false) $BIND = "&";
2097 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2098 // Cookies are not accepted
2099 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2100 // Cookie found in URL
2101 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2102 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2103 // Not found! So let's set default here
2104 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2107 // Is there already added data? Then change the binder
2108 if (!empty($ADD)) $BIND = "&";
2111 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2112 // Add session from URL
2113 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2115 // Add current session
2116 $ADD .= $BIND."PHPSESSID=".session_id();
2120 // Add all together and return it
2123 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2124 function generatePassString($passHash) {
2127 // Return vanilla password hash
2130 // Is a secret key and master salt already initialized?
2131 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2132 // Only calculate when the secret key is generated
2133 $newHash = ""; $start = 9;
2134 for ($idx = 0; $idx < 10; $idx++) {
2135 $part1 = hexdec(substr($passHash, $start, 4));
2136 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2137 $mod = dechex($idx);
2138 if ($part1 > $part2) {
2139 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2140 } elseif ($part2 > $part1) {
2141 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2143 $mod = substr(round($mod), 0, 4);
2144 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2145 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2150 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2151 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2152 //* DEBUG: */ print($ret."<br />\n");
2155 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2156 $ret = md5($passHash);
2157 //* DEBUG: */ echo "++".$ret."++<br />\n";
2164 // Fix "deleted" cookies
2165 function FIX_DELETED_COOKIES ($cookies) {
2166 // Is this an array with entries?
2167 if ((is_array($cookies)) && (count($cookies) > 0)) {
2168 // Then check all cookies if they are marked as deleted!
2169 foreach ($cookies as $cookieName) {
2170 // Is the cookie set to "deleted"?
2171 if (get_session($cookieName) == "deleted") {
2172 set_session($cookieName, "");
2178 // Output error messages in a fasioned way and die...
2179 function mxchange_die ($msg) {
2182 // Load the message template
2183 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2186 include(PATH."inc/footer.php");
2192 // Display parsing time and number of SQL queries in footer
2193 function DISPLAY_PARSING_TIME_FOOTER() {
2194 global $startTime, $_CONFIG;
2195 $endTime = microtime(true);
2197 // Is the timer started?
2198 if (!isset($GLOBALS['startTime'])) {
2203 // "Explode" both times
2204 $start = explode(" ", $GLOBALS['startTime']);
2205 $end = explode(" ", $endTime);
2206 $runTime = $end[0] - $start[0];
2207 if ($runTime < 0) $runTime = 0;
2208 $runTime = TRANSLATE_COMMA($runTime);
2212 'runtime' => $runTime,
2213 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2214 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2217 // Load the template
2218 LOAD_TEMPLATE("show_timings", false, $content);
2221 // Unset/set session variables
2222 function set_session ($var, $value) {
2225 // Abort in CSS mode here
2226 if ($CSS == 1) return true;
2228 // Trim value and session variable
2229 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2231 // Is the session variable set?
2232 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2233 // Remove the session
2234 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2235 unset($_SESSION[$var]);
2236 return session_unregister($var);
2237 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2239 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2240 $_SESSION[$var] = $value;
2241 return session_register($var);
2242 } elseif (!empty($value)) {
2244 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2245 $_SESSION[$var] = $value;
2249 // Ignored (but valid)
2250 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2254 // Check wether a boolean constant is set
2255 // Taken from user comments in PHP documentation for function constant()
2256 function isBooleanConstantAndTrue($constName) { // : Boolean
2259 // Failed by default
2263 if (isset($constCache[$constName])) {
2265 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2266 $res = $constCache[$constName];
2269 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2270 if (defined($constName)) $res = (constant($constName) === true);
2273 $constCache[$constName] = $res;
2275 //* DEBUG: */ var_dump($res);
2281 // Check wether a session variable is set
2282 function isSessionVariableSet($var) {
2283 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2284 return (isset($_SESSION[$var]));
2286 // Returns wether the value of the session variable or NULL if not set
2287 function get_session($var) {
2290 // Default is not found! ;-)
2293 // Is the variable there or cached values?
2294 if (isset($cacheArray['session'][$var])) {
2295 // Get cached value (skips a lot SQL_ESCAPE() calles!
2296 $value = $cacheArray['session'][$var];
2297 } elseif (isSessionVariableSet($var)) {
2298 // Then get it secured!
2299 $value = SQL_ESCAPE($_SESSION[$var]);
2302 $cacheArray['session'][$var] = $value;
2308 // Send notification to admin
2309 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2310 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2312 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2314 // Send outdated way
2315 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2316 SEND_ADMIN_EMAILS($subject, $msg);
2319 // Destroy user session
2320 function destroy_user_session () {
2321 // Remove all user data from session
2322 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2324 // Merges an array together but only if both are arrays
2325 function merge_array ($array1, $array2) {
2326 // Are both an array?
2327 if ((is_array($array1)) && (is_array($array2))) {
2328 // Merge all together
2329 return array_merge($array1, $array2);
2330 } elseif (is_array($array1)) {
2331 // Return left array
2335 // Something wired happened here...
2336 print(__FUNCTION__.":<pre>");
2337 debug_print_backtrace();
2340 // Debug message logger
2341 function DEBUG_LOG ($message, $force=false) {
2342 // Is debug mode enabled?
2343 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2344 // Log this message away
2345 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2346 fwrite($fp, date("d.m.Y|H:i:s", time())."|".strip_tags($message)."\n");
2350 // Reads a directory with PHP files in and gets only files back
2351 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2355 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2358 while ($baseFile = readdir($dirPointer)) {
2359 // Load file only if extension is active
2361 $file = $baseDir.$baseFile;
2363 // Is this a valid reset file?
2364 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2365 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2366 // Remove both for extension name
2367 $extName = substr($baseFile, strlen($prefix), -4);
2370 $extId = GET_EXT_ID($extName);
2372 // Is the extension valid and active?
2373 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2374 // Then add this file
2376 } elseif ($extId == 0) {
2377 // Add non-extension files as well
2384 closedir($dirPointer);
2389 // Return array with include files
2392 // Load more reset scripts
2393 function RESET_ADD_INCLUDES () {
2396 // Is the reset set or old sql_patches?
2397 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2402 // Get more daily reset scripts
2403 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2406 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2408 // Create current week mark
2409 $currWeek = date("W", time());
2412 if ($_CONFIG['last_week'] != $currWeek) {
2413 // Include weekly reset scripts
2414 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2417 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2420 // Create current month mark
2421 $currMonth = date("m", time());
2424 if ($_CONFIG['last_month'] != $currMonth) {
2425 // Include monthly reset scripts
2426 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2429 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2435 // Handle extra values
2436 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2437 // Default is the value itself
2440 // Do we have a special filter function?
2441 if (!empty($filterFunction)) {
2442 // Does the filter function exist?
2443 if (function_exists($filterFunction)) {
2444 // Do we have extra parameters here?
2445 if (!empty($extraValue)) {
2446 // Put both parameters in one new array by default
2447 $args = array($value, $extraValue);
2449 // If we have an array simply use it and pre-extend it with our value
2450 if (is_array($extraValue)) {
2451 // Make the new args array
2452 $args = array_merge(array($value), $extraValue);
2455 // Call the multi-parameter call-back
2456 $ret = call_user_func_array($filterFunction, $args);
2458 // One parameter call
2459 $ret = call_user_func($filterFunction, $value);
2467 // Check if given FQFN is a readable file
2468 function FILE_READABLE($fqfn) {
2470 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2472 // Converts timestamp selections into a timestamp
2473 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2474 // Init test variable
2477 // Get last three chars
2478 $TEST = substr($id, -3);
2480 // Improved way of checking! :-)
2481 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2482 // Found a multi-selection for timings?
2483 $TEST = substr($id, 0, -3);
2484 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)) {
2485 // Generate timestamp
2486 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2487 $DATA[] = "$TEST='".$POST[$TEST]."'";
2489 // Remove data from array
2490 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2491 unset($POST[$TEST."_".$rem]);
2495 unset($id); $skip = true; $TEST2 = $TEST;
2498 // Process this entry
2499 $skip = false; $TEST2 = "";
2502 // Reverts the german decimal comma into Computer decimal dot
2503 function REVERT_COMMA ($str) {
2504 // Default float is not a float... ;-)
2507 // Which language is selected?
2508 switch (GET_LANGUAGE()) {
2509 case "de": // German language
2510 // Remove german thousand dots first
2511 $str = str_replace(".", "", $str);
2513 // Replace german commata with decimal dot and cast it
2514 $float = (float)str_replace(",", ".", $str);
2517 default: // US and so on
2518 // Remove thousand dots first and cast
2519 $float = (float)str_replace(",", "", $str);
2526 // Handle menu-depending failed logins and return the rendered content
2527 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2528 // Default output is empty ;-)
2531 // Is the session data set?
2532 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2533 // Ignore zero values
2534 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2535 // Non-guest has login failtures found, get both data and prepare it for template
2536 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2538 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2539 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2543 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2546 // Reset session data
2547 set_session('mxchange_'.$accessLevel.'_failtures', "");
2548 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2551 // Return rendered content
2555 function REBUILD_CACHE ($cache, $inc="") {
2556 global $cacheInstance, $_CONFIG, $CSS;
2558 // Shall I remove the cache file?
2559 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2561 if ($cacheInstance->cache_file($cache, true)) {
2563 $cacheInstance->cache_destroy();
2566 // Include file given?
2569 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2571 // Is the include there?
2572 if (FILE_READABLE($fqfn)) {
2573 // And rebuild it from scratch
2576 // Include not found!
2577 DEBUG_LOG(__FUNCTION__.":Include {$inc} not found. cache={$cache}");
2582 // Purge admin menu cache
2583 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2584 global $_CONFIG, $cacheInstance;
2586 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2587 if (!EXT_IS_ACTIVE("cache")) {
2588 // Cache extension not active
2590 } elseif (!is_object($cacheInstance)) {
2591 // No cache instance!
2592 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2594 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2595 // Caching disabled (currently experiemental!)
2599 // Experiemental feature!
2600 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2602 // Translates the "pool type" into human-readable
2603 function TRANSLATE_POOL_TYPE ($type) {
2604 // Default type is unknown
2605 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2607 // Generate constant
2608 $constName = sprintf("POOL_TYPE_%s", $type);
2611 if (defined($constName)) {
2613 $translated = constant($constName);
2616 // Return "translation"
2619 // "Getter" for remote IP number
2620 function GET_REMOTE_ADDR () {
2621 // Get remote ip from environment
2622 $remoteAddr = getenv('REMOTE_ADDR');
2624 // Is removeip installed?
2625 if (EXT_IS_ACTIVE("removeip")) {
2626 // Then anonymize it
2627 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2633 // "Getter" for remote hostname
2634 function GET_REMOTE_HOST () {
2635 // Get remote ip from environment
2636 $remoteHost = getenv('REMOTE_HOST');
2638 // Is removeip installed?
2639 if (EXT_IS_ACTIVE("removeip")) {
2640 // Then anonymize it
2641 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2647 // "Getter" for user agent
2648 function GET_USER_AGENT () {
2649 // Get remote ip from environment
2650 $userAgent = getenv('HTTP_USER_AGENT');
2652 // Is removeip installed?
2653 if (EXT_IS_ACTIVE("removeip")) {
2654 // Then anonymize it
2655 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2661 // "Getter" for referer
2662 function GET_REFERER () {
2663 // Get remote ip from environment
2664 $referer = getenv('HTTP_REFERER');
2666 // Is removeip installed?
2667 if (EXT_IS_ACTIVE("removeip")) {
2668 // Then anonymize it
2669 $referer = GET_ANONYMOUS_REFERER($referer);
2676 //////////////////////////////////////////////////
2678 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2680 //////////////////////////////////////////////////
2682 if (!function_exists('html_entity_decode')) {
2683 // Taken from documentation on www.php.net
2684 function html_entity_decode($string) {
2685 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2686 $trans_tbl = array_flip($trans_tbl);
2687 return strtr($string, $trans_tbl);