2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
40 // Check if our config file is writeable or not
41 function is_INCWritable($inc) {
42 $fp = @fopen(PATH."inc/".$inc.".php", 'a');
43 if ($inc == "dummy") {
46 return @unlink(PATH."inc/dummy.php");
48 // Close all other files
53 // Open a table (you may want to add some header stuff here)
54 function OPEN_TABLE($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
57 // Count tables so we can generate CSS classes for every table... :-)
59 // Class is empty so count one up and create a class
60 $table_cnt++; $CLASS = "class".$table_cnt;
62 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
64 // Shall I add the classes to TABLE and TD or only to TD?
65 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
68 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
71 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
73 // Vertical align is given
74 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
75 $OUT .= ">\n<TR>\n<TD";
76 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
77 $OUT .= " class=\"".$CLASS."\">";
81 // Close a table (you may want to add some footer stuff here)
82 function CLOSE_TABLE($ADD="") {
83 OUTPUT_HTML(" </TD>\n</TR>");
84 if (!empty($ADD)) OUTPUT_HTML($ADD);
85 OUTPUT_HTML("</TABLE>");
88 // Output HTML code directly or "render" it. You addionally switch the new-line character off
89 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
90 // Some global variables
91 global $OUTPUT, $footer, $CSS;
93 // Do we have HTML-Code here?
95 // Yes, so we handle it as you have configured
99 // That's why you don't need any \n at the end of your HTML code... :-)
100 if (_OB_CACHING == "on") {
101 // Output into PHP's internal buffer
104 // That's why you don't need any \n at the end of your HTML code... :-)
105 if ($NEW_LINE) echo "\n";
107 // Render mode for old or lame servers...
110 // That's why you don't need any \n at the end of your HTML code... :-)
111 if ($NEW_LINE) $OUTPUT .= "\n";
116 // If we are switching from render to direct output rendered code
117 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
119 // The same as above... ^
121 if ($NEW_LINE) echo "\n";
125 // Huh, something goes wrong or maybe you have edited config.php ???
126 die ("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
129 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
130 // Output cached HTML code
131 $OUTPUT = ob_get_contents();
133 // Clear output buffer for later output
136 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
137 $OUTPUT = REWRITE_LINKS($OUTPUT);
140 // Compile and run finished rendered HTML code
141 while (strpos($OUTPUT, '{!') > 0) {
142 // Prepare the content and eval() it...
144 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
147 if (empty($newContent)) {
148 // Something went wrong!
149 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
151 $OUTPUT = $newContent;
154 // Output code here, DO NOT REMOVE! ;-)
156 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
157 // Rewrite links when rewrite extension is active
158 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
159 $OUTPUT = REWRITE_LINKS($OUTPUT);
162 // Compile and run finished rendered HTML code
163 while (strpos($OUTPUT, '{!') > 0) {
164 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
168 // Output code here, DO NOT REMOVE! ;-)
173 // Output the raw HTML code
174 function OUTPUT_RAW ($HTML) {
175 // Output stripped HTML code to avoid broken JavaScript code, etc.
176 echo stripslashes($HTML);
178 // Flush the output if only _OB_CACHING is not "on"
179 if (_OB_CACHING != "on") {
185 // Add a fatal error message to the queue array
186 function ADD_FATAL ($message, $extra="") {
189 // Regular text message to add to $FATAL
192 // $message is text with a mask plus extras to insert into the text
193 $FATAL[] = sprintf($message, $extra);
197 // Load a template file and return it's content (only it's name; do not use ' or ")
198 function LOAD_TEMPLATE($template, $return=false, $content="") {
199 // Add more variables which you want to use in your template files
200 global $DATA, $_CONFIG, $username;
202 // Make all template names lowercase
203 $template = strtolower($template);
205 // Count the template load
206 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
207 $_CONFIG['num_templates']++;
210 $ACTION = SQL_ESCAPE($GLOBALS['action']);
211 $WHAT = SQL_ESCAPE($GLOBALS['what']);
213 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
214 $REFID = $GLOBALS['refid'];
216 // @DEPRECATED Try to remove this if() block
217 if ($template == "member_support_form") {
218 // Support request of a member
219 $result = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
220 array($GLOBALS['userid']), __FILE__, __LINE__);
222 // @TODO Merge this data into $content
223 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
226 $gender = TRANSLATE_GENDER($gender);
228 // Insert data if content is an array
229 if (is_array($content)) {
230 // Please switch to $content[bla] in all your templates! Direct
231 // variables are deprecated as of 09/13/2008.
232 $content['gender'] = $gender;
233 $content['surname'] = $surname;
234 $content['family'] = $family;
235 $content['email'] = $email;
239 SQL_FREERESULT($result);
242 // Generate date/time string
243 $date_time = MAKE_DATETIME(time(), "1");
246 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
249 // Check for admin/guest/member templates
250 if (strpos($template, "admin_") > -1) {
251 // Admin template found
253 } elseif (strpos($template, "guest_") > -1) {
254 // Guest template found
256 } elseif (strpos($template, "member_") > -1) {
257 // Member template found
259 } elseif (strpos($template, "install_") > -1) {
260 // Installation template found
262 } elseif (strpos($template, "ext_") > -1) {
263 // Extension template found
265 } elseif (strpos($template, "la_") > -1) {
266 // "Logical-area" template found
269 // Test for extension
270 $test = substr($template, 0, strpos($template, "_"));
271 if (EXT_IS_ACTIVE($test)) {
272 // Set extra path to extension's name
277 ////////////////////////
278 // Generate file name //
279 ////////////////////////
280 $file = $BASE.$MODE.$template.".tpl";
282 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
283 // Select what depended header/footer template file for admin/guest/member area
284 $file2 = sprintf("%s%s%s_%s.tpl",
288 SQL_ESCAPE($GLOBALS['what'])
292 if (FILE_READABLE($file2)) $file = $file2;
294 // Remove variable from memory
298 // Does the special template exists?
299 if (!FILE_READABLE($file)) {
300 // Reset to default template
301 $file = $BASE.$template.".tpl";
304 // Now does the final template exists?
305 if (FILE_READABLE($file)) {
306 // The local file does exists so we load it. :)
307 $tmpl_file = implode("", file($file));
309 // Replace ' to our own chars to preventing them being quoted
310 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
312 // Do we have to compile the code?
314 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
316 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
319 // Simply return loaded code
323 // Add surrounding HTML comments to help finding bugs faster
324 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
325 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
326 // Only admins shall see this warning or when installation mode is active
327 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
328 (".basename($file).")<br />
331 <PRE>".print_r($content, true)."</PRE>
333 <PRE>".print_r($DATA, true)."</PRE>
337 // Do we have some content to output or return?
339 // Not empty so let's put it out! ;)
341 // Return the HTML code
347 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
348 // Warning, empty output!
349 return "E:".$template."<br />\n";
353 // Send mail out to an email address
354 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML='N', $FROM="") {
355 // Compile subject line (for POINTS constant etc.)
356 $eval = "\$SUBJECT = \"".COMPILE_CODE(addslashes($SUBJECT))."\";";
358 $SUBJECT = html_entity_decode($SUBJECT);
361 if ((!eregi("@", $TO)) && ($TO > 0)) {
362 // Value detected, load email from database
363 if (EXT_IS_ACTIVE("msg")) {
364 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
367 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
368 list($TO) = SQL_FETCHROW($result_email);
369 SQL_FREERESULT($result_email);
371 } elseif ($TO == 0) {
376 // Not in PHPMailer-Mode
377 if (!CHECK_PHPMAILER_USAGE()) {
379 // Load email header template
380 $FROM = LOAD_EMAIL_TEMPLATE("header");
383 $FROM .= LOAD_EMAIL_TEMPLATE("header");
385 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
387 // Load email header template
388 $FROM = LOAD_EMAIL_TEMPLATE("header");
391 $FROM .= LOAD_EMAIL_TEMPLATE("header");
395 // Fix HTML parameter (default is no!)
396 if (empty($HTML)) $HTML = "N";
397 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
398 // In debug mode we want to display the mail instead of sending it away so we can debug this part
400 ".htmlentities(trim($FROM))."
402 Subject : ".$SUBJECT."
405 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail", true))) {
406 // Send mail as HTML away
407 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
408 } elseif (!empty($TO)) {
410 $TO = COMPILE_CODE($TO);
413 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
414 } elseif ($HTML == "N") {
416 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
420 // Check if legacy or PHPMailer command
422 function CHECK_PHPMAILER_USAGE() {
423 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
427 * Send out a raw email with PHPMailer class or legacy mail() command
429 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
430 // Shall we use PHPMailer class or legacy mode?
431 if (CHECK_PHPMAILER_USAGE()) {
432 // Use PHPMailer class with SMTP enabled
433 require_once(PATH."inc/phpmailer/class.phpmailer.php");
434 require_once(PATH."inc/phpmailer/class.smtp.php");
437 $mail = new PHPMailer();
438 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
441 $mail->SMTPAuth = true;
442 $mail->Host = SMTP_HOSTNAME;
444 $mail->Username = SMTP_USER;
445 $mail->Password = SMTP_PASSWORD;
447 $mail->From = WEBMASTER;
451 $mail->FromName = MAIN_TITLE;
452 $mail->Subject = $subject;
453 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
455 $mail->AltBody = "Your mail program required HTML support to read this mail!";
456 $mail->WordWrap = 70;
461 $mail->AddAddress($to, "");
462 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
463 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
464 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
467 // Use legacy mail() command
468 @mail($to, $subject, $msg, $from);
473 // Generate a password in a specified length or use default password length
474 function GEN_PASS($LEN = 0) {
476 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
478 // Initialize array with all allowed chars
479 $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,-,+,_,/");
481 // Initialize randomizer
482 mt_srand((double) microtime() * 1000000);
484 // Start creating password
486 for ($i = 0; $i < $LEN; $i++) {
487 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
490 // When the size is below 40 we can also add additional security by scrambling it
491 if (strlen($PASS) <= 40) {
492 // Also scramble the password
493 $PASS = scrambleString($PASS);
496 // Return the password
500 function MAKE_DATETIME ($time, $mode="0")
504 return NEVER_HAPPENED;
506 // Filter out numbers
507 $time = bigintval($time);
510 switch (GET_LANGUAGE())
512 case "de": // German date / time format
514 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
515 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
516 case "2": $ret = date("d.m.Y|H:i", $time); break;
517 case "3": $ret = date("d.m.Y", $time); break;
521 default: // Default is the US date / time format!
523 case "0": $ret = date("r", $time); break;
524 case "1": $ret = date("Y-m-d - g:i A", $time); break;
525 case "2": $ret = date("y-m-d|H:i", $time); break;
526 case "3": $ret = date("y-m-d", $time); break;
532 // Translates the american decimal dot into a german comma
533 function TRANSLATE_COMMA ($dotted, $cut=true) {
536 // Default is 3 you can change this in admin area "Misc -> Misc Options"
537 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
538 $maxComma = $_CONFIG['max_comma'];
542 // Test for commata if in cut-mode
543 $com = explode(".", $dotted);
544 if (count($com) > 1) {
545 // Commata found, so only zeros?
546 if ($com[1] == str_repeat("0", strlen($com[1]))) {
547 // Only zeros, so don't display them
551 // Don't display commatas even if there are none... ;-)
557 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
560 switch (GET_LANGUAGE()) {
562 $dotted = number_format($dotted, $maxComma, ",", ".");
566 $dotted = number_format($dotted, $maxComma, ".", ",");
570 // Return translated value
575 function DEREFERER ($URL) {
576 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
581 function TRANSLATE_GENDER ($gender) {
584 case "M": $ret = GENDER_M; break;
585 case "F": $ret = GENDER_F; break;
586 case "C": $ret = GENDER_C; break;
587 default : $ret = $gender; break;
592 function GET_POOL_TYPE($PT) {
593 // Unknown pool type is default
594 $ret = POOL_UNKNOWN." (".$PT.")";
596 // Generate constant name
597 $constantName = sprintf("POOL_%s", $PT);
599 // Is the type known?
600 if (defined($constantName)) {
601 // Prepare eval command
602 $eval = sprintf("\$ret = %s;", $constantName);
610 function FRAMETESTER($URL) {
611 // Prepare frametester URL
612 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
614 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
616 return $frametesterUrl;
619 function SELECTION_COUNT($array) {
621 if (is_array($array)) {
622 foreach ($array as $key => $sel) {
623 if (!empty($sel)) $ret++;
629 function IMG_CODE ($code, $type, $DATA, $uid) {
630 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
633 function TRANSLATE_STATUS($status) {
637 $ret = ACCOUNT_UNCONFIRMED;
641 $ret = ACCOUNT_CONFIRMED;
645 $ret = ACCOUNT_LOCKED;
649 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
655 function GET_LANGUAGE() {
656 if (!empty($_GET['mx_lang'])) {
657 // Accept only first 2 chars
658 $lang = substr($_GET['mx_lang'], 0, 2);
664 // Set default return value to default language from config
667 // Check GET variable and cookie
669 // Check if main language file does exist
670 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
671 // Okay found, so let's update cookies
674 } elseif (!isSessionVariableSet('mx_lang')) {
675 // Return stored value from cookie
676 $ret = get_session('mx_lang');
678 // Fixes a warning before the session has the mx_lang constant
679 if (empty($ret)) $ret = DEFAULT_LANG;
684 function SET_LANGUAGE($lang) {
687 // Accept only first 2 chars!
688 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
691 set_session("mx_lang", $lang);
694 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
695 global $DATA, $_CONFIG, $REPLACER;
697 // Make sure all template names are lowercase!
698 $template = strtolower($template);
700 // Default "nickname" if extension is not installed
703 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
704 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
706 // Init variables (DEPRECATED! Use $content[bla] instead.
712 // Prepare IP number and User Agent
713 $REMOTE_ADDR = getenv('REMOTE_ADDR');
714 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
717 if (isSessionVariableSet('admin_login')) {
719 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
720 array(get_session('admin_login')), __FILE__, __LINE__);
721 list($ADMIN) = SQL_FETCHROW($result);
722 SQL_FREERESULT($result);
725 // Expiration in a nice output format
726 if ($_CONFIG['auto_purge'] == 0) {
727 // Will never expire!
728 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
729 } elseif (function_exists('CREATE_FANCY_TIME')) {
730 // Create nice date string
731 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
734 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
737 // Is content an array?
738 if (is_array($content)) {
739 // Add expiration to array, $EXPIRATION is now deprecated!
740 $content['expiration'] = $EXPIRATION;
743 // @TODO Try to rewrite this part
744 if ($template == "add-points") {
745 if (isset($_POST['points'])) {
746 $points = bigintval($_POST['points']);
748 $points = __POINTS_VALUE;
754 if (EXT_IS_ACTIVE("nickname")) {
756 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
757 array(bigintval($UID)), __FILE__, __LINE__);
758 list($surname, $family, $gender, $email, $nick) = SQL_FETCHROW($result);
759 SQL_FREERESULT($result);
762 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
763 array(bigintval($UID)), __FILE__, __LINE__);
764 list($surname, $family, $gender, $email) = SQL_FETCHROW($result);
765 SQL_FREERESULT($result);
768 // Neutral gender and email address is default
773 // Translate M to male or F to female
774 $gender = TRANSLATE_GENDER($gender);
776 // Insert data if content is an array
777 if (is_array($content)) {
778 // Please do no longer use direct variable names, use $content[bla]
780 $content['gender'] = $gender;
781 $content['surname'] = $surname;
782 $content['family'] = $family;
783 $content['email'] = $email;
784 $content['nick'] = $nick;
787 // Store email for some functions in global data array
788 $DATA['email'] = $email;
791 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
793 // Check for admin/guest/member templates
794 if (strpos($template, "admin_") > -1) {
795 // Admin template found
796 $file = $BASE."admin/".$template.".tpl";
797 } elseif (strpos($template, "guest_") > -1) {
798 // Guest template found
799 $file = $BASE."guest/".$template.".tpl";
800 } elseif (strpos($template, "member_") > -1) {
801 // Member template found
802 $file = $BASE."member/".$template.".tpl";
804 // Test for extension
805 $test = substr($template, 0, strpos($template, "_"));
806 if (EXT_IS_ACTIVE($test)) {
807 // Set extra path to extension's name
808 $file = $BASE.$test."/".$template.".tpl";
810 // No special filename
811 $file = $BASE.$template.".tpl";
815 // Does the special template exists?
816 if (!FILE_READABLE($file)) {
817 // Reset to default template
818 $file = $BASE.$template.".tpl";
821 // Now does the final template exists?
823 if (FILE_READABLE($file)) {
824 // The local file does exists so we load it. :)
825 $tmpl_file = @implode("", @file($file));
826 $tmpl_file = addslashes($tmpl_file);
829 $tmpl_file = "\$newContent=\"".COMPILE_CODE($tmpl_file)."\";";
832 // Replace HTML conform chars
833 $newContent = html_entity_decode($newContent);
834 } elseif (!empty($template)) {
835 // Template file not found!
836 $newContent = TEMPLATE_404.": ".$template."<br />
838 <PRE>".print_r($newContent, true)."</PRE>
840 <PRE>".print_r($DATA, true)."</PRE>
843 // Debug mode not active? Then remove the HTML tags
844 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
846 // No template name supplied!
847 $newContent = NO_TEMPLATE_SUPPLIED;
850 // Is there some content?
851 if (empty($newContent)) {
853 $newContent = "Compiler error for template {$template}!";
856 // Return compiled content
857 return COMPILE_CODE($newContent);
860 function MAKE_TIME($H, $M, $S, $stamp) {
861 // Extract day, month and year from given timestamp
862 $DAY = date("d", $stamp);
863 $MONTH = date("m", $stamp);
864 $YEAR = date('Y', $stamp);
866 // Create timestamp for wished time which depends on extracted date
867 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
870 function LOAD_URL($URL, $addUrlData=true) {
871 global $CSS, $_CONFIG, $footer;
873 // Check if http(s):// is there
874 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
875 // Make all URLs full-qualified
879 // Compile out URI codes
880 $URL = COMPILE_CODE($URL);
883 $OUTPUT = ob_get_contents();
888 // Add some data to URL if cookies are not accepted
889 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
891 // Probe for bot from search engine
892 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
893 // Search engine bot detected so let's rewrite many chars for the link
894 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
896 // Output new location link as anchor
897 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
898 } elseif (!headers_sent()) {
899 // Load URL when headers are not sent
902 debug_print_backtrace();
903 die("</pre>URL={$URL}");
905 @header ("Location: ".str_replace("&", "&", $URL));
907 // Output error message
908 include(PATH."inc/header.php");
909 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
910 include(PATH."inc/footer.php");
915 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
916 global $SEC_CHARS, $URL_CHARS;
919 // Select smaller set of chars to replace when we e.g. want to compile URLs
920 if (!$full) $ARRAY = $URL_CHARS;
924 // BEFORE 0.2.1 : Language and data constants
925 // WITH 0.2.1+ : Only language constants
926 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
928 // BEFORE 0.2.1 : Not used
929 // WITH 0.2.1+ : Data constants
930 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
933 // Compile QUOT and other non-HTML codes
934 foreach ($ARRAY['to'] as $k => $to) {
935 // Do the reversed thing as in inc/libs/security_functions.php
936 $code = str_replace($to, $ARRAY['from'][$k], $code);
939 // But shall I keep simple quotes for later use?
940 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
942 // Find $content[bla][blub] entries
943 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
945 // Are some matches found?
946 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
947 // Replace all matches
948 $matchesFound = array();
949 foreach ($matches[0] as $key => $match) {
950 // Avoid replacing matches multiple times
951 if (!isset($matchesFound[$match])) {
953 $code = str_replace($match, "\".".$match.".\"", $code);
954 $matchesFound[$match] = 1;
957 // Take all string elements
958 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
959 // Replace it in the code
960 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
961 $code = str_replace($match, $newMatch, $code);
962 $matchesFound[$key."_".$matches[4][$key]] = 1;
967 // Return compiled code
971 /************************************************************************
973 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
974 * $a_sort sortiert: *
976 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
977 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
978 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
979 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
980 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
982 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
983 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
984 * Sie, dass es doch nicht so schwer ist! :-) *
986 ************************************************************************/
987 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
990 while ($primary_key < count($a_sort)) {
991 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
992 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
995 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
996 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
997 } elseif ($key != $key2) {
998 // Sort numbers (E.g.: 9 < 10)
999 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1000 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1004 // We have found two different values, so let's sort whole array
1005 foreach ($dummy as $sort_key => $sort_val) {
1006 $t = $dummy[$sort_key][$key];
1007 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1008 $dummy[$sort_key][$key2] = $t;
1019 // Write back sorted array
1023 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1025 global $MONTH_DESCR; $OUT = "";
1028 // This is a yes/no selection only!
1029 if ($id > 0) $prefix .= "[".$id."]";
1030 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1034 // Begin with regular selection box here
1035 if (!empty($prefix)) $prefix .= "_";
1037 if ($id > 0) $type2 .= "[".$id."]";
1038 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1043 for ($idx = 1; $idx < 32; $idx++)
1045 $OUT .= "<OPTION value=\"".$idx."\"";
1046 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1047 $OUT .= ">".$idx."</OPTION>\n";
1051 case "month": // Month
1052 foreach ($MONTH_DESCR as $month => $descr)
1054 $OUT .= "<OPTION value=\"".$month."\"";
1055 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1056 $OUT .= ">".$descr."</OPTION>\n";
1060 case "year": // Year
1062 $YEAR = date('Y', time());
1064 // Check if the default value is larger than minimum and bigger than actual year
1065 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1067 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1069 $OUT .= "<OPTION value=\"".$idx."\"";
1070 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1071 $OUT .= ">".$idx."</OPTION>\n";
1074 elseif ($DEFAULT == -1)
1076 // Current year minus 1
1077 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1079 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1084 // Get current year and subtract 16 (for erotic content)
1085 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1086 $YEAR = date('Y', time()) - 16;
1087 for ($idx = 1930; $idx <= $YEAR; $idx++)
1089 $OUT .= "<OPTION value=\"".$idx."\"";
1090 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1091 $OUT .= ">".$idx."</OPTION>\n";
1098 for ($idx = 0; $idx < 60; $idx+=5) {
1099 if (strlen($idx) == 1) $idx = "0".$idx;
1100 $OUT .= "<OPTION value=\"".$idx."\"";
1101 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1102 $OUT .= ">".$idx."</OPTION>\n";
1107 for ($idx = 0; $idx < 24; $idx++) {
1108 if (strlen($idx) == 1) $idx = "0".$idx;
1109 $OUT .= "<OPTION value=\"".$idx."\"";
1110 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1111 $OUT .= ">".$idx."</OPTION>\n";
1116 $OUT .= "<OPTION value=\"Y\"";
1117 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1118 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1119 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1120 $OUT .= ">".NO."</OPTION>\n";
1123 $OUT .= " </SELECT>\n";
1127 function TRANSLATE_YESNO($yn)
1131 case 'Y': $yn = YES; break;
1132 case 'N': $yn = NO; break;
1133 default : $yn = "??? (".$yn.")"; break;
1138 // Deprecated : $length
1141 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1144 // Fix missing _MAX constant
1145 if (!defined('_MAX')) define('_MAX', 15235);
1147 // Build server string
1148 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1151 $keys = SITE_KEY.":".DATE_KEY;
1152 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1153 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1154 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1155 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1157 // Build string from misc data
1158 $data = $code.":".$uid.":".$DATA;
1160 // Add more additional data
1161 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1162 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1163 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1164 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1165 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1166 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1168 // Calculate number for generating the code
1169 $a = $code + _ADD - 1;
1171 if (isset($_CONFIG['master_hash'])) {
1172 // Generate hash with master salt from modula of number with the prime number and other data
1173 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1175 // Create number from hash
1176 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1178 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1179 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1181 // Create number from hash
1182 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1185 // At least 10 numbers shall be secure enought!
1186 $len = $_CONFIG['code_length'];
1187 if ($len == 0) $len = $length;
1188 if ($len == 0) $len = 10;
1190 // Cut off requested counts of number
1191 $return = substr(str_replace('.', "", $rcode), 0, $len);
1193 // Done building code
1196 // Does only allow numbers
1197 function bigintval($num, $castValue = true) {
1198 // Filter all numbers out
1199 $ret = preg_replace("/[^0123456789]/", "", $num);
1202 if ($castValue) $ret = (double)$ret;
1204 // Has the whole value changed?
1205 if ("".$ret."" != "".$num."") {
1207 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1213 // Insert the code in $img_code into jpeg or PNG image
1214 function GENERATE_IMAGE($img_code, $header=true) {
1217 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1218 // Stop execution of function here because of over-sized code length
1220 } elseif (!$header) {
1221 // Return in an HTML code code
1222 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1226 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1227 if (FILE_READABLE($img)) {
1228 // Switch image type
1229 switch ($_CONFIG['img_type'])
1232 // Okay, load image and hide all errors
1233 $image = @imagecreatefromjpeg($img);
1237 // Okay, load image and hide all errors
1238 $image = @imagecreatefrompng($img);
1242 // Exit function here
1246 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1247 $text_color = imagecolorallocate($image, 0, 0, 0);
1249 // Insert code into image
1250 imagestring($image, 5, 14, 2, $img_code, $text_color);
1252 // Return to browser
1253 header ("Content-Type: image/".$_CONFIG['img_type']);
1255 // Output image with matching image factory
1256 switch ($_CONFIG['img_type']) {
1257 case "jpg": imagejpeg($image); break;
1258 case "png": imagepng($image); break;
1261 // Remove image from memory
1262 imagedestroy($image);
1264 // Create selection box or array of splitted timestamp
1265 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1266 // Calculate 15-seconds timestamp (15-seconds-steps shall be fine ;) )
1267 $stamp = round($timestamp / 15) * 15;
1269 // Do we have a leap year?
1271 $TEST = date('Y', time()) / 4;
1272 $M1 = date("m", time());
1273 $M2 = date("m", (time() + $stamp));
1275 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1276 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1278 // First of all years...
1279 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1281 $M = abs(floor($stamp / 2628000 - $Y * 12));
1283 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1285 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1287 $h = abs(floor($stamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1289 $m = abs(floor($stamp / 60 - $Y * (365 + $SWITCH / ONE_DAY) * 24 * 60 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1290 // And at last seconds...
1291 $s = abs(floor($stamp - $Y * (365 + $SWITCH / ONE_DAY) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1293 // Is seconds zero and time is < 60 seconds?
1294 if (($s == 0) && ($stamp < 60)) {
1300 // Now we convert them in seconds...
1302 if ($return_array) {
1303 // Just put all data in an array for later use
1315 $OUT = "<DIV align=\"".$align."\">\n";
1316 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1319 if (ereg('Y', $display) || (empty($display))) {
1320 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1323 if (ereg("M", $display) || (empty($display))) {
1324 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1327 if (ereg("W", $display) || (empty($display))) {
1328 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1331 if (ereg("D", $display) || (empty($display))) {
1332 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1335 if (ereg("h", $display) || (empty($display))) {
1336 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1339 if (ereg("m", $display) || (empty($display))) {
1340 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1343 if (ereg("s", $display) || (empty($display))) {
1344 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1350 if (ereg('Y', $display) || (empty($display))) {
1351 // Generate year selection
1352 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1353 for ($idx = 0; $idx <= 10; $idx++) {
1354 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1355 if ($idx == $Y) $OUT .= " selected default";
1356 $OUT .= ">".$idx."</OPTION>\n";
1358 $OUT .= " </SELECT></TD>\n";
1360 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1363 if (ereg("M", $display) || (empty($display))) {
1364 // Generate month selection
1365 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1366 for ($idx = 0; $idx <= 11; $idx++)
1368 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1369 if ($idx == $M) $OUT .= " selected default";
1370 $OUT .= ">".$idx."</OPTION>\n";
1372 $OUT .= " </SELECT></TD>\n";
1374 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1377 if (ereg("W", $display) || (empty($display))) {
1378 // Generate week selection
1379 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1380 for ($idx = 0; $idx <= 4; $idx++) {
1381 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1382 if ($idx == $W) $OUT .= " selected default";
1383 $OUT .= ">".$idx."</OPTION>\n";
1385 $OUT .= " </SELECT></TD>\n";
1387 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1390 if (ereg("D", $display) || (empty($display))) {
1391 // Generate day selection
1392 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1393 for ($idx = 0; $idx <= 31; $idx++) {
1394 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1395 if ($idx == $D) $OUT .= " selected default";
1396 $OUT .= ">".$idx."</OPTION>\n";
1398 $OUT .= " </SELECT></TD>\n";
1400 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1403 if (ereg("h", $display) || (empty($display))) {
1404 // Generate hour selection
1405 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1406 for ($idx = 0; $idx <= 23; $idx++) {
1407 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1408 if ($idx == $h) $OUT .= " selected default";
1409 $OUT .= ">".$idx."</OPTION>\n";
1411 $OUT .= " </SELECT></TD>\n";
1413 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1416 if (ereg("m", $display) || (empty($display))) {
1417 // Generate minute selection
1418 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1419 for ($idx = 0; $idx <= 59; $idx++) {
1420 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1421 if ($idx == $m) $OUT .= " selected default";
1422 $OUT .= ">".$idx."</OPTION>\n";
1424 $OUT .= " </SELECT></TD>\n";
1426 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1429 if (ereg("s", $display) || (empty($display))) {
1430 // Generate second selection
1431 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1432 for ($idx = 0; $idx <= 45; $idx += 15) {
1433 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1434 if ($idx == $s) $OUT .= " selected default";
1435 $OUT .= ">".$idx."</OPTION>\n";
1437 $OUT .= " </SELECT></TD>\n";
1439 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1442 $OUT .= "</TABLE>\n";
1444 // Return generated HTML code
1449 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1452 // Do we have a leap year?
1454 $TEST = date('Y', time()) / 4;
1455 $M1 = date("m", time());
1456 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1457 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1458 // First add years...
1459 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1461 $ret += $POST[$prefix."_mo"] * 2628000;
1463 $ret += $POST[$prefix."_we"] * 604800;
1465 $ret += $POST[$prefix."_da"] * 86400;
1467 $ret += $POST[$prefix."_ho"] * 3600;
1469 $ret += $POST[$prefix."_mi"] * 60;
1470 // And at last seconds...
1471 $ret += $POST[$prefix."_se"];
1472 // Return calculated value
1475 // Sends out mail to all administrators
1476 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1477 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1478 // Trim template name
1479 $template = trim($template);
1481 // Load email template
1482 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1484 if (GET_EXT_VERSION("admins") < "0.4.0") {
1485 // Older version detected!
1486 return SEND_ADMIN_EMAILS($subj, $msg);
1489 // Check which admin shall receive this mail
1490 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1491 array($template), __FILE__, __LINE__);
1492 if (SQL_NUMROWS($result) == 0) {
1493 // Create new entry (to all admins)
1494 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1495 array($template), __FILE__, __LINE__);
1497 // Load admin IDs...
1499 while(list($aid) = SQL_FETCHROW($result)) {
1504 SQL_FREERESULT($result);
1506 // "implode" IDs and query string
1507 $aid = implode(",", $aids);
1509 // Add line to userlog
1510 USERLOG_ADD_LINE($subj, $msg, $UID);
1512 } elseif ($aid == "0") {
1513 // Select all email adresses
1514 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1516 // If Admin-ID is not "to-all" select
1517 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1521 // Load email addresses and send away
1522 while (list($email) = SQL_FETCHROW($result)) {
1523 SEND_EMAIL($email, $subj, $msg);
1527 SQL_FREERESULT($result);
1530 function CREATE_FANCY_TIME($stamp) {
1531 // Get data array with years/months/weeks/days/...
1532 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1534 foreach($data as $k => $v) {
1536 // Value is greater than 0 "eval" data to return string
1537 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1543 // Remove leading commata and space
1544 $ret = substr($ret, 2);
1546 // Return fancy time string
1550 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1551 $SEP = ""; $TOP = "";
1554 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1558 for ($page = 1; $page <= $PAGES; $page++) {
1559 // Is the page currently selected or shall we generate a link to it?
1560 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1561 // Is currently selected, so only highlight it
1562 $NAV .= "<STRONG>-";
1564 // Open anchor tag and add base URL
1565 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1567 // Add userid when we shall show all mails from a single member
1568 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1570 // Close open anchor tag
1574 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1575 // Is currently selected, so only highlight it
1576 $NAV .= "-</STRONG>";
1582 // Add seperator if we have not yet reached total pages
1583 if ($page < $PAGES) $NAV .= " | ";
1586 // Define constants only once
1587 if (!defined('__NAV_OUTPUT')) {
1588 define('__NAV_OUTPUT' , $NAV);
1589 define('__NAV_COLSPAN', $colspan);
1590 define('__NAV_TOP' , $TOP);
1591 define('__NAV_SEP' , $SEP);
1594 // Load navigation template
1595 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1598 // Return generated HTML-Code
1606 // Extract host from script name
1607 function EXTRACT_HOST (&$script) {
1608 // Use default SERVER_URL by default... ;) So?
1611 // Is this URL valid?
1612 if (substr($script, 0, 7) == "http://") {
1613 // Use the hostname from script URL as new hostname
1614 $url = substr($script, 7);
1615 $extract = explode("/", $url);
1617 // Done extracting the URL :)
1620 // Extract host name
1621 $host = str_replace("http://", "", $url);
1622 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1624 // Generate relative URL
1625 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1626 if (substr(strtolower($script), 0, 7) == "http://") {
1627 // But only if http:// is in front!
1628 $script = substr($script, (strlen($url) + 7));
1629 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1631 $script = substr($script, (strlen($url) + 8));
1634 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1635 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1641 // Send a GET request
1642 function GET_URL ($script) {
1643 // Compile the script name
1644 $script = COMPILE_CODE($script);
1646 // Extract host name from script
1647 $host = EXTRACT_HOST($script);
1649 // Generate GET request header
1650 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1651 $request .= "Host: " . $host . "\r\n";
1652 $request .= "Referer: " . URL . "/admin.php\r\n";
1653 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1654 $request .= "Content-Type: text/plain\r\n";
1655 $request .= "Cache-Control: no-cache\r\n";
1656 $request .= "Connection: Close\r\n\r\n";
1658 // Send the raw request
1659 $response = SEND_RAW_REQUEST($host, $request);
1661 // Return the result to the caller function
1665 // Send a POST request
1666 function POST_URL ($script, $postData) {
1667 // Is postData an array?
1668 if (!is_array($postData)) {
1670 return array("", "", "");
1673 // Compile the script name
1674 $script = COMPILE_CODE($script);
1676 // Extract host name from script
1677 $host = EXTRACT_HOST($script);
1679 // Construct request
1680 $data = http_build_query($postData, '', '&');
1682 // Generate POST request header
1683 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1684 $request .= "Host: " . $host . "\r\n";
1685 $request .= "Referer: " . URL . "/admin.php\r\n";
1686 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1687 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1688 $request .= "Content-length: " . strlen($data) . "\r\n";
1689 $request .= "Cache-Control: no-cache\r\n";
1690 $request .= "Connection: Close\r\n\r\n";
1693 // Send the raw request
1694 $response = SEND_RAW_REQUEST($host, $request);
1696 // Return the result to the caller function
1700 // Sends a raw request to another host
1701 function SEND_RAW_REQUEST ($host, $request) {
1705 $response = array("", "", "");
1707 // Default is not to use proxy
1710 // Are proxy settins set?
1711 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1717 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1719 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1721 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1725 if (!is_resource($fp)) {
1732 // Generate CONNECT request header
1733 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1734 $proxyTunnel .= "Host: ".$host."\r\n";
1736 // Use login data to proxy? (username at least!)
1737 if (!empty($_CONFIG['proxy_username'])) {
1739 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1740 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1743 // Add last new-line
1744 $proxyTunnel .= "\r\n";
1745 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1748 fputs($fp, $proxyTunnel);
1752 // No response received
1756 // Read the first line
1757 $resp = trim(fgets($fp, 10240));
1758 $respArray = explode(" ", $resp);
1759 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1760 // Invalid response!
1766 fputs($fp, $request);
1770 $response[] = trim(fgets($fp, 1024));
1776 // Skip first empty lines
1778 foreach ($resp as $idx => $line) {
1780 $line = trim($line);
1782 // Is this line empty?
1785 array_shift($response);
1787 // Abort on first non-empty line
1792 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1794 // Proxy agent found?
1795 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1796 // Proxy header detected, so remove two lines
1797 array_shift($response);
1798 array_shift($response);
1801 // Was the request successfull?
1802 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1803 // Not found / access forbidden
1804 $response = array("", "", "");
1810 // Taken from www.php.net eregi() user comments
1811 function VALIDATE_EMAIL($email) {
1813 $email = COMPILE_CODE($email);
1815 // Check first part of email address
1816 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1819 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1822 $regex = "^".$first."@".$domain."$";
1824 // Return check result
1825 return eregi($regex, $email);
1827 // Function taken from user comments on www.php.net / function eregi()
1828 function VALIDATE_URL ($URL, $compile=true) {
1829 // Trim URL a little
1830 $URL = trim(urldecode($URL));
1831 //* DEBUG: */ echo $URL."<br />";
1833 // Compile some chars out...
1834 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1835 //* DEBUG: */ echo $URL."<br />";
1837 // Check for the extension filter
1838 if (EXT_IS_ACTIVE("filter")) {
1839 // Use the extension's filter set
1840 return FILTER_VALIDATE_URL($URL, false);
1843 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1844 // https:// in front of the URLs
1845 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1848 function MEMBER_ACTION_LINKS($uid, $status="") {
1849 // Define all main targets
1850 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1852 // Begin of navigation links
1853 $eval = "\$OUT = \"[ ";
1855 foreach ($TARGETS as $tar) {
1856 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1857 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1858 if (($tar == "lock_user") && ($status == "LOCKED")) {
1859 // Locked accounts shall be unlocked
1860 $eval .= "UNLOCK_USER";
1862 // All other status is fine
1863 $eval .= strtoupper($tar);
1865 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1866 if (($tar == "lock_user") && ($status == "LOCKED")) {
1867 // Locked accounts shall be unlocked
1868 $eval .= "UNLOCK_USER";
1870 // All other status is fine
1871 $eval .= strtoupper($tar);
1873 $eval .= ".\"</A></SPAN> | ";
1876 // Finish navigation link
1877 $eval = substr($eval, 0, -7)."]\";";
1883 // Function for backward-compatiblity
1884 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1885 // Load it from the register extension
1886 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1888 // Generate an email link
1889 function CREATE_EMAIL_LINK($email, $table="admins") {
1890 // Default email link (INSECURE! Spammer can read this by harvester programs)
1891 $EMAIL = "mailto:".$email;
1893 // Check for several extensions
1894 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1895 // Create email link for contacting admin in guest area
1896 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1897 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1898 // Create email link for contacting a member within admin area (or later in other areas, too?)
1899 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1900 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1901 // Create email link to contact sponsor within admin area (or like the link above?)
1902 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1905 // Shall I close the link when there is no admin?
1906 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1908 // Return email link
1911 // Generate a hash for extra-security for all passwords
1912 function generateHash ($plainText, $salt = "") {
1913 global $_CONFIG, $_SERVER;
1915 // Is the required extension "sql_patches" there and a salt is not given?
1916 if (((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1917 // Extension sql_patches is missing/outdated so we return the plain text
1921 // Do we miss an arry element here?
1922 if (!isset($_CONFIG['file_hash'])) {
1924 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1925 debug_print_backtrace();
1929 // When the salt is empty build a new one, else use the first x configured characters as the salt
1931 // Build server string
1932 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1935 $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'];
1938 $data = $plainText.":".uniqid(rand(), true).":".time();
1940 // Calculate number for generating the code
1941 $a = time() + _ADD - 1;
1943 // Generate SHA1 sum from modula of number and the prime number
1944 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1945 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1946 $sha1 = scrambleString($sha1);
1947 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1948 //* DEBUG: */ $sha1b = descrambleString($sha1);
1949 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1951 // Generate the password salt string
1952 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1953 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1956 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1957 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1961 return $salt.sha1($salt.$plainText);
1964 function scrambleString($str) {
1970 // Final check, in case of failture it will return unscrambled string
1971 if (strlen($str) > 40) {
1972 // The string is to long
1974 } elseif (strlen($str) == 40) {
1976 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1978 // Generate new numbers
1979 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1982 // Scramble string here
1983 //* DEBUG: */ echo "***Original=".$str."***<br />";
1984 for ($idx = 0; $idx < strlen($str); $idx++) {
1985 // Get char on scrambled position
1986 $char = substr($str, $scrambleNums[$idx], 1);
1988 // Add it to final output string
1989 $scrambled .= $char;
1992 // Return scrambled string
1993 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
1997 function descrambleString($str) {
1999 // Scramble only 40 chars long strings
2000 if (strlen($str) != 40) return $str;
2002 // Load numbers from config
2003 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2006 if (count($scrambleNums) != 40) return $str;
2008 // Begin descrambling
2009 $orig = str_repeat(" ", 40);
2010 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2011 for ($idx = 0; $idx < 40; $idx++) {
2012 $char = substr($str, $idx, 1);
2013 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2016 // Return scrambled string
2017 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2021 function genScrambleString($len) {
2022 // Prepare randomizer and array for the numbers
2023 mt_srand((double) microtime() * 1000000);
2024 $scrambleNumbers = array();
2026 // First we need to setup randomized numbers from 0 to 31
2027 for ($idx = 0; $idx < $len; $idx++) {
2029 $rand = mt_rand(0, ($len -1));
2031 // Check for it by creating more numbers
2032 while (array_key_exists($rand, $scrambleNumbers)) {
2033 $rand = mt_rand(0, ($len -1));
2037 $scrambleNumbers[$rand] = $rand;
2040 // So let's create the string for storing it in database
2041 $scrambleString = implode(":", $scrambleNumbers);
2042 return $scrambleString;
2044 // Append data like session ID referral ID to the given URL which would
2045 // normally be stored in cookies
2046 function ADD_URL_DATA($URL) {
2050 // Determine URL binder
2052 if (strpos($URL, "?") !== false) $BIND = "&";
2054 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2055 // Cookies are not accepted
2056 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2057 // Cookie found in URL
2058 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2059 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2060 // Not found! So let's set default here
2061 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2064 // Is there already added data? Then change the binder
2065 if (!empty($ADD)) $BIND = "&";
2068 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2069 // Add session from URL
2070 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2072 // Add current session
2073 $ADD .= $BIND."PHPSESSID=".session_id();
2077 // Add all together and return it
2080 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2081 function generatePassString($passHash) {
2084 // Return vanilla password hash
2087 // Is a secret key and master salt already initialized?
2088 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2089 // Only calculate when the secret key is generated
2090 $newHash = ""; $start = 9;
2091 for ($idx = 0; $idx < 10; $idx++) {
2092 $part1 = hexdec(substr($passHash, $start, 4));
2093 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2094 $mod = dechex($idx);
2095 if ($part1 > $part2) {
2096 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2097 } elseif ($part2 > $part1) {
2098 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2100 $mod = substr(round($mod), 0, 4);
2101 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2102 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2107 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2108 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2109 //* DEBUG: */ print($ret."<br />\n");
2112 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2113 $ret = md5($passHash);
2114 //* DEBUG: */ echo "++".$ret."++<br />\n";
2121 // Fix "deleted" cookies
2122 function FIX_DELETED_COOKIES ($cookies) {
2123 // Is this an array with entries?
2124 if ((is_array($cookies)) && (count($cookies) > 0)) {
2125 // Then check all cookies if they are marked as deleted!
2126 foreach ($cookies as $cookieName) {
2127 // Is the cookie set to "deleted"?
2128 if (get_session($cookieName) == "deleted") {
2129 set_session($cookieName, "");
2135 // Output error messages in a fasioned way and die...
2136 function mxchange_die ($msg) {
2139 // Load the message template
2140 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2143 include(PATH."inc/footer.php");
2149 // Display parsing time and number of SQL queries in footer
2150 function DISPLAY_PARSING_TIME_FOOTER() {
2151 global $startTime, $_CONFIG;
2152 $endTime = microtime(true);
2154 // Is the timer started?
2155 if (!isset($GLOBALS['startTime'])) {
2160 // "Explode" both times
2161 $start = explode(" ", $GLOBALS['startTime']);
2162 $end = explode(" ", $endTime);
2163 $runTime = $end[0] - $start[0];
2164 if ($runTime < 0) $runTime = 0;
2165 $runTime = TRANSLATE_COMMA($runTime);
2169 'runtime' => $runTime,
2170 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2171 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2174 // Load the template
2175 LOAD_TEMPLATE("show_timings", false, $content);
2178 // Unset/set session variables
2179 function set_session ($var, $value) {
2182 // Abort in CSS mode here
2183 if ($CSS == 1) return true;
2185 // Trim value and session variable
2186 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2188 // Is the session variable set?
2189 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2190 // Remove the session
2191 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2192 unset($_SESSION[$var]);
2193 return session_unregister($var);
2194 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2196 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2197 $_SESSION[$var] = $value;
2198 return session_register($var);
2199 } elseif (!empty($value)) {
2201 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2202 $_SESSION[$var] = $value;
2206 // Ignored (but valid)
2207 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2211 // Check wether a boolean constant is set
2212 // Taken from user comments in PHP documentation for function constant()
2213 function isBooleanConstantAndTrue($constName) { // : Boolean
2216 // Failed by default
2220 if (isset($constCache[$constName])) {
2222 $res = $constCache[$constName];
2225 if (defined($constName)) $res = (constant($constName) === true);
2228 $constCache[$constName] = $res;
2235 // Check wether a session variable is set
2236 function isSessionVariableSet($var) {
2237 //* DEBUG: */ echo __FUNCTION__.":var={$var}<br />\n";
2238 return (isset($_SESSION[$var]));
2240 // Returns wether the value of the session variable or NULL if not set
2241 function get_session($var) {
2242 // Default is not found! ;-)
2245 // Is the variable there?
2246 if (isSessionVariableSet($var)) {
2247 // Then get it secured!
2248 $value = SQL_ESCAPE($_SESSION[$var]);
2254 // Send notification to admin
2255 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2256 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2258 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2260 // Send outdated way
2261 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2262 SEND_ADMIN_EMAILS($subject, $msg);
2265 // Destroy user session
2266 function destroy_user_session () {
2267 // Remove all user data from session
2268 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2270 // Merges an array together but only if both are arrays
2271 function merge_array ($array1, $array2) {
2272 // Are both an array?
2273 if ((is_array($array1)) && (is_array($array2))) {
2274 // Merge all together
2275 return array_merge($array1, $array2);
2276 } elseif (is_array($array1)) {
2277 // Return left array
2281 // Something wired happened here...
2282 print(__FUNCTION__.":<pre>");
2283 debug_print_backtrace();
2286 // Debug message logger
2287 function DEBUG_LOG ($message) {
2288 // Is debug mode enabled?
2289 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
2290 // Log this message away
2291 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2292 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2296 // Reads a directory with PHP files in and gets only files back
2297 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2301 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2304 while ($baseFile = readdir($dirPointer)) {
2305 // Load file only if extension is active
2307 $file = $baseDir.$baseFile;
2309 // Is this a valid reset file?
2310 //* DEBUG: */ echo __FUNCTION__.":baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2311 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2312 // Remove both for extension name
2313 $extName = substr($baseFile, strlen($prefix), -4);
2316 $extId = GET_EXT_ID($extName);
2318 // Is the extension valid and active?
2319 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2320 // Then add this file
2322 } elseif ($extId == 0) {
2323 // Add non-extension files as well
2330 closedir($dirPointer);
2332 // Return array with include files
2335 // Load more reset scripts
2336 function RESET_ADD_INCLUDES () {
2339 // Is the reset set or old sql_patches?
2340 if ((!isBooleanConstantAndTrue('__DAILY_RESET')) || (GET_EXT_VERSION("sql_patches") < "0.4.5")) {
2345 // Get more daily reset scripts
2346 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2348 // Create current week mark
2349 $currWeek = date("W", time());
2352 if ($_CONFIG['last_week'] != $currWeek) {
2353 // Include weekly reset scripts
2354 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2357 UPDATE_CONFIG("last_week", $currWeek);
2360 // Create current month mark
2361 $currMonth = date("m", time());
2364 if ($_CONFIG['last_month'] != $currMonth) {
2365 // Include monthly reset scripts
2366 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2369 UPDATE_CONFIG("last_month", $currMonth);
2375 // Handle extra values
2376 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2377 // Default is the value itself
2380 // Do we have a special filter function?
2381 if (!empty($filterFunction)) {
2382 // Does the filter function exist?
2383 if (function_exists($filterFunction)) {
2384 // Do we have extra parameters here?
2385 if (!empty($extraValue)) {
2386 // Put both parameters in one new array by default
2387 $args = array($value, $extraValue);
2389 // If we have an array simply use it and pre-extend it with our value
2390 if (is_array($extraValue)) {
2391 // Make the new args array
2392 $args = array_merge(array($value), $extraValue);
2395 // Call the multi-parameter call-back
2396 $ret = call_user_func_array($filterFunction, $args);
2398 // One parameter call
2399 $ret = call_user_func($filterFunction, $value);
2407 // Check if given FQFN is a readable file
2408 function FILE_READABLE($fqfn) {
2410 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2412 // Converts timestamp selections into a timestamp
2413 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2414 // Init test variable
2417 // Get last three chars
2418 $TEST = substr($id, -3);
2420 // Improved way of checking! :-)
2421 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2422 // Found a multi-selection for timings?
2423 $TEST = substr($id, 0, -3);
2424 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)) {
2425 // Generate timestamp
2426 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2427 $DATA[] = "$TEST='".$POST[$TEST]."'";
2429 // Remove data from array
2430 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2431 unset($POST[$TEST."_".$rem]);
2435 unset($id); $skip = true; $TEST2 = $TEST;
2438 // Process this entry
2439 $skip = false; $TEST2 = "";
2442 // Reverts the german decimal comma into Computer decimal dot
2443 function REVERT_COMMA ($str) {
2444 // Default float is not a float... ;-)
2447 // Which language is selected?
2448 switch (GET_LANGUAGE()) {
2449 case "de": // German language
2450 // Remove german thousand dots first
2451 $str = str_replace(".", "", $str);
2453 // Replace german commata with decimal dot and cast it
2454 $float = (float)str_replace(",", ".", $str);
2457 default: // US and so on
2458 // Remove thousand dots first and cast
2459 $float = (float)str_replace(",", "", $str);
2466 // Handle menu-depending failed logins and return the rendered content
2467 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2468 // Default output is empty ;-)
2471 // Is the session data set?
2472 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2473 // Ignore zero values
2474 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2475 // Non-guest has login failtures found, get both data and prepare it for template
2476 //* DEBUG: */ echo __FUNCTION__.":accessLevel={$accessLevel}<br />\n";
2478 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2479 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2483 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2486 // Reset session data
2487 set_session('mxchange_'.$accessLevel.'_failtures', "");
2488 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2491 // Return rendered content
2495 function REBUILD_CACHE ($cache, $inc="") {
2496 global $cacheInstance;
2498 // Shall I remove the cache file?
2499 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2501 if ($cacheInstance->cache_file($cache, true)) {
2503 $cacheInstance->cache_destroy();
2505 // Include file given?
2507 // And rebuild it from scratch
2508 require_once(PATH."inc/loader/load_cache-".$inc.".php");
2514 //////////////////////////////////////////////////
2516 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2518 //////////////////////////////////////////////////
2520 if (!function_exists('html_entity_decode')) {
2521 // Taken from documentation on www.php.net
2522 function html_entity_decode($string) {
2523 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2524 $trans_tbl = array_flip($trans_tbl);
2525 return strtr($string, $trans_tbl);