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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
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'];
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__);
221 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
224 $gender = TRANSLATE_GENDER($gender);
226 // Insert data if content is an array
227 if (is_array($content)) {
228 // Please switch to $content[bla] in all your templates! Direct
229 // variables are deprecated as of 09/13/2008.
230 $content['gender'] = $gender;
231 $content['surname'] = $surname;
232 $content['family'] = $family;
233 $content['email'] = $email;
237 SQL_FREERESULT($result);
240 // Generate date/time string
241 $date_time = MAKE_DATETIME(time(), "1");
244 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
247 // Check for admin/guest/member templates
248 if (strpos($template, "admin_") > -1) {
249 // Admin template found
251 } elseif (strpos($template, "guest_") > -1) {
252 // Guest template found
254 } elseif (strpos($template, "member_") > -1) {
255 // Member template found
257 } elseif (strpos($template, "install_") > -1) {
258 // Installation template found
260 } elseif (strpos($template, "ext_") > -1) {
261 // Extension template found
263 } elseif (strpos($template, "la_") > -1) {
264 // "Logical-area" template found
267 // Test for extension
268 $test = substr($template, 0, strpos($template, "_"));
269 if (EXT_IS_ACTIVE($test)) {
270 // Set extra path to extension's name
275 ////////////////////////
276 // Generate file name //
277 ////////////////////////
278 $file = $BASE.$MODE.$template.".tpl";
280 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
281 // Select what depended header/footer template file for admin/guest/member area
282 $file2 = sprintf("%s%s%s_%s.tpl",
286 SQL_ESCAPE($GLOBALS['what'])
290 if (FILE_READABLE($file2)) $file = $file2;
292 // Remove variable from memory
296 // Does the special template exists?
297 if (!FILE_READABLE($file)) {
298 // Reset to default template
299 $file = $BASE.$template.".tpl";
302 // Now does the final template exists?
303 if (FILE_READABLE($file)) {
304 // The local file does exists so we load it. :)
305 $tmpl_file = implode("", file($file));
307 // Replace ' to our own chars to preventing them being quoted
308 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
310 // Do we have to compile the code?
312 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
314 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
317 // Simply return loaded code
321 // Add surrounding HTML comments to help finding bugs faster
322 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
323 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
324 // Only admins shall see this warning or when installation mode is active
325 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
326 (".basename($file).")<br />
329 <PRE>".print_r($content, true)."</PRE>
331 <PRE>".print_r($DATA, true)."</PRE>
335 // Do we have some content to output or return?
337 // Not empty so let's put it out! ;)
339 // Return the HTML code
345 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
346 // Warning, empty output!
347 return "E:".$template."<br />\n";
351 // Send mail out to an email address
352 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML='N', $FROM="") {
353 // Compile subject line (for POINTS constant etc.)
354 $eval = "\$SUBJECT = \"".COMPILE_CODE(addslashes($SUBJECT))."\";";
356 $SUBJECT = html_entity_decode($SUBJECT);
359 if ((!eregi("@", $TO)) && ($TO > 0)) {
360 // Value detected, load email from database
361 if (EXT_IS_ACTIVE("msg")) {
362 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
365 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
366 list($TO) = SQL_FETCHROW($result_email);
367 SQL_FREERESULT($result_email);
369 } elseif ($TO == 0) {
374 // Not in PHPMailer-Mode
375 if (!CHECK_PHPMAILER_USAGE()) {
377 // Load email header template
378 $FROM = LOAD_EMAIL_TEMPLATE("header");
381 $FROM .= LOAD_EMAIL_TEMPLATE("header");
383 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
385 // Load email header template
386 $FROM = LOAD_EMAIL_TEMPLATE("header");
389 $FROM .= LOAD_EMAIL_TEMPLATE("header");
393 // Fix HTML parameter (default is no!)
394 if (empty($HTML)) $HTML = "N";
395 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
396 // In debug mode we want to display the mail instead of sending it away so we can debug this part
398 ".htmlentities(trim($FROM))."
400 Subject : ".$SUBJECT."
403 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail", true))) {
404 // Send mail as HTML away
405 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
406 } elseif (!empty($TO)) {
408 $TO = COMPILE_CODE($TO);
411 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
412 } elseif ($HTML == "N") {
414 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
418 // Check if legacy or PHPMailer command
420 function CHECK_PHPMAILER_USAGE() {
421 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
425 * Send out a raw email with PHPMailer class or legacy mail() command
427 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
428 // Shall we use PHPMailer class or legacy mode?
429 if (CHECK_PHPMAILER_USAGE()) {
430 // Use PHPMailer class with SMTP enabled
431 require_once(PATH."inc/phpmailer/class.phpmailer.php");
432 require_once(PATH."inc/phpmailer/class.smtp.php");
435 $mail = new PHPMailer();
436 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
439 $mail->SMTPAuth = true;
440 $mail->Host = SMTP_HOSTNAME;
442 $mail->Username = SMTP_USER;
443 $mail->Password = SMTP_PASSWORD;
445 $mail->From = WEBMASTER;
449 $mail->FromName = MAIN_TITLE;
450 $mail->Subject = $subject;
451 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
453 $mail->AltBody = "Your mail program required HTML support to read this mail!";
454 $mail->WordWrap = 70;
459 $mail->AddAddress($to, "");
460 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
461 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
462 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
465 // Use legacy mail() command
466 @mail($to, $subject, $msg, $from);
471 // Generate a password in a specified length or use default password length
472 function GEN_PASS($LEN = 0) {
474 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
476 // Initialize array with all allowed chars
477 $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,-,+,_,/");
479 // Initialize randomizer
480 mt_srand((double) microtime() * 1000000);
482 // Start creating password
484 for ($i = 0; $i < $LEN; $i++) {
485 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
488 // When the size is below 40 we can also add additional security by scrambling it
489 if (strlen($PASS) <= 40) {
490 // Also scramble the password
491 $PASS = scrambleString($PASS);
494 // Return the password
498 function MAKE_DATETIME ($time, $mode="0")
502 return NEVER_HAPPENED;
504 // Filter out numbers
505 $time = bigintval($time);
508 switch (GET_LANGUAGE())
510 case "de": // German date / time format
512 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
513 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
514 case "2": $ret = date("d.m.Y|H:i", $time); break;
515 case "3": $ret = date("d.m.Y", $time); break;
519 default: // Default is the US date / time format!
521 case "0": $ret = date("r", $time); break;
522 case "1": $ret = date("Y-m-d - g:i A", $time); break;
523 case "2": $ret = date("y-m-d|H:i", $time); break;
524 case "3": $ret = date("y-m-d", $time); break;
530 // Translates the american decimal dot into a german comma
531 function TRANSLATE_COMMA ($dotted, $cut=true) {
534 // Default is 3 you can change this in admin area "Misc -> Misc Options"
535 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
536 $maxComma = $_CONFIG['max_comma'];
540 // Test for commata if in cut-mode
541 $com = explode(".", $dotted);
542 if (count($com) > 1) {
543 // Commata found, so only zeros?
544 if ($com[1] == str_repeat("0", strlen($com[1]))) {
545 // Only zeros, so don't display them
549 // Don't display commatas even if there are none... ;-)
555 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
558 switch (GET_LANGUAGE()) {
560 $dotted = number_format($dotted, $maxComma, ",", ".");
564 $dotted = number_format($dotted, $maxComma, ".", ",");
568 // Return translated value
573 function DEREFERER ($URL) {
574 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
579 function TRANSLATE_GENDER ($gender) {
582 case "M": $ret = GENDER_M; break;
583 case "F": $ret = GENDER_F; break;
584 case "C": $ret = GENDER_C; break;
585 default : $ret = $gender; break;
590 function GET_POOL_TYPE($PT) {
593 case "TEMP" : $ret = POOL_TEMP; break;
594 case "SEND" : $ret = POOL_SEND; break;
595 case "NEW" : $ret = POOL_NEW; break;
596 case "ADMIN" : $ret = POOL_ADMIN; break;
597 case "ACTIVE" : $ret = POOL_ACTIVE; break;
598 case "DELETED": $ret = POOL_DELETED; break;
599 default : $ret = POOL_UNKNOWN." (".$PT.")"; break;
604 function FRAMETESTER($URL) {
605 // Prepare frametester URL
606 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
608 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
610 return $frametesterUrl;
613 function SELECTION_COUNT($array) {
615 if (is_array($array)) {
616 foreach ($array as $key => $sel) {
617 if (!empty($sel)) $ret++;
623 function IMG_CODE ($code, $type, $DATA, $uid) {
624 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
627 function TRANSLATE_STATUS($status) {
631 $ret = ACCOUNT_UNCONFIRMED;
635 $ret = ACCOUNT_CONFIRMED;
639 $ret = ACCOUNT_LOCKED;
643 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
649 function GET_LANGUAGE() {
650 if (!empty($_GET['mx_lang'])) {
651 // Accept only first 2 chars
652 $lang = substr($_GET['mx_lang'], 0, 2);
658 // Set default return value to default language from config
661 // Check GET variable and cookie
663 // Check if main language file does exist
664 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
665 // Okay found, so let's update cookies
668 } elseif (!isSessionVariableSet('mx_lang')) {
669 // Return stored value from cookie
670 $ret = get_session('mx_lang');
672 // Fixes a warning before the session has the mx_lang constant
673 if (empty($ret)) $ret = DEFAULT_LANG;
678 function SET_LANGUAGE($lang) {
681 // Accept only first 2 chars!
682 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
685 set_session("mx_lang", $lang);
688 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
689 global $DATA, $_CONFIG, $REPLACER;
691 // Make sure all template names are lowercase!
692 $template = strtolower($template);
694 // Default "nickname" if extension is not installed
697 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
698 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
700 // Init variables (DEPRECATED! Use $content[bla] instead.
706 // Prepare IP number and User Agent
707 $REMOTE_ADDR = getenv('REMOTE_ADDR');
708 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
711 if (isSessionVariableSet('admin_login')) {
713 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
714 array(get_session('admin_login')), __FILE__, __LINE__);
715 list($ADMIN) = SQL_FETCHROW($result);
716 SQL_FREERESULT($result);
719 // Expiration in a nice output format
720 if ($_CONFIG['auto_purge'] == 0) {
721 // Will never expire!
722 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
723 } elseif (function_exists('CREATE_FANCY_TIME')) {
724 // Create nice date string
725 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
728 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
731 // Is content an array?
732 if (is_array($content)) {
733 // Add expiration to array, $EXPIRATION is now deprecated!
734 $content['expiration'] = $EXPIRATION;
737 // @TODO Try to rewrite this part
738 if ($template == "add-points") {
739 if (isset($_POST['points'])) {
740 $points = bigintval($_POST['points']);
742 $points = __POINTS_VALUE;
748 if (EXT_IS_ACTIVE("nickname")) {
750 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
751 array(bigintval($UID)), __FILE__, __LINE__);
752 list($surname, $family, $gender, $email, $nick) = SQL_FETCHROW($result);
753 SQL_FREERESULT($result);
756 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
757 array(bigintval($UID)), __FILE__, __LINE__);
758 list($surname, $family, $gender, $email) = SQL_FETCHROW($result);
759 SQL_FREERESULT($result);
762 // Neutral gender and email address is default
767 // Translate M to male or F to female
768 $gender = TRANSLATE_GENDER($gender);
770 // Insert data if content is an array
771 if (is_array($content)) {
772 // Please do no longer use direct variable names, use $content[bla]
774 $content['gender'] = $gender;
775 $content['surname'] = $surname;
776 $content['family'] = $family;
777 $content['email'] = $email;
778 $content['nick'] = $nick;
781 // Store email for some functions in global data array
782 $DATA['email'] = $email;
785 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
787 // Check for admin/guest/member templates
788 if (strpos($template, "admin_") > -1) {
789 // Admin template found
790 $file = $BASE."admin/".$template.".tpl";
791 } elseif (strpos($template, "guest_") > -1) {
792 // Guest template found
793 $file = $BASE."guest/".$template.".tpl";
794 } elseif (strpos($template, "member_") > -1) {
795 // Member template found
796 $file = $BASE."member/".$template.".tpl";
798 // Test for extension
799 $test = substr($template, 0, strpos($template, "_"));
800 if (EXT_IS_ACTIVE($test)) {
801 // Set extra path to extension's name
802 $file = $BASE.$test."/".$template.".tpl";
804 // No special filename
805 $file = $BASE.$template.".tpl";
809 // Does the special template exists?
810 if (!FILE_READABLE($file)) {
811 // Reset to default template
812 $file = $BASE.$template.".tpl";
815 // Now does the final template exists?
817 if (FILE_READABLE($file)) {
818 // The local file does exists so we load it. :)
819 $tmpl_file = @implode("", @file($file));
820 $tmpl_file = addslashes($tmpl_file);
823 $tmpl_file = "\$newContent=\"".COMPILE_CODE($tmpl_file)."\";";
826 // Replace HTML conform chars
827 $newContent = html_entity_decode($newContent);
828 } elseif (!empty($template)) {
829 // Template file not found!
830 $newContent = TEMPLATE_404.": ".$template."<br />
832 <PRE>".print_r($newContent, true)."</PRE>
834 <PRE>".print_r($DATA, true)."</PRE>
837 // Debug mode not active? Then remove the HTML tags
838 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
840 // No template name supplied!
841 $newContent = NO_TEMPLATE_SUPPLIED;
844 // Is there some content?
845 if (empty($newContent)) {
847 $newContent = "Compiler error for template {$template}!";
850 // Return compiled content
851 return COMPILE_CODE($newContent);
854 function MAKE_TIME($H, $M, $S, $stamp) {
855 // Extract day, month and year from given timestamp
856 $DAY = date("d", $stamp);
857 $MONTH = date("m", $stamp);
858 $YEAR = date('Y', $stamp);
860 // Create timestamp for wished time which depends on extracted date
861 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
864 function LOAD_URL($URL, $addUrlData=true) {
865 global $CSS, $_CONFIG, $footer;
867 // Check if http(s):// is there
868 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
869 // Make all URLs full-qualified
873 // Compile out URI codes
874 $URL = COMPILE_CODE($URL);
877 $OUTPUT = ob_get_contents();
882 // Add some data to URL if cookies are not accepted
883 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
885 // Probe for bot from search engine
886 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
887 // Search engine bot detected so let's rewrite many chars for the link
888 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
890 // Output new location link as anchor
891 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
892 } elseif (!headers_sent()) {
893 // Load URL when headers are not sent
896 debug_print_backtrace();
897 die("</pre>URL={$URL}");
899 @header ("Location: ".str_replace("&", "&", $URL));
901 // Output error message
902 include(PATH."inc/header.php");
903 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
904 include(PATH."inc/footer.php");
909 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
910 global $SEC_CHARS, $URL_CHARS;
913 // Select smaller set of chars to replace when we e.g. want to compile URLs
914 if (!$full) $ARRAY = $URL_CHARS;
918 // BEFORE 0.2.1 : Language and data constants
919 // WITH 0.2.1+ : Only language constants
920 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
922 // BEFORE 0.2.1 : Not used
923 // WITH 0.2.1+ : Data constants
924 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
927 // Compile QUOT and other non-HTML codes
928 foreach ($ARRAY['to'] as $k => $to) {
929 // Do the reversed thing as in inc/libs/security_functions.php
930 $code = str_replace($to, $ARRAY['from'][$k], $code);
933 // But shall I keep simple quotes for later use?
934 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
936 // Find $content[bla][blub] entries
937 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
939 // Are some matches found?
940 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
941 // Replace all matches
942 $matchesFound = array();
943 foreach ($matches[0] as $key => $match) {
944 // Avoid replacing matches multiple times
945 if (!isset($matchesFound[$match])) {
947 $code = str_replace($match, "\".".$match.".\"", $code);
948 $matchesFound[$match] = 1;
951 // Take all string elements
952 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
953 // Replace it in the code
954 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
955 $code = str_replace($match, $newMatch, $code);
956 $matchesFound[$key."_".$matches[4][$key]] = 1;
961 // Return compiled code
965 /************************************************************************
967 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
968 * $a_sort sortiert: *
970 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
971 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
972 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
973 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
974 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
976 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
977 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
978 * Sie, dass es doch nicht so schwer ist! :-) *
980 ************************************************************************/
981 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
984 while ($primary_key < count($a_sort)) {
985 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
986 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
989 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
990 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
991 } elseif ($key != $key2) {
992 // Sort numbers (E.g.: 9 < 10)
993 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
994 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
998 // We have found two different values, so let's sort whole array
999 foreach ($dummy as $sort_key => $sort_val) {
1000 $t = $dummy[$sort_key][$key];
1001 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1002 $dummy[$sort_key][$key2] = $t;
1013 // Write back sorted array
1017 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1019 global $MONTH_DESCR; $OUT = "";
1022 // This is a yes/no selection only!
1023 if ($id > 0) $prefix .= "[".$id."]";
1024 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1028 // Begin with regular selection box here
1029 if (!empty($prefix)) $prefix .= "_";
1031 if ($id > 0) $type2 .= "[".$id."]";
1032 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1037 for ($idx = 1; $idx < 32; $idx++)
1039 $OUT .= "<OPTION value=\"".$idx."\"";
1040 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1041 $OUT .= ">".$idx."</OPTION>\n";
1045 case "month": // Month
1046 foreach ($MONTH_DESCR as $month => $descr)
1048 $OUT .= "<OPTION value=\"".$month."\"";
1049 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1050 $OUT .= ">".$descr."</OPTION>\n";
1054 case "year": // Year
1056 $YEAR = date('Y', time());
1058 // Check if the default value is larger than minimum and bigger than actual year
1059 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1061 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1063 $OUT .= "<OPTION value=\"".$idx."\"";
1064 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1065 $OUT .= ">".$idx."</OPTION>\n";
1068 elseif ($DEFAULT == -1)
1070 // Current year minus 1
1071 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1073 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1078 // Get current year and subtract 16 (for erotic content)
1079 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1080 $YEAR = date('Y', time()) - 16;
1081 for ($idx = 1930; $idx <= $YEAR; $idx++)
1083 $OUT .= "<OPTION value=\"".$idx."\"";
1084 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1085 $OUT .= ">".$idx."</OPTION>\n";
1092 for ($idx = 0; $idx < 60; $idx+=5) {
1093 if (strlen($idx) == 1) $idx = "0".$idx;
1094 $OUT .= "<OPTION value=\"".$idx."\"";
1095 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1096 $OUT .= ">".$idx."</OPTION>\n";
1101 for ($idx = 0; $idx < 24; $idx++) {
1102 if (strlen($idx) == 1) $idx = "0".$idx;
1103 $OUT .= "<OPTION value=\"".$idx."\"";
1104 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1105 $OUT .= ">".$idx."</OPTION>\n";
1110 $OUT .= "<OPTION value=\"Y\"";
1111 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1112 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1113 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1114 $OUT .= ">".NO."</OPTION>\n";
1117 $OUT .= " </SELECT>\n";
1121 function TRANSLATE_YESNO($yn)
1125 case 'Y': $yn = YES; break;
1126 case 'N': $yn = NO; break;
1127 default : $yn = "??? (".$yn.")"; break;
1132 // Deprecated : $length
1135 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1138 // Fix missing _MAX constant
1139 if (!defined('_MAX')) define('_MAX', 15235);
1141 // Build server string
1142 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1145 $keys = SITE_KEY.":".DATE_KEY;
1146 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1147 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1148 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1149 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1151 // Build string from misc data
1152 $data = $code.":".$uid.":".$DATA;
1154 // Add more additional data
1155 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1156 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1157 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1158 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1159 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1160 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1162 // Calculate number for generating the code
1163 $a = $code + _ADD - 1;
1165 if (isset($_CONFIG['master_hash'])) {
1166 // Generate hash with master salt from modula of number with the prime number and other data
1167 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1169 // Create number from hash
1170 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1172 // Generate hash with "hash of site key" 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, substr(sha1(SITE_KEY), 0, 8));
1175 // Create number from hash
1176 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1179 // At least 10 numbers shall be secure enought!
1180 $len = $_CONFIG['code_length'];
1181 if ($len == 0) $len = 10;
1183 // Cut off requested counts of number
1184 $return = substr(str_replace('.', "", $rcode), 0, $len);
1186 // Done building code
1189 // Does only allow numbers
1190 function bigintval($num, $castValue = true) {
1191 // Filter all numbers out
1192 $ret = preg_replace("/[^0123456789]/", "", $num);
1195 if ($castValue) $ret = (double)$ret;
1197 // Has the whole value changed?
1198 if ("".$ret."" != "".$num."") {
1200 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1206 // Insert the code in $img_code into jpeg or PNG image
1207 function GENERATE_IMAGE($img_code, $header=true) {
1210 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1211 // Stop execution of function here because of over-sized code length
1213 } elseif (!$header) {
1214 // Return in an HTML code code
1215 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1219 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1220 if (FILE_READABLE($img)) {
1221 // Switch image type
1222 switch ($_CONFIG['img_type'])
1225 // Okay, load image and hide all errors
1226 $image = @imagecreatefromjpeg($img);
1230 // Okay, load image and hide all errors
1231 $image = @imagecreatefrompng($img);
1235 // Exit function here
1239 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1240 $text_color = imagecolorallocate($image, 0, 0, 0);
1242 // Insert code into image
1243 imagestring($image, 5, 14, 2, $img_code, $text_color);
1245 // Return to browser
1246 header ("Content-Type: image/".$_CONFIG['img_type']);
1248 // Output image with matching image factory
1249 switch ($_CONFIG['img_type']) {
1250 case "jpg": imagejpeg($image); break;
1251 case "png": imagepng($image); break;
1254 // Remove image from memory
1255 imagedestroy($image);
1257 // Create selection box or array of splitted timestamp
1258 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1259 // Calculate 15-seconds timestamp (15-seconds-steps shall be fine ;) )
1260 $stamp = round($timestamp / 15) * 15;
1262 // Do we have a leap year?
1264 $TEST = date('Y', time()) / 4;
1265 $M1 = date("m", time());
1266 $M2 = date("m", (time() + $stamp));
1268 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1269 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1271 // First of all years...
1272 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1274 $M = abs(floor($stamp / 2628000 - $Y * 12));
1276 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1278 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1280 $h = abs(floor($stamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1282 $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));
1283 // And at last seconds...
1284 $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));
1286 // Is seconds zero and time is < 60 seconds?
1287 if (($s == 0) && ($stamp < 60)) {
1293 // Now we convert them in seconds...
1295 if ($return_array) {
1296 // Just put all data in an array for later use
1308 $OUT = "<DIV align=\"".$align."\">\n";
1309 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1312 if (ereg('Y', $display) || (empty($display))) {
1313 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1316 if (ereg("M", $display) || (empty($display))) {
1317 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1320 if (ereg("W", $display) || (empty($display))) {
1321 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1324 if (ereg("D", $display) || (empty($display))) {
1325 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1328 if (ereg("h", $display) || (empty($display))) {
1329 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1332 if (ereg("m", $display) || (empty($display))) {
1333 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1336 if (ereg("s", $display) || (empty($display))) {
1337 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1343 if (ereg('Y', $display) || (empty($display))) {
1344 // Generate year selection
1345 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1346 for ($idx = 0; $idx <= 10; $idx++) {
1347 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1348 if ($idx == $Y) $OUT .= " selected default";
1349 $OUT .= ">".$idx."</OPTION>\n";
1351 $OUT .= " </SELECT></TD>\n";
1353 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1356 if (ereg("M", $display) || (empty($display))) {
1357 // Generate month selection
1358 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1359 for ($idx = 0; $idx <= 11; $idx++)
1361 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1362 if ($idx == $M) $OUT .= " selected default";
1363 $OUT .= ">".$idx."</OPTION>\n";
1365 $OUT .= " </SELECT></TD>\n";
1367 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1370 if (ereg("W", $display) || (empty($display))) {
1371 // Generate week selection
1372 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1373 for ($idx = 0; $idx <= 4; $idx++) {
1374 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1375 if ($idx == $W) $OUT .= " selected default";
1376 $OUT .= ">".$idx."</OPTION>\n";
1378 $OUT .= " </SELECT></TD>\n";
1380 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1383 if (ereg("D", $display) || (empty($display))) {
1384 // Generate day selection
1385 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1386 for ($idx = 0; $idx <= 31; $idx++) {
1387 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1388 if ($idx == $D) $OUT .= " selected default";
1389 $OUT .= ">".$idx."</OPTION>\n";
1391 $OUT .= " </SELECT></TD>\n";
1393 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1396 if (ereg("h", $display) || (empty($display))) {
1397 // Generate hour selection
1398 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1399 for ($idx = 0; $idx <= 23; $idx++) {
1400 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1401 if ($idx == $h) $OUT .= " selected default";
1402 $OUT .= ">".$idx."</OPTION>\n";
1404 $OUT .= " </SELECT></TD>\n";
1406 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1409 if (ereg("m", $display) || (empty($display))) {
1410 // Generate minute selection
1411 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1412 for ($idx = 0; $idx <= 59; $idx++) {
1413 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1414 if ($idx == $m) $OUT .= " selected default";
1415 $OUT .= ">".$idx."</OPTION>\n";
1417 $OUT .= " </SELECT></TD>\n";
1419 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1422 if (ereg("s", $display) || (empty($display))) {
1423 // Generate second selection
1424 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1425 for ($idx = 0; $idx <= 45; $idx += 15) {
1426 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1427 if ($idx == $s) $OUT .= " selected default";
1428 $OUT .= ">".$idx."</OPTION>\n";
1430 $OUT .= " </SELECT></TD>\n";
1432 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1435 $OUT .= "</TABLE>\n";
1437 // Return generated HTML code
1442 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1445 // Do we have a leap year?
1447 $TEST = date('Y', time()) / 4;
1448 $M1 = date("m", time());
1449 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1450 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1451 // First add years...
1452 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1454 $ret += $POST[$prefix."_mo"] * 2628000;
1456 $ret += $POST[$prefix."_we"] * 604800;
1458 $ret += $POST[$prefix."_da"] * 86400;
1460 $ret += $POST[$prefix."_ho"] * 3600;
1462 $ret += $POST[$prefix."_mi"] * 60;
1463 // And at last seconds...
1464 $ret += $POST[$prefix."_se"];
1465 // Return calculated value
1468 // Sends out mail to all administrators
1469 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1470 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1471 // Trim template name
1472 $template = trim($template);
1474 // Load email template
1475 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1477 if (GET_EXT_VERSION("admins") < "0.4.0") {
1478 // Older version detected!
1479 return SEND_ADMIN_EMAILS($subj, $msg);
1482 // Check which admin shall receive this mail
1483 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1484 array($template), __FILE__, __LINE__);
1485 if (SQL_NUMROWS($result) == 0) {
1486 // Create new entry (to all admins)
1487 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1488 array($template), __FILE__, __LINE__);
1490 // Load admin IDs...
1492 while(list($aid) = SQL_FETCHROW($result)) {
1497 SQL_FREERESULT($result);
1499 // "implode" IDs and query string
1500 $aid = implode(",", $aids);
1502 // Add line to userlog
1503 USERLOG_ADD_LINE($subj, $msg, $UID);
1505 } elseif ($aid == "0") {
1506 // Select all email adresses
1507 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1509 // If Admin-ID is not "to-all" select
1510 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1514 // Load email addresses and send away
1515 while (list($email) = SQL_FETCHROW($result)) {
1516 SEND_EMAIL($email, $subj, $msg);
1520 SQL_FREERESULT($result);
1523 function CREATE_FANCY_TIME($stamp) {
1524 // Get data array with years/months/weeks/days/...
1525 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1527 foreach($data as $k => $v) {
1529 // Value is greater than 0 "eval" data to return string
1530 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1536 // Remove leading commata and space
1537 $ret = substr($ret, 2);
1539 // Return fancy time string
1543 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1544 $SEP = ""; $TOP = "";
1547 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1551 for ($page = 1; $page <= $PAGES; $page++) {
1552 // Is the page currently selected or shall we generate a link to it?
1553 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1554 // Is currently selected, so only highlight it
1555 $NAV .= "<STRONG>-";
1557 // Open anchor tag and add base URL
1558 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1560 // Add userid when we shall show all mails from a single member
1561 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1563 // Close open anchor tag
1567 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1568 // Is currently selected, so only highlight it
1569 $NAV .= "-</STRONG>";
1575 // Add seperator if we have not yet reached total pages
1576 if ($page < $PAGES) $NAV .= " | ";
1579 // Define constants only once
1580 if (!defined('__NAV_OUTPUT')) {
1581 define('__NAV_OUTPUT' , $NAV);
1582 define('__NAV_COLSPAN', $colspan);
1583 define('__NAV_TOP' , $TOP);
1584 define('__NAV_SEP' , $SEP);
1587 // Load navigation template
1588 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1591 // Return generated HTML-Code
1599 // Extract host from script name
1600 function EXTRACT_HOST (&$script) {
1601 // Use default SERVER_URL by default... ;) So?
1604 // Is this URL valid?
1605 if (substr($script, 0, 7) == "http://") {
1606 // Use the hostname from script URL as new hostname
1607 $url = substr($script, 7);
1608 $extract = explode("/", $url);
1610 // Done extracting the URL :)
1613 // Extract host name
1614 $host = str_replace("http://", "", $url);
1615 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1617 // Generate relative URL
1618 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1619 if (substr(strtolower($script), 0, 7) == "http://") {
1620 // But only if http:// is in front!
1621 $script = substr($script, (strlen($url) + 7));
1622 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1624 $script = substr($script, (strlen($url) + 8));
1627 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1628 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1634 // Send a GET request
1635 function GET_URL ($script) {
1636 // Compile the script name
1637 $script = COMPILE_CODE($script);
1639 // Extract host name from script
1640 $host = EXTRACT_HOST($script);
1642 // Generate GET request header
1643 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1644 $request .= "Host: " . $host . "\r\n";
1645 $request .= "Referer: " . URL . "/admin.php\r\n";
1646 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1647 $request .= "Content-Type: text/plain\r\n";
1648 $request .= "Cache-Control: no-cache\r\n";
1649 $request .= "Connection: Close\r\n\r\n";
1651 // Send the raw request
1652 $response = SEND_RAW_REQUEST($host, $request);
1654 // Return the result to the caller function
1658 // Send a POST request
1659 function POST_URL ($script, $postData) {
1660 // Is postData an array?
1661 if (!is_array($postData)) {
1663 return array("", "", "");
1666 // Compile the script name
1667 $script = COMPILE_CODE($script);
1669 // Extract host name from script
1670 $host = EXTRACT_HOST($script);
1672 // Construct request
1673 $data = http_build_query($postData, '', '&');
1675 // Generate POST request header
1676 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1677 $request .= "Host: " . $host . "\r\n";
1678 $request .= "Referer: " . URL . "/admin.php\r\n";
1679 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1680 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1681 $request .= "Content-length: " . strlen($data) . "\r\n";
1682 $request .= "Cache-Control: no-cache\r\n";
1683 $request .= "Connection: Close\r\n\r\n";
1686 // Send the raw request
1687 $response = SEND_RAW_REQUEST($host, $request);
1689 // Return the result to the caller function
1693 // Sends a raw request to another host
1694 function SEND_RAW_REQUEST ($host, $request) {
1698 $response = array("", "", "");
1700 // Default is not to use proxy
1703 // Are proxy settins set?
1704 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1710 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1712 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1714 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1718 if (!is_resource($fp)) {
1725 // Generate CONNECT request header
1726 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1727 $proxyTunnel .= "Host: ".$host."\r\n";
1729 // Use login data to proxy? (username at least!)
1730 if (!empty($_CONFIG['proxy_username'])) {
1732 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1733 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1736 // Add last new-line
1737 $proxyTunnel .= "\r\n";
1738 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1741 fputs($fp, $proxyTunnel);
1745 // No response received
1749 // Read the first line
1750 $resp = trim(fgets($fp, 10240));
1751 $respArray = explode(" ", $resp);
1752 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1753 // Invalid response!
1759 fputs($fp, $request);
1763 $response[] = trim(fgets($fp, 1024));
1769 // Skip first empty lines
1771 foreach ($resp as $idx => $line) {
1773 $line = trim($line);
1775 // Is this line empty?
1778 array_shift($response);
1780 // Abort on first non-empty line
1785 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1787 // Proxy agent found?
1788 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1789 // Proxy header detected, so remove two lines
1790 array_shift($response);
1791 array_shift($response);
1794 // Was the request successfull?
1795 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1796 // Not found / access forbidden
1797 $response = array("", "", "");
1803 // Taken from www.php.net eregi() user comments
1804 function VALIDATE_EMAIL($email) {
1806 $email = COMPILE_CODE($email);
1808 // Check first part of email address
1809 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1812 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1815 $regex = "^".$first."@".$domain."$";
1817 // Return check result
1818 return eregi($regex, $email);
1820 // Function taken from user comments on www.php.net / function eregi()
1821 function VALIDATE_URL ($URL, $compile=true) {
1822 // Trim URL a little
1823 $URL = trim(urldecode($URL));
1824 //* DEBUG: */ echo $URL."<br />";
1826 // Compile some chars out...
1827 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1828 //* DEBUG: */ echo $URL."<br />";
1830 // Check for the extension filter
1831 if (EXT_IS_ACTIVE("filter")) {
1832 // Use the extension's filter set
1833 return FILTER_VALIDATE_URL($URL, false);
1836 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1837 // https:// in front of the URLs
1838 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1841 function MEMBER_ACTION_LINKS($uid, $status="") {
1842 // Define all main targets
1843 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1845 // Begin of navigation links
1846 $eval = "\$OUT = \"[ ";
1848 foreach ($TARGETS as $tar) {
1849 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1850 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1851 if (($tar == "lock_user") && ($status == "LOCKED")) {
1852 // Locked accounts shall be unlocked
1853 $eval .= "UNLOCK_USER";
1855 // All other status is fine
1856 $eval .= strtoupper($tar);
1858 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1859 if (($tar == "lock_user") && ($status == "LOCKED")) {
1860 // Locked accounts shall be unlocked
1861 $eval .= "UNLOCK_USER";
1863 // All other status is fine
1864 $eval .= strtoupper($tar);
1866 $eval .= ".\"</A></SPAN> | ";
1869 // Finish navigation link
1870 $eval = substr($eval, 0, -7)."]\";";
1876 // Function for backward-compatiblity
1877 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1878 // Load it from the register extension
1879 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1881 // Generate an email link
1882 function CREATE_EMAIL_LINK($email, $table="admins") {
1883 // Default email link (INSECURE! Spammer can read this by harvester programs)
1884 $EMAIL = "mailto:".$email;
1886 // Check for several extensions
1887 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1888 // Create email link for contacting admin in guest area
1889 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1890 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1891 // Create email link for contacting a member within admin area (or later in other areas, too?)
1892 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1893 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1894 // Create email link to contact sponsor within admin area (or like the link above?)
1895 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1898 // Shall I close the link when there is no admin?
1899 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1901 // Return email link
1904 // Generate a hash for extra-security for all passwords
1905 function generateHash ($plainText, $salt = "") {
1906 global $_CONFIG, $_SERVER;
1908 // Is the required extension "sql_patches" there and a salt is not given?
1909 if (((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1910 // Extension sql_patches is missing/outdated so we return the plain text
1914 // Do we miss an arry element here?
1915 if (!isset($_CONFIG['file_hash'])) {
1917 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1918 debug_print_backtrace();
1922 // When the salt is empty build a new one, else use the first x configured characters as the salt
1924 // Build server string
1925 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1928 $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'];
1931 $data = $plainText.":".uniqid(rand(), true).":".time();
1933 // Calculate number for generating the code
1934 $a = time() + _ADD - 1;
1936 // Generate SHA1 sum from modula of number and the prime number
1937 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1938 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br>";
1939 $sha1 = scrambleString($sha1);
1940 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br>";
1941 //* DEBUG: */ $sha1b = descrambleString($sha1);
1942 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br>";
1944 // Generate the password salt string
1945 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1946 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1949 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1950 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1954 return $salt.sha1($salt.$plainText);
1957 function scrambleString($str) {
1963 // Final check, in case of failture it will return unscrambled string
1964 if (strlen($str) > 40) {
1965 // The string is to long
1967 } elseif (strlen($str) == 40) {
1969 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1971 // Generate new numbers
1972 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1975 // Scramble string here
1976 //* DEBUG: */ echo "***Original=".$str."***<br />";
1977 for ($idx = 0; $idx < strlen($str); $idx++) {
1978 // Get char on scrambled position
1979 $char = substr($str, $scrambleNums[$idx], 1);
1981 // Add it to final output string
1982 $scrambled .= $char;
1985 // Return scrambled string
1986 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
1990 function descrambleString($str) {
1992 // Scramble only 40 chars long strings
1993 if (strlen($str) != 40) return $str;
1995 // Load numbers from config
1996 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1999 if (count($scrambleNums) != 40) return $str;
2001 // Begin descrambling
2002 $orig = str_repeat(" ", 40);
2003 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2004 for ($idx = 0; $idx < 40; $idx++) {
2005 $char = substr($str, $idx, 1);
2006 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2009 // Return scrambled string
2010 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2014 function genScrambleString($len) {
2015 // Prepare randomizer and array for the numbers
2016 mt_srand((double) microtime() * 1000000);
2017 $scrambleNumbers = array();
2019 // First we need to setup randomized numbers from 0 to 31
2020 for ($idx = 0; $idx < $len; $idx++) {
2022 $rand = mt_rand(0, ($len -1));
2024 // Check for it by creating more numbers
2025 while (array_key_exists($rand, $scrambleNumbers)) {
2026 $rand = mt_rand(0, ($len -1));
2030 $scrambleNumbers[$rand] = $rand;
2033 // So let's create the string for storing it in database
2034 $scrambleString = implode(":", $scrambleNumbers);
2035 return $scrambleString;
2037 // Append data like session ID referral ID to the given URL which would
2038 // normally be stored in cookies
2039 function ADD_URL_DATA($URL) {
2043 // Determine URL binder
2045 if (strpos($URL, "?") !== false) $BIND = "&";
2047 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2048 // Cookies are not accepted
2049 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2050 // Cookie found in URL
2051 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2052 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2053 // Not found! So let's set default here
2054 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2057 // Is there already added data? Then change the binder
2058 if (!empty($ADD)) $BIND = "&";
2061 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2062 // Add session from URL
2063 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2065 // Add current session
2066 $ADD .= $BIND."PHPSESSID=".session_id();
2070 // Add all together and return it
2073 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2074 function generatePassString($passHash) {
2077 // Return vanilla password hash
2080 // Is a secret key and master salt already initialized?
2081 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2082 // Only calculate when the secret key is generated
2083 $newHash = ""; $start = 9;
2084 for ($idx = 0; $idx < 10; $idx++) {
2085 $part1 = hexdec(substr($passHash, $start, 4));
2086 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2087 $mod = dechex($idx);
2088 if ($part1 > $part2) {
2089 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2090 } elseif ($part2 > $part1) {
2091 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2093 $mod = substr(round($mod), 0, 4);
2094 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2095 //* DEBUG: */ echo "*".$start."=".$mod."*<br>";
2100 //* DEBUG: */ print($passHash."<br>".$newHash." (".strlen($newHash).")");
2101 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2102 //* DEBUG: */ print($ret."<br />\n");
2105 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2106 $ret = md5($passHash);
2107 //* DEBUG: */ echo "++".$ret."++<br />\n";
2114 // Fix "deleted" cookies
2115 function FIX_DELETED_COOKIES ($cookies) {
2116 // Is this an array with entries?
2117 if ((is_array($cookies)) && (count($cookies) > 0)) {
2118 // Then check all cookies if they are marked as deleted!
2119 foreach ($cookies as $cookieName) {
2120 // Is the cookie set to "deleted"?
2121 if (get_session($cookieName) == "deleted") {
2122 set_session($cookieName, "");
2128 // Output error messages in a fasioned way and die...
2129 function mxchange_die ($msg) {
2132 // Load the message template
2133 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2136 include(PATH."inc/footer.php");
2142 // Display parsing time and number of SQL queries in footer
2143 function DISPLAY_PARSING_TIME_FOOTER() {
2144 global $startTime, $_CONFIG;
2145 $endTime = microtime(true);
2147 // Is the timer started?
2148 if (!isset($GLOBALS['startTime'])) {
2153 // "Explode" both times
2154 $start = explode(" ", $GLOBALS['startTime']);
2155 $end = explode(" ", $endTime);
2156 $runTime = $end[0] - $start[0];
2157 if ($runTime < 0) $runTime = 0;
2158 $runTime = TRANSLATE_COMMA($runTime);
2162 'runtime' => $runTime,
2163 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2164 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2167 // Load the template
2168 LOAD_TEMPLATE("show_timings", false, $content);
2171 // Unset/set session variables
2172 function set_session ($var, $value) {
2175 // Abort in CSS mode here
2176 if ($CSS == 1) return true;
2178 // Trim value and session variable
2179 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2181 // Is the session variable set?
2182 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2183 // Remove the session
2184 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2185 unset($_SESSION[$var]);
2186 return session_unregister($var);
2187 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2189 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2190 $_SESSION[$var] = $value;
2191 return session_register($var);
2192 } elseif (!empty($value)) {
2194 $_SESSION[$var] = $value;
2196 // Something bad happens!
2197 return false; // Hope this doesn't make so much trouble???
2200 // Return always true if the session variable is already set.
2201 // Keept me busy for a longer while...
2202 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2206 // Check wether a boolean constant is set
2207 // Taken from user comments in PHP documentation for function constant()
2208 function isBooleanConstantAndTrue($constname) { // : Boolean
2210 if (defined($constname)) $res = (constant($constname) === true);
2214 // Check wether a session variable is set
2215 function isSessionVariableSet($var) {
2216 return (isset($_SESSION[$var]));
2218 // Returns wether the value of the session variable or NULL if not set
2219 function get_session($var) {
2220 // Default is not found! ;-)
2223 // Is the variable there?
2224 if (isSessionVariableSet($var)) {
2225 // Then get it secured!
2226 $value = SQL_ESCAPE($_SESSION[$var]);
2232 // Send notification to admin
2233 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2234 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2236 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2238 // Send outdated way
2239 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2240 SEND_ADMIN_EMAILS($subject, $msg);
2243 // Destroy user session
2244 function destroy_user_session () {
2245 // Remove all user data from session
2246 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2248 // Merges an array together but only if both are arrays
2249 function merge_array ($array1, $array2) {
2250 // Are both an array?
2251 if ((is_array($array1)) && (is_array($array2))) {
2252 // Merge all together
2253 return array_merge($array1, $array2);
2254 } elseif (is_array($array1)) {
2255 // Return left array
2259 // Something wired happened here...
2260 print(__FUNCTION__.":<pre>");
2261 debug_print_backtrace();
2264 // Debug message logger
2265 function DEBUG_LOG ($message) {
2266 // Is debug mode enabled?
2267 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
2268 // Log this message away
2269 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2270 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2274 // Reads a directory with PHP files in and gets only files back
2275 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2279 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2282 while ($baseFile = readdir($dirPointer)) {
2283 // Load file only if extension is active
2285 $file = $baseDir.$baseFile;
2287 // Is this a valid reset file?
2288 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2289 // Remove both for extension name
2290 $extName = substr($baseFile, strlen($prefix), -4);
2293 $extId = GET_EXT_ID($extName);
2295 // Is the extension valid and active?
2296 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2297 // Then add this file
2304 closedir($dirPointer);
2306 // Return array with include files
2309 // Load more reset scripts
2310 function RESET_ADD_INCLUDES () {
2313 // Is the reset set or old sql_patches?
2314 if ((!isBooleanConstantAndTrue('__DAILY_RESET')) || (GET_EXT_VERSION("sql_patches") < "0.4.5")) {
2319 // Get more daily reset scripts
2320 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2322 // Create current week mark
2323 $currWeek = date("W", time());
2326 if ($_CONFIG['last_week'] != $currWeek) {
2327 // Include weekly reset scripts
2328 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2331 UPDATE_CONFIG("last_week", $currWeek);
2334 // Create current month mark
2335 $currMonth = date("m", time());
2338 if ($_CONFIG['last_month'] != $currMonth) {
2339 // Include monthly reset scripts
2340 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2343 UPDATE_CONFIG("last_month", $currMonth);
2349 // Handle extra values
2350 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2351 // Default is the value itself
2354 // Do we have a special filter function?
2355 if (!empty($filterFunction)) {
2356 // Does the filter function exist?
2357 if (function_exists($filterFunction)) {
2358 // Do we have extra parameters here?
2359 if (!empty($extraValue)) {
2360 // Put both parameters in one new array by default
2361 $args = array($value, $extraValue);
2363 // If we have an array simply use it and pre-extend it with our value
2364 if (is_array($extraValue)) {
2365 // Make the new args array
2366 $args = array_merge(array($value), $extraValue);
2369 // Call the multi-parameter call-back
2370 $ret = call_user_func_array($filterFunction, $args);
2372 // One parameter call
2373 $ret = call_user_func($filterFunction, $value);
2381 // Check if given FQFN is a readable file
2382 function FILE_READABLE($fqfn) {
2384 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2386 // Converts timestamp selections into a timestamp
2387 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2388 // Init test variable
2391 // Get last three chars
2392 $TEST = substr($id, -3);
2394 // Improved way of checking! :-)
2395 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2396 // Found a multi-selection for timings?
2397 $TEST = substr($id, 0, -3);
2398 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)) {
2399 // Generate timestamp
2400 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2401 $DATA[] = "$TEST='".$POST[$TEST]."'";
2403 // Remove data from array
2404 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2405 unset($POST[$TEST."_".$rem]);
2409 unset($id); $skip = true; $TEST2 = $TEST;
2412 // Process this entry
2413 $skip = false; $TEST2 = "";
2416 // Reverts the german decimal comma into Computer decimal dot
2417 function REVERT_COMMA ($str) {
2418 $float = (float)str_replace(",", ".", $str);
2422 //////////////////////////////////////////////////
2424 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2426 //////////////////////////////////////////////////
2428 if (!function_exists('html_entity_decode')) {
2429 // Taken from documentation on www.php.net
2430 function html_entity_decode($string) {
2431 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2432 $trans_tbl = array_flip($trans_tbl);
2433 return strtr($string, $trans_tbl);