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_INC_WRITEABLE($inc) {
43 $fqfn = sprintf("%sinc/%s.php", constant('PATH'), $inc);
45 // Abort by simple test
46 if ((FILE_READABLE($fqfn)) && (!is_writeable($fqfn))) {
50 // Test if we can append data
51 $fp = @fopen($fqfn, 'a');
52 if ($inc == "dummy") {
57 // Close all other files
62 // Output HTML code directly or "render" it. You addionally switch the new-line character off
63 function OUTPUT_HTML ($HTML, $NEW_LINE = true) {
64 // Some global variables
65 global $OUTPUT, $footer, $CSS;
67 // Do we have HTML-Code here?
69 // Yes, so we handle it as you have configured
70 switch (constant('OUTPUT_MODE'))
73 // That's why you don't need any \n at the end of your HTML code... :-)
74 if (_OB_CACHING == "on") {
75 // Output into PHP's internal buffer
78 // That's why you don't need any \n at the end of your HTML code... :-)
79 if ($NEW_LINE) echo "\n";
81 // Render mode for old or lame servers...
84 // That's why you don't need any \n at the end of your HTML code... :-)
85 if ($NEW_LINE) $OUTPUT .= "\n";
90 // If we are switching from render to direct output rendered code
91 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
93 // The same as above... ^
95 if ($NEW_LINE) echo "\n";
99 // Huh, something goes wrong or maybe you have edited config.php ???
100 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
101 mxchange_die("<strong>{!FATAL_ERROR!}:</strong> {!LANG_NO_RENDER_DIRECT!}");
104 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
105 // Headers already sent?
106 if (headers_sent()) {
108 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
110 // Trigger an user error
111 trigger_error("Headers are already sent!");
114 // Output cached HTML code
115 $OUTPUT = ob_get_contents();
117 // Clear output buffer for later output
121 header("HTTP/1.1 200");
124 $now = gmdate('D, d M Y H:i:s') . ' GMT';
126 // General headers for no caching
127 header("Expired: " . $now); // RFC2616 - Section 14.21
128 header("Last-Modified: " . $now);
129 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
130 header("Pragma: no-cache"); // HTTP/1.0
131 header("Connection: Close");
133 // Extension "rewrite" installed?
134 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
135 $OUTPUT = REWRITE_LINKS($OUTPUT);
138 // Compile and run finished rendered HTML code
139 while (strpos($OUTPUT, '{!') > 0) {
140 // Prepare the content and eval() it...
142 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
145 // Was that eval okay?
146 if (empty($newContent)) {
147 // Something went wrong!
148 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
150 $OUTPUT = $newContent;
153 // Output code here, DO NOT REMOVE! ;-)
155 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
156 // Rewrite links when rewrite extension is active
157 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
158 $OUTPUT = REWRITE_LINKS($OUTPUT);
161 // Compile and run finished rendered HTML code
162 while (strpos($OUTPUT, '{!') > 0) {
163 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
167 // Output code here, DO NOT REMOVE! ;-)
172 // Output the raw HTML code
173 function OUTPUT_RAW ($HTML) {
174 // Output stripped HTML code to avoid broken JavaScript code, etc.
175 echo stripslashes(stripslashes($HTML));
177 // Flush the output if only _OB_CACHING is not "on"
178 if (_OB_CACHING != "on") {
184 // Add a fatal error message to the queue array
185 function addFatalMessage ($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 $message = sprintf($message, $extra);
197 // Log fatal messages away
198 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
201 // Getter for total fatal message count
202 function getTotalFatalErrors () {
208 // Do we have at least the first entry?
209 if (!empty($FATAL[0])) {
211 $count = count($FATAL);
218 // Load a template file and return it's content (only it's name; do not use ' or ")
219 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
220 // Add more variables which you want to use in your template files
221 global $DATA, $_CONFIG, $username;
223 // Make all template names lowercase
224 $template = strtolower($template);
226 // Count the template load
227 incrementConfigEntry('num_templates');
229 // Prepare IP number and User Agent
230 $REMOTE_ADDR = GET_REMOTE_ADDR();
231 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
232 $HTTP_USER_AGENT = GET_USER_AGENT();
236 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
238 // @DEPRECATED Try to rewrite the if() condition
239 if ($template == "member_support_form") {
240 // Support request of a member
241 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
242 array($GLOBALS['userid']), __FILE__, __LINE__);
244 // Is content an array?
245 if (is_array($content)) {
247 $content = merge_array($content, SQL_FETCHARRAY($result));
250 $content['gender'] = TRANSLATE_GENDER($content['gender']);
252 // DEPRECATED: Load data in direct variables
253 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
256 $gender = TRANSLATE_GENDER($gender);
257 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
261 SQL_FREERESULT($result);
264 // Generate date/time string
265 $date_time = MAKE_DATETIME(time(), "1");
268 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
271 // Check for admin/guest/member templates
272 if (strpos($template, "admin_") > -1) {
273 // Admin template found
275 } elseif (strpos($template, "guest_") > -1) {
276 // Guest template found
278 } elseif (strpos($template, "member_") > -1) {
279 // Member template found
281 } elseif (strpos($template, "install_") > -1) {
282 // Installation template found
284 } elseif (strpos($template, "ext_") > -1) {
285 // Extension template found
287 } elseif (strpos($template, "la_") > -1) {
288 // "Logical-area" template found
291 // Test for extension
292 $test = substr($template, 0, strpos($template, "_"));
293 if (EXT_IS_ACTIVE($test)) {
294 // Set extra path to extension's name
299 ////////////////////////
300 // Generate file name //
301 ////////////////////////
302 $file = $BASE.$MODE.$template.".tpl";
304 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
305 // Select what depended header/footer template file for admin/guest/member area
306 $file2 = sprintf("%s%s%s_%s.tpl",
310 SQL_ESCAPE($GLOBALS['what'])
314 if (FILE_READABLE($file2)) $file = $file2;
316 // Remove variable from memory
320 // Does the special template exists?
321 if (!FILE_READABLE($file)) {
322 // Reset to default template
323 $file = $BASE.$template.".tpl";
326 // Now does the final template exists?
327 if (FILE_READABLE($file)) {
328 // The local file does exists so we load it. :)
329 $tmpl_file = READ_FILE($file);
331 // Replace ' to our own chars to preventing them being quoted
332 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
334 // Do we have to compile the code?
336 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
338 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
341 // Simply return loaded code
345 // Add surrounding HTML comments to help finding bugs faster
346 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
347 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
348 // Only admins shall see this warning or when installation mode is active
349 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
350 (".basename($file).")<br />
353 <pre>".print_r($content, true)."</pre>
355 <pre>".print_r($DATA, true)."</pre>
359 // Remove content and data
363 // Do we have some content to output or return?
365 // Not empty so let's put it out! ;)
367 // Return the HTML code
373 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
374 // Warning, empty output!
375 return "E:".$template."<br />\n";
379 // Send mail out to an email address
380 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
381 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
383 // Compile subject line (for POINTS constant etc.)
384 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
388 if ((!eregi("@", $TO)) && ($TO > 0)) {
389 // Value detected, is the message extension installed?
390 if (EXT_IS_ACTIVE("msg")) {
391 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
394 // Load email address
395 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
396 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
398 // Does the user exist?
399 if (SQL_NUMROWS($result_email)) {
400 // Load email address
401 list($TO) = SQL_FETCHROW($result_email);
404 $TO = constant('WEBMASTER');
408 SQL_FREERESULT($result_email);
410 } elseif ("$TO" == "0") {
412 $TO = constant('WEBMASTER');
414 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
416 // Check for PHPMailer or debug-mode
417 if (!CHECK_PHPMAILER_USAGE()) {
418 // Not in PHPMailer-Mode
420 // Load email header template
421 $FROM = LOAD_EMAIL_TEMPLATE("header");
424 $FROM .= LOAD_EMAIL_TEMPLATE("header");
426 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
428 // Load email header template
429 $FROM = LOAD_EMAIL_TEMPLATE("header");
432 $FROM .= LOAD_EMAIL_TEMPLATE("header");
437 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
441 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
444 // Fix HTML parameter (default is no!)
445 if (empty($HTML)) $HTML = "N";
446 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
447 // In debug mode we want to display the mail instead of sending it away so we can debug this part
449 ".htmlentities(trim($FROM))."
451 Subject : ".$SUBJECT."
454 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
455 // Send mail as HTML away
456 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
457 } elseif (!empty($TO)) {
459 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
460 } elseif ($HTML == "N") {
462 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
466 // Check if legacy or PHPMailer command
468 function CHECK_PHPMAILER_USAGE() {
469 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
473 * Send out a raw email with PHPMailer class or legacy mail() command
475 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
476 // Shall we use PHPMailer class or legacy mode?
477 if (CHECK_PHPMAILER_USAGE()) {
478 // Use PHPMailer class with SMTP enabled
479 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
480 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
483 $mail = new PHPMailer();
484 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
487 $mail->SMTPAuth = true;
488 $mail->Host = constant('SMTP_HOSTNAME');
490 $mail->Username = constant('SMTP_USER');
491 $mail->Password = constant('SMTP_PASSWORD');
493 $mail->From = constant('WEBMASTER');
497 $mail->FromName = constant('MAIN_TITLE');
498 $mail->Subject = $subject;
499 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
501 $mail->AltBody = "Your mail program required HTML support to read this mail!";
502 $mail->WordWrap = 70;
505 $mail->Body = html_entity_decode($msg);
507 $mail->AddAddress($to, "");
508 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
509 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
510 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
513 // Use legacy mail() command
514 @mail($to, $subject, html_entity_decode($msg), $from);
519 // Generate a password in a specified length or use default password length
520 function GEN_PASS ($LEN = 0) {
521 // Auto-fix invalid length of zero
522 if ($LEN == 0) $LEN = getConfig('pass_len');
524 // Initialize array with all allowed chars
525 $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,-,+,_,/");
527 // Initialize randomizer
528 mt_srand((double) microtime() * 1000000);
530 // Start creating password
532 for ($i = 0; $i < $LEN; $i++) {
533 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
536 // When the size is below 40 we can also add additional security by scrambling it
537 if (strlen($PASS) <= 40) {
538 // Also scramble the password
539 $PASS = scrambleString($PASS);
542 // Return the password
546 function MAKE_DATETIME ($time, $mode="0")
550 return NEVER_HAPPENED;
552 // Filter out numbers
553 $time = bigintval($time);
556 switch (GET_LANGUAGE())
558 case "de": // German date / time format
560 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
561 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
562 case "2": $ret = date("d.m.Y|H:i", $time); break;
563 case "3": $ret = date("d.m.Y", $time); break;
565 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
570 default: // Default is the US date / time format!
572 case "0": $ret = date("r", $time); break;
573 case "1": $ret = date("Y-m-d - g:i A", $time); break;
574 case "2": $ret = date("y-m-d|H:i", $time); break;
575 case "3": $ret = date("y-m-d", $time); break;
577 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
584 // Translates the american decimal dot into a german comma
585 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
588 // Default is 3 you can change this in admin area "Misc -> Misc Options"
589 if (getConfig('max_comma') == null) $_CONFIG['max_comma'] = "3";
591 // Use from config is default
592 $maxComma = getConfig('max_comma');
594 // Use from parameter?
595 if ($max > 0) $maxComma = $max;
598 if (($cut) && ($max == 0)) {
599 // Test for commata if in cut-mode
600 $com = explode(".", $dotted);
601 if (count($com) < 2) {
602 // Don't display commatas even if there are none... ;-)
608 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
611 switch (GET_LANGUAGE()) {
613 $dotted = number_format($dotted, $maxComma, ",", ".");
617 $dotted = number_format($dotted, $maxComma, ".", ",");
621 // Return translated value
626 function DEREFERER ($URL) {
627 // Don't de-refer our own links!
628 if (substr($URL, 0, strlen(URL)) != URL) {
629 // De-refer this link
630 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
638 function TRANSLATE_GENDER ($gender) {
641 case "M": $ret = GENDER_M; break;
642 case "F": $ret = GENDER_F; break;
643 case "C": $ret = GENDER_C; break;
644 default : $ret = $gender; break;
649 function FRAMETESTER($URL) {
650 // Prepare frametester URL
651 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
653 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
655 return $frametesterUrl;
658 function SELECTION_COUNT($array) {
660 if (is_array($array)) {
661 foreach ($array as $key => $sel) {
662 if (!empty($sel)) $ret++;
668 function IMG_CODE ($code, $type, $DATA, $uid) {
669 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
672 function TRANSLATE_STATUS($status) {
676 $ret = ACCOUNT_UNCONFIRMED;
680 $ret = ACCOUNT_CONFIRMED;
684 $ret = ACCOUNT_LOCKED;
689 $ret = ACCOUNT_DELETED;
693 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
694 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
700 function GET_LANGUAGE() {
703 // Set default return value to default language from config
704 $ret = constant('DEFAULT_LANG');
709 // Is the variable set
710 if (!empty($_GET['mx_lang'])) {
711 // Accept only first 2 chars
712 $lang = substr($_GET['mx_lang'], 0, 2);
713 } elseif (isset($cacheArray['language'])) {
715 $ret = $cacheArray['language'];
716 } elseif (!empty($lang)) {
717 // Check if main language file does exist
718 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
719 // Okay found, so let's update cookies
722 } elseif (!isSessionVariableSet('mx_lang')) {
723 // Return stored value from cookie
724 $ret = get_session('mx_lang');
726 // Fixes a warning before the session has the mx_lang constant
727 if (empty($ret)) $ret = constant('DEFAULT_LANG');
731 $cacheArray['language'] = $ret;
737 function SET_LANGUAGE ($lang) {
738 // Accept only first 2 chars!
739 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
742 set_session('mx_lang', $lang);
745 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
746 global $DATA, $REPLACER, $_CONFIG;
748 // Make sure all template names are lowercase!
749 $template = strtolower($template);
751 // Default "nickname" if extension is not installed
754 // Prepare IP number and User Agent
755 $REMOTE_ADDR = GET_REMOTE_ADDR();
756 $HTTP_USER_AGENT = GET_USER_AGENT();
759 $ADMIN = constant('MAIN_TITLE');
761 // Is the admin logged in?
764 $aid = GET_CURRENT_ADMIN_ID();
767 $ADMIN = GET_ADMIN_EMAIL($aid);
770 // Neutral email address is default
771 $email = constant('WEBMASTER');
773 // Expiration in a nice output format
774 if (getConfig('auto_purge') == 0) {
775 // Will never expire!
776 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
778 // Create nice date string
779 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
782 // Is content an array?
783 if (is_array($content)) {
784 // Add expiration to array, $EXPIRATION is now deprecated!
785 $content['expiration'] = $EXPIRATION;
789 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
790 if (($UID > 0) && (is_array($content))) {
791 // If nickname extension is installed, fetch nickname as well
792 if (EXT_IS_ACTIVE("nickname")) {
793 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
795 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
796 array(bigintval($UID)), __FILE__, __LINE__);
798 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
800 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
801 array(bigintval($UID)), __FILE__, __LINE__);
804 // Fetch and merge data
805 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
806 $content = merge_array($content, SQL_FETCHARRAY($result));
807 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
810 SQL_FREERESULT($result);
813 // Translate M to male or F to female if present
814 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
816 // Overwrite email from data if present
817 if (isset($content['email'])) $email = $content['email'];
819 // Store email for some functions in global data array
820 $DATA['email'] = $email;
823 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
825 // Check for admin/guest/member templates
826 if (strpos($template, "admin_") > -1) {
827 // Admin template found
828 $file = $BASE."admin/".$template.".tpl";
829 } elseif (strpos($template, "guest_") > -1) {
830 // Guest template found
831 $file = $BASE."guest/".$template.".tpl";
832 } elseif (strpos($template, "member_") > -1) {
833 // Member template found
834 $file = $BASE."member/".$template.".tpl";
836 // Test for extension
837 $test = substr($template, 0, strpos($template, "_"));
838 if (EXT_IS_ACTIVE($test)) {
839 // Set extra path to extension's name
840 $file = $BASE.$test."/".$template.".tpl";
842 // No special filename
843 $file = $BASE.$template.".tpl";
847 // Does the special template exists?
848 if (!FILE_READABLE($file)) {
849 // Reset to default template
850 $file = $BASE.$template.".tpl";
853 // Now does the final template exists?
855 if (FILE_READABLE($file)) {
856 // The local file does exists so we load it. :)
857 $tmpl_file = READ_FILE($file);
858 $tmpl_file = addslashes($tmpl_file);
861 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
863 } elseif (!empty($template)) {
864 // Template file not found!
865 $newContent = TEMPLATE_404.": ".$template."<br />
867 <pre>".print_r($content, true)."</pre>
869 <pre>".print_r($DATA, true)."</pre>
872 // Debug mode not active? Then remove the HTML tags
873 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
875 // No template name supplied!
876 $newContent = NO_TEMPLATE_SUPPLIED;
879 // Is there some content?
880 if (empty($newContent)) {
882 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
883 // Add last error if the required function exists
884 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
887 // Remove content and data
891 // Return compiled content
892 return COMPILE_CODE($newContent);
895 function MAKE_TIME($H, $M, $S, $stamp) {
896 // Extract day, month and year from given timestamp
897 $DAY = date("d", $stamp);
898 $MONTH = date("m", $stamp);
899 $YEAR = date('Y', $stamp);
901 // Create timestamp for wished time which depends on extracted date
902 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
905 function LOAD_URL($URL, $addUrlData=true) {
906 global $CSS, $footer;
908 // Compile out URI codes
909 $URL = COMPILE_CODE($URL);
911 // Check if http(s):// is there
912 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
913 // Make all URLs full-qualified
920 debug_print_backtrace();
923 $OUTPUT = ob_get_contents();
925 // Clear it only if there is content
926 if (!empty($OUTPUT)) {
930 // Add some data to URL if cookies are not accepted
931 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
933 // Probe for bot from search engine
934 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
935 // Search engine bot detected so let's rewrite many chars for the link
936 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
938 // Output new location link as anchor
939 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
940 } elseif (!headers_sent()) {
941 // Load URL when headers are not sent
944 debug_print_backtrace();
945 die("</pre>URL={$URL}");
947 header ("Location: ".str_replace("&", "&", $URL));
949 // Output error message
950 LOAD_INC("inc/header.php");
951 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
952 LOAD_INC("inc/footer.php");
957 // Wrapper for LOAD_URL but URL comes from a configuration entry
958 function LOAD_CONFIGURED_URL ($configEntry) {
960 $URL = getConfig($configEntry);
965 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
973 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
974 global $SEC_CHARS, $URL_CHARS;
975 // Is the code a string?
976 if (!is_string($code)) {
977 // Silently return it
983 // Select smaller set of chars to replace when we e.g. want to compile URLs
984 if (!$full) $ARRAY = $URL_CHARS;
988 // BEFORE 0.2.1 : Language and data constants
989 // WITH 0.2.1+ : Only language constants
990 $code = str_replace('{--','".', str_replace('--}','."', $code));
992 // BEFORE 0.2.1 : Not used
993 // WITH 0.2.1+ : Data constants
994 $code = str_replace('{!','".', str_replace("!}", '."', $code));
997 // Compile QUOT and other non-HTML codes
998 foreach ($ARRAY['to'] as $k => $to) {
999 // Do the reversed thing as in inc/libs/security_functions.php
1000 $code = str_replace($to, $ARRAY['from'][$k], $code);
1003 // But shall I keep simple quotes for later use?
1004 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1006 // Find $content[bla][blub] entries
1007 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1009 // Are some matches found?
1010 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1011 // Replace all matches
1012 $matchesFound = array();
1013 foreach ($matches[0] as $key => $match) {
1014 // Fuzzy look has failed by default
1015 $fuzzyFound = false;
1017 // Fuzzy look on match if already found
1018 foreach ($matchesFound as $found => $set) {
1020 $test = substr($found, 0, strlen($match));
1022 // Does this entry exist?
1023 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1024 if ($test == $match) {
1026 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1033 if ($fuzzyFound) continue;
1035 // Take all string elements
1036 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1037 // Replace it in the code
1038 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1039 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1040 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1041 $matchesFound[$key."_".$matches[4][$key]] = 1;
1042 $matchesFound[$match] = 1;
1043 } elseif (!isset($matchesFound[$match])) {
1044 // Not yet replaced!
1045 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1046 $code = str_replace($match, "\".".$match.".\"", $code);
1047 $matchesFound[$match] = 1;
1052 // Return compiled code
1056 /************************************************************************
1058 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1059 * $a_sort sortiert: *
1061 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1062 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1063 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1064 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1065 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1067 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1068 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1069 * Sie, dass es doch nicht so schwer ist! :-) *
1071 ************************************************************************/
1072 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1075 while ($primary_key < count($a_sort)) {
1076 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1077 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1080 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1081 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1082 } elseif ($key != $key2) {
1083 // Sort numbers (E.g.: 9 < 10)
1084 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1085 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1089 // We have found two different values, so let's sort whole array
1090 foreach ($dummy as $sort_key => $sort_val) {
1091 $t = $dummy[$sort_key][$key];
1092 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1093 $dummy[$sort_key][$key2] = $t;
1104 // Write back sorted array
1108 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1109 global $MONTH_DESCR;
1112 if ($type == "yn") {
1113 // This is a yes/no selection only!
1114 if ($id > 0) $prefix .= "[".$id."]";
1115 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1117 // Begin with regular selection box here
1118 if (!empty($prefix)) $prefix .= "_";
1120 if ($id > 0) $type2 .= "[".$id."]";
1121 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1126 for ($idx = 1; $idx < 32; $idx++) {
1127 $OUT .= "<option value=\"".$idx."\"";
1128 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1129 $OUT .= ">".$idx."</option>\n";
1133 case "month": // Month
1134 foreach ($MONTH_DESCR as $month => $descr) {
1135 $OUT .= "<option value=\"".$month."\"";
1136 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1137 $OUT .= ">".$descr."</option>\n";
1141 case "year": // Year
1143 $YEAR = date('Y', time());
1145 // Use configured min age or fixed?
1146 if (GET_EXT_VERSION("other") >= "0.2.1") {
1148 $startYear = $YEAR - getConfig('min_age');
1151 $startYear = $YEAR - 16;
1154 // Calculate earliest year (100 years old people can still enter Internet???)
1155 $minYear = $YEAR - 100;
1157 // Check if the default value is larger than minimum and bigger than actual year
1158 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1159 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1160 $OUT .= "<option value=\"".$idx."\"";
1161 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1162 $OUT .= ">".$idx."</option>\n";
1164 } elseif ($DEFAULT == -1) {
1165 // Current year minus 1
1166 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1168 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1171 // Get current year and subtract the configured minimum age
1172 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1173 // Calculate earliest year depending on extension version
1174 if (GET_EXT_VERSION("other") >= "0.2.1") {
1175 // Use configured minimum age
1176 $YEAR = date('Y', time()) - getConfig('min_age');
1178 // Use fixed 16 years age
1179 $YEAR = date('Y', time()) - 16;
1182 // Construct year selection list
1183 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1184 $OUT .= "<option value=\"".$idx."\"";
1185 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1186 $OUT .= ">".$idx."</option>\n";
1193 for ($idx = 0; $idx < 60; $idx+=5) {
1194 if (strlen($idx) == 1) $idx = "0".$idx;
1195 $OUT .= "<option value=\"".$idx."\"";
1196 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1197 $OUT .= ">".$idx."</option>\n";
1202 for ($idx = 0; $idx < 24; $idx++) {
1203 if (strlen($idx) == 1) $idx = "0".$idx;
1204 $OUT .= "<option value=\"".$idx."\"";
1205 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1206 $OUT .= ">".$idx."</option>\n";
1211 $OUT .= "<option value=\"Y\"";
1212 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1213 $OUT .= ">{!YES!}</option>\n<option value=\"N\"";
1214 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1215 $OUT .= ">{!NO!}</option>\n";
1218 $OUT .= " </select>\n";
1222 function TRANSLATE_YESNO($yn)
1226 case "Y": $yn = YES; break;
1227 case "N": $yn = NO; break;
1228 default : $yn = "??? (".$yn.")"; break;
1233 // Deprecated : $length
1236 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1237 // Fix missing _MAX constant
1238 if (!defined('_MAX')) define('_MAX', 15235);
1240 // Build server string
1241 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1244 $keys = SITE_KEY.":".DATE_KEY;
1245 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1246 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1247 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1248 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1250 // Build string from misc data
1251 $data = $code.":".$uid.":".$DATA;
1253 // Add more additional data
1254 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1255 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1256 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1257 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1258 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1260 // Calculate number for generating the code
1261 $a = $code + _ADD - 1;
1263 if (getConfig('master_hash') != null) {
1264 // Generate hash with master salt from modula of number with the prime number and other data
1265 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1267 // Create number from hash
1268 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1270 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1271 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1273 // Create number from hash
1274 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1277 // At least 10 numbers shall be secure enought!
1278 $len = getConfig('code_length');
1279 if ($len == 0) $len = $length;
1280 if ($len == 0) $len = 10;
1282 // Cut off requested counts of number
1283 $return = substr(str_replace('.', "", $rcode), 0, $len);
1285 // Done building code
1288 // Does only allow numbers
1289 function bigintval($num, $castValue = true) {
1290 // Filter all numbers out
1291 $ret = preg_replace("/[^0123456789]/", "", $num);
1294 if ($castValue) $ret = (double)$ret;
1296 // Has the whole value changed?
1297 if ("".$ret."" != "".$num."") {
1300 debug_print_backtrace();
1302 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1308 // Insert the code in $img_code into jpeg or PNG image
1309 function GENERATE_IMAGE($img_code, $header=true) {
1310 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1311 // Stop execution of function here because of over-sized code length
1313 } elseif (!$header) {
1314 // Return in an HTML code code
1315 return "<IMG src=\"{!URL!}/img.php?code=".$img_code."\">\n";
1319 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1320 if (FILE_READABLE($img)) {
1321 // Switch image type
1322 switch (getConfig('img_type'))
1325 // Okay, load image and hide all errors
1326 $image = @imagecreatefromjpeg($img);
1330 // Okay, load image and hide all errors
1331 $image = @imagecreatefrompng($img);
1335 // Exit function here
1339 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1340 $text_color = imagecolorallocate($image, 0, 0, 0);
1342 // Insert code into image
1343 imagestring($image, 5, 14, 2, $img_code, $text_color);
1345 // Return to browser
1346 header ("Content-Type: image/".getConfig('img_type'));
1348 // Output image with matching image factory
1349 switch (getConfig('img_type')) {
1350 case "jpg": imagejpeg($image); break;
1351 case "png": imagepng($image); break;
1354 // Remove image from memory
1355 imagedestroy($image);
1357 // Create selection box or array of splitted timestamp
1358 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1359 // Calculate 2-seconds timestamp
1360 $stamp = round($timestamp);
1361 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1363 // Do we have a leap year?
1365 $TEST = date('Y', time()) / 4;
1366 $M1 = date("m", time());
1367 $M2 = date("m", (time() + $timestamp));
1369 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1370 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1372 // First of all years...
1373 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1374 //* DEBUG: */ print("Y={$Y}<br />\n");
1376 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1377 //* DEBUG: */ print("M={$M}<br />\n");
1379 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1380 //* DEBUG: */ print("W={$W}<br />\n");
1382 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1383 //* DEBUG: */ print("D={$D}<br />\n");
1385 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
1386 //* DEBUG: */ print("h={$h}<br />\n");
1388 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1389 //* DEBUG: */ print("m={$m}<br />\n");
1390 // And at last seconds...
1391 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1392 //* DEBUG: */ print("s={$s}<br />\n");
1394 // Is seconds zero and time is < 60 seconds?
1395 if (($s == 0) && ($timestamp < 60)) {
1397 $s = round($timestamp);
1401 // Now we convert them in seconds...
1403 if ($return_array) {
1404 // Just put all data in an array for later use
1416 $OUT = "<div align=\"".$align."\">\n";
1417 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1420 if (ereg('Y', $display) || (empty($display))) {
1421 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._YEARS."</strong></td>\n";
1424 if (ereg("M", $display) || (empty($display))) {
1425 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MONTHS."</strong></td>\n";
1428 if (ereg("W", $display) || (empty($display))) {
1429 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._WEEKS."</strong></td>\n";
1432 if (ereg("D", $display) || (empty($display))) {
1433 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._DAYS."</strong></td>\n";
1436 if (ereg("h", $display) || (empty($display))) {
1437 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._HOURS."</strong></td>\n";
1440 if (ereg("m", $display) || (empty($display))) {
1441 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MINUTES."</strong></td>\n";
1444 if (ereg("s", $display) || (empty($display))) {
1445 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._SECONDS."</strong></td>\n";
1451 if (ereg('Y', $display) || (empty($display))) {
1452 // Generate year selection
1453 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1454 for ($idx = 0; $idx <= 10; $idx++) {
1455 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1456 if ($idx == $Y) $OUT .= " selected default";
1457 $OUT .= ">".$idx."</option>\n";
1459 $OUT .= " </select></td>\n";
1461 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1464 if (ereg("M", $display) || (empty($display))) {
1465 // Generate month selection
1466 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1467 for ($idx = 0; $idx <= 11; $idx++)
1469 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1470 if ($idx == $M) $OUT .= " selected default";
1471 $OUT .= ">".$idx."</option>\n";
1473 $OUT .= " </select></td>\n";
1475 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1478 if (ereg("W", $display) || (empty($display))) {
1479 // Generate week selection
1480 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1481 for ($idx = 0; $idx <= 4; $idx++) {
1482 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1483 if ($idx == $W) $OUT .= " selected default";
1484 $OUT .= ">".$idx."</option>\n";
1486 $OUT .= " </select></td>\n";
1488 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1491 if (ereg("D", $display) || (empty($display))) {
1492 // Generate day selection
1493 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1494 for ($idx = 0; $idx <= 31; $idx++) {
1495 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1496 if ($idx == $D) $OUT .= " selected default";
1497 $OUT .= ">".$idx."</option>\n";
1499 $OUT .= " </select></td>\n";
1501 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1504 if (ereg("h", $display) || (empty($display))) {
1505 // Generate hour selection
1506 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1507 for ($idx = 0; $idx <= 23; $idx++) {
1508 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1509 if ($idx == $h) $OUT .= " selected default";
1510 $OUT .= ">".$idx."</option>\n";
1512 $OUT .= " </select></td>\n";
1514 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1517 if (ereg("m", $display) || (empty($display))) {
1518 // Generate minute selection
1519 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1520 for ($idx = 0; $idx <= 59; $idx++) {
1521 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1522 if ($idx == $m) $OUT .= " selected default";
1523 $OUT .= ">".$idx."</option>\n";
1525 $OUT .= " </select></td>\n";
1527 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1530 if (ereg("s", $display) || (empty($display))) {
1531 // Generate second selection
1532 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1533 for ($idx = 0; $idx <= 59; $idx++) {
1534 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1535 if ($idx == $s) $OUT .= " selected default";
1536 $OUT .= ">".$idx."</option>\n";
1538 $OUT .= " </select></td>\n";
1540 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1543 $OUT .= "</table>\n";
1545 // Return generated HTML code
1550 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1551 // Initial return value
1554 // Do we have a leap year?
1556 $TEST = date('Y', time()) / 4;
1557 $M1 = date("m", time());
1558 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1559 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1560 // First add years...
1561 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1563 $ret += $POST[$prefix."_mo"] * 2628000;
1565 $ret += $POST[$prefix."_we"] * 604800;
1567 $ret += $POST[$prefix."_da"] * 86400;
1569 $ret += $POST[$prefix."_ho"] * 3600;
1571 $ret += $POST[$prefix."_mi"] * 60;
1572 // And at last seconds...
1573 $ret += $POST[$prefix."_se"];
1574 // Return calculated value
1577 // Sends out mail to all administrators
1578 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1579 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1580 // Trim template name
1581 $template = trim($template);
1583 // Load email template
1584 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1586 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1587 // Older version detected!
1588 return SEND_ADMIN_EMAILS($subj, $msg);
1591 // Check which admin shall receive this mail
1592 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1593 array($template), __FILE__, __LINE__);
1594 if (SQL_NUMROWS($result) == 0) {
1595 // Create new entry (to all admins)
1596 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1597 array($template), __FILE__, __LINE__);
1599 // Load admin IDs...
1601 while (list($aid) = SQL_FETCHROW($result)) {
1606 SQL_FREERESULT($result);
1608 // "implode" IDs and query string
1609 $aid = implode(",", $aids);
1611 // Add line to userlog
1612 USERLOG_ADD_LINE($subj, $msg, $UID);
1614 } elseif ($aid == "0") {
1615 // Select all email adresses
1616 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`", __FILE__, __LINE__);
1618 // If Admin-ID is not "to-all" select
1619 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`", array($aid), __FILE__, __LINE__);
1623 // Load email addresses and send away
1624 while (list($email) = SQL_FETCHROW($result)) {
1625 SEND_EMAIL($email, $subj, $msg);
1629 SQL_FREERESULT($result);
1632 function CREATE_FANCY_TIME ($stamp) {
1633 // Get data array with years/months/weeks/days/...
1634 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1636 foreach($data as $k => $v) {
1638 // Value is greater than 0 "eval" data to return string
1639 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1645 // Do we have something there?
1646 if (strlen($ret) > 0) {
1647 // Remove leading commata and space
1648 $ret = substr($ret, 2);
1651 $ret = "0 "._SECONDS;
1654 // Return fancy time string
1658 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1659 $SEP = ""; $TOP = "";
1662 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1666 for ($page = 1; $page <= $PAGES; $page++) {
1667 // Is the page currently selected or shall we generate a link to it?
1668 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1669 // Is currently selected, so only highlight it
1670 $NAV .= "<strong>-";
1672 // Open anchor tag and add base URL
1673 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1675 // Add userid when we shall show all mails from a single member
1676 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1678 // Close open anchor tag
1682 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1683 // Is currently selected, so only highlight it
1684 $NAV .= "-</strong>";
1690 // Add seperator if we have not yet reached total pages
1691 if ($page < $PAGES) $NAV .= " | ";
1694 // Define constants only once
1695 if (!defined('__NAV_OUTPUT')) {
1696 define('__NAV_OUTPUT' , $NAV);
1697 define('__NAV_COLSPAN', $colspan);
1698 define('__NAV_TOP' , $TOP);
1699 define('__NAV_SEP' , $SEP);
1702 // Load navigation template
1703 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1706 // Return generated HTML-Code
1714 // Extract host from script name
1715 function EXTRACT_HOST (&$script) {
1716 // Use default SERVER_URL by default... ;) So?
1719 // Is this URL valid?
1720 if (substr($script, 0, 7) == "http://") {
1721 // Use the hostname from script URL as new hostname
1722 $url = substr($script, 7);
1723 $extract = explode("/", $url);
1725 // Done extracting the URL :)
1728 // Extract host name
1729 $host = str_replace("http://", "", $url);
1730 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1732 // Generate relative URL
1733 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1734 if (substr(strtolower($script), 0, 7) == "http://") {
1735 // But only if http:// is in front!
1736 $script = substr($script, (strlen($url) + 7));
1737 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1739 $script = substr($script, (strlen($url) + 8));
1742 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1743 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1749 // Send a GET request
1750 function GET_URL ($script) {
1751 // Compile the script name
1752 $script = COMPILE_CODE($script);
1754 // Extract host name from script
1755 $host = EXTRACT_HOST($script);
1757 // Generate GET request header
1758 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1759 $request .= "Host: " . $host . "\r\n";
1760 $request .= "Referer: " . URL . "/admin.php\r\n";
1761 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1762 $request .= "Content-Type: text/plain\r\n";
1763 $request .= "Cache-Control: no-cache\r\n";
1764 $request .= "Connection: Close\r\n\r\n";
1766 // Send the raw request
1767 $response = SEND_RAW_REQUEST($host, $request);
1769 // Return the result to the caller function
1773 // Send a POST request
1774 function POST_URL ($script, $postData) {
1775 // Is postData an array?
1776 if (!is_array($postData)) {
1778 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1779 return array("", "", "");
1782 // Compile the script name
1783 $script = COMPILE_CODE($script);
1785 // Extract host name from script
1786 $host = EXTRACT_HOST($script);
1788 // Construct request
1789 $data = http_build_query($postData, '','&');
1791 // Generate POST request header
1792 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1793 $request .= "Host: " . $host . "\r\n";
1794 $request .= "Referer: " . URL . "/admin.php\r\n";
1795 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1796 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1797 $request .= "Content-length: " . strlen($data) . "\r\n";
1798 $request .= "Cache-Control: no-cache\r\n";
1799 $request .= "Connection: Close\r\n\r\n";
1802 // Send the raw request
1803 $response = SEND_RAW_REQUEST($host, $request);
1805 // Return the result to the caller function
1809 // Sends a raw request to another host
1810 function SEND_RAW_REQUEST ($host, $request) {
1812 $response = array("", "", "");
1814 // Default is not to use proxy
1817 // Are proxy settins set?
1818 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1824 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1826 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1828 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1832 if (!is_resource($fp)) {
1839 // Generate CONNECT request header
1840 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1841 $proxyTunnel .= "Host: ".$host."\r\n";
1843 // Use login data to proxy? (username at least!)
1844 if (getConfig('proxy_username') != "") {
1846 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1847 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1850 // Add last new-line
1851 $proxyTunnel .= "\r\n";
1852 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1855 fputs($fp, $proxyTunnel);
1859 // No response received
1863 // Read the first line
1864 $resp = trim(fgets($fp, 10240));
1865 $respArray = explode(" ", $resp);
1866 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1867 // Invalid response!
1873 fputs($fp, $request);
1877 $response[] = trim(fgets($fp, 1024));
1883 // Skip first empty lines
1885 foreach ($resp as $idx => $line) {
1887 $line = trim($line);
1889 // Is this line empty?
1892 array_shift($response);
1894 // Abort on first non-empty line
1899 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1901 // Proxy agent found?
1902 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1903 // Proxy header detected, so remove two lines
1904 array_shift($response);
1905 array_shift($response);
1908 // Was the request successfull?
1909 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1910 // Not found / access forbidden
1911 $response = array("", "", "");
1917 // Taken from www.php.net eregi() user comments
1918 function VALIDATE_EMAIL($email) {
1920 $email = COMPILE_CODE($email);
1922 // Check first part of email address
1923 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1926 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1929 $regex = "^".$first."@".$domain."$";
1931 // Return check result
1932 return eregi($regex, $email);
1934 // Function taken from user comments on www.php.net / function eregi()
1935 function VALIDATE_URL ($URL, $compile=true) {
1936 // Trim URL a little
1937 $URL = trim(urldecode($URL));
1938 //* DEBUG: */ echo $URL."<br />";
1940 // Compile some chars out...
1941 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1942 //* DEBUG: */ echo $URL."<br />";
1944 // Check for the extension filter
1945 if (EXT_IS_ACTIVE("filter")) {
1946 // Use the extension's filter set
1947 return FILTER_VALIDATE_URL($URL, false);
1950 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1951 // https:// in front of the URLs
1952 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1955 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1956 // Define all main targets
1957 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1959 // Begin of navigation links
1960 $eval = "\$OUT = \"[ ";
1962 foreach ($TARGETS as $tar) {
1963 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"{!ADMIN_LINK_";
1964 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1965 if (($tar == "lock_user") && ($status == "LOCKED")) {
1966 // Locked accounts shall be unlocked
1967 $eval .= "UNLOCK_USER";
1969 // All other status is fine
1970 $eval .= strtoupper($tar);
1972 $eval .= "_TITLE!}\\\">{!ADMIN_";
1973 if (($tar == "lock_user") && ($status == "LOCKED")) {
1974 // Locked accounts shall be unlocked
1975 $eval .= "UNLOCK_USER";
1977 // All other status is fine
1978 $eval .= strtoupper($tar);
1980 $eval .= "!}</a></span> | ";
1983 // Finish navigation link
1984 $eval = substr($eval, 0, -7)."]\";";
1990 // Function for backward-compatiblity
1991 function ADD_CATEGORY_table ($MODE, $return=false) {
1992 // Load it from the register extension
1993 return REGISTER_ADD_CATEGORY_table ($MODE, $return);
1995 // Generate an email link
1996 function CREATE_EMAIL_LINK ($email, $table = "admins") {
1997 // Default email link (INSECURE! Spammer can read this by harvester programs)
1998 $EMAIL = "mailto:".$email;
2000 // Check for several extensions
2001 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2002 // Create email link for contacting admin in guest area
2003 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2004 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2005 // Create email link for contacting a member within admin area (or later in other areas, too?)
2006 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2007 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2008 // Create email link to contact sponsor within admin area (or like the link above?)
2009 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2012 // Shall I close the link when there is no admin?
2013 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2015 // Return email link
2018 // Generate a hash for extra-security for all passwords
2019 function generateHash ($plainText, $salt = "") {
2022 // Is the required extension "sql_patches" there and a salt is not given?
2023 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2024 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2025 return md5($plainText);
2028 // Do we miss an arry element here?
2029 if (getConfig('file_hash') == null) {
2031 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2032 debug_print_backtrace();
2036 // When the salt is empty build a new one, else use the first x configured characters as the salt
2038 // Build server string
2039 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2042 $keys = SITE_KEY.":".DATE_KEY.":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime'))).":".getConfig('master_salt');
2045 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2047 // Calculate number for generating the code
2048 $a = time() + _ADD - 1;
2050 // Generate SHA1 sum from modula of number and the prime number
2051 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2052 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2053 $sha1 = scrambleString($sha1);
2054 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2055 //* DEBUG: */ $sha1b = descrambleString($sha1);
2056 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2058 // Generate the password salt string
2059 $salt = substr($sha1, 0, getConfig('salt_length'));
2060 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2063 $salt = substr($salt, 0, getConfig('salt_length'));
2064 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2068 return $salt.sha1($salt.$plainText);
2071 function scrambleString($str) {
2075 // Final check, in case of failture it will return unscrambled string
2076 if (strlen($str) > 40) {
2077 // The string is to long
2079 } elseif (strlen($str) == 40) {
2081 $scrambleNums = explode(":", getConfig('pass_scramble'));
2083 // Generate new numbers
2084 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2087 // Scramble string here
2088 //* DEBUG: */ echo "***Original=".$str."***<br />";
2089 for ($idx = 0; $idx < strlen($str); $idx++) {
2090 // Get char on scrambled position
2091 $char = substr($str, $scrambleNums[$idx], 1);
2093 // Add it to final output string
2094 $scrambled .= $char;
2097 // Return scrambled string
2098 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2102 function descrambleString($str) {
2103 // Scramble only 40 chars long strings
2104 if (strlen($str) != 40) return $str;
2106 // Load numbers from config
2107 $scrambleNums = explode(":", getConfig('pass_scramble'));
2110 if (count($scrambleNums) != 40) return $str;
2112 // Begin descrambling
2113 $orig = str_repeat(" ", 40);
2114 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2115 for ($idx = 0; $idx < 40; $idx++) {
2116 $char = substr($str, $idx, 1);
2117 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2120 // Return scrambled string
2121 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2125 function genScrambleString($len) {
2126 // Prepare randomizer and array for the numbers
2127 mt_srand((double) microtime() * 1000000);
2128 $scrambleNumbers = array();
2130 // First we need to setup randomized numbers from 0 to 31
2131 for ($idx = 0; $idx < $len; $idx++) {
2133 $rand = mt_rand(0, ($len -1));
2135 // Check for it by creating more numbers
2136 while (array_key_exists($rand, $scrambleNumbers)) {
2137 $rand = mt_rand(0, ($len -1));
2141 $scrambleNumbers[$rand] = $rand;
2144 // So let's create the string for storing it in database
2145 $scrambleString = implode(":", $scrambleNumbers);
2146 return $scrambleString;
2148 // Append data like session ID or referal ID to the given URL which would
2149 // normally be stored in cookies
2150 function ADD_URL_DATA ($URL) {
2154 // Determine URL binder
2156 if (strpos($URL, "?") !== false) $BIND = "&";
2158 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2159 // Cookies are not accepted
2160 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2161 // Cookie found in URL
2162 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2163 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2164 // Not found! So let's set default here
2165 $ADD .= $BIND."refid=".getConfig('def_refid');
2168 // Is there already added data? Then change the binder
2169 if (!empty($ADD)) $BIND = "&";
2172 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2173 // Add session from URL
2174 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2176 // Add current session
2177 $ADD .= $BIND."PHPSESSID=".session_id();
2181 // Add all together and return it
2184 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2185 function generatePassString($passHash) {
2186 // Return vanilla password hash
2189 // Is a secret key and master salt already initialized?
2190 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2191 // Only calculate when the secret key is generated
2192 $newHash = ""; $start = 9;
2193 for ($idx = 0; $idx < 10; $idx++) {
2194 $part1 = hexdec(substr($passHash, $start, 4));
2195 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2196 $mod = dechex($idx);
2197 if ($part1 > $part2) {
2198 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2199 } elseif ($part2 > $part1) {
2200 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2202 $mod = substr(round($mod), 0, 4);
2203 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2204 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2209 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2210 $ret = generateHash($newHash, getConfig('master_salt'));
2211 //* DEBUG: */ print($ret."<br />\n");
2214 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2215 $ret = md5($passHash);
2216 //* DEBUG: */ echo "++".$ret."++<br />\n";
2223 // Fix "deleted" cookies
2224 function FIX_DELETED_COOKIES ($cookies) {
2225 // Is this an array with entries?
2226 if ((is_array($cookies)) && (count($cookies) > 0)) {
2227 // Then check all cookies if they are marked as deleted!
2228 foreach ($cookies as $cookieName) {
2229 // Is the cookie set to "deleted"?
2230 if (get_session($cookieName) == "deleted") {
2231 set_session($cookieName, "");
2237 // Output error messages in a fasioned way and die...
2238 function mxchange_die ($msg) {
2240 LOAD_INC_ONCE("inc/header.php");
2242 // Load the message template
2243 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2246 LOAD_INC("inc/footer.php");
2252 // Display parsing time and number of SQL queries in footer
2253 function DISPLAY_PARSING_TIME_FOOTER() {
2254 // Is the timer started?
2255 if (!isset($GLOBALS['startTime'])) {
2261 $endTime = microtime(true);
2263 // "Explode" both times
2264 $start = explode(" ", $GLOBALS['startTime']);
2265 $end = explode(" ", $endTime);
2266 $runTime = $end[0] - $start[0];
2267 if ($runTime < 0) $runTime = 0;
2268 $runTime = TRANSLATE_COMMA($runTime);
2272 'runtime' => $runTime,
2273 'numSQLs' => (getConfig('sql_count') + 1),
2274 'numTemplates' => (getConfig('num_templates') + 1)
2277 // Load the template
2278 LOAD_TEMPLATE("show_timings", false, $content);
2281 // Unset/set session variables
2282 function set_session ($var, $value) {
2285 // Abort in CSS mode here
2286 if ($CSS == 1) return true;
2288 // Trim value and session variable
2289 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2291 // Is the session variable set?
2292 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2293 // Remove the session
2294 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2295 unset($_SESSION[$var]);
2296 return session_unregister($var);
2297 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2299 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2300 $_SESSION[$var] = $value;
2301 return session_register($var);
2302 } elseif (!empty($value)) {
2304 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2305 $_SESSION[$var] = $value;
2309 // Ignored (but valid)
2310 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2314 // Check wether a boolean constant is set
2315 // Taken from user comments in PHP documentation for function constant()
2316 function isBooleanConstantAndTrue($constName) { // : Boolean
2319 // Failed by default
2323 if (isset($cacheArray['const'][$constName])) {
2325 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2326 $res = $cacheArray['const'][$constName];
2329 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2330 if (defined($constName)) $res = (constant($constName) === true);
2333 $cacheArray['const'][$constName] = $res;
2335 //* DEBUG: */ var_dump($res);
2341 // Check wether a session variable is set
2342 function isSessionVariableSet ($var) {
2343 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2344 return (isset($_SESSION[$var]));
2346 // Returns wether the value of the session variable or NULL if not set
2347 function get_session ($var) {
2350 // Default is not found! ;-)
2353 // Is the variable there or cached values?
2354 if (isset($cacheArray['session'][$var])) {
2355 // Get cached value (skips a lot SQL_ESCAPE() calles!
2356 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2357 $value = $cacheArray['session'][$var];
2358 } elseif (isSessionVariableSet($var)) {
2359 // Then get it secured!
2360 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2361 $value = SQL_ESCAPE($_SESSION[$var]);
2364 $cacheArray['session'][$var] = $value;
2371 // Send notification to admin
2372 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2373 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2375 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2377 // Send outdated way
2378 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2379 SEND_ADMIN_EMAILS($subject, $msg);
2383 // Destroy user session
2384 function destroy_user_session () {
2386 $GLOBALS['userid'] = 0;
2388 // Remove all user data from session
2389 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2392 // Merges an array together but only if both are arrays
2393 function merge_array ($array1, $array2) {
2394 // Are both an array?
2395 if ((is_array($array1)) && (is_array($array2))) {
2396 // Merge all together
2397 return array_merge($array1, $array2);
2398 } elseif (is_array($array1)) {
2399 // Return left array
2403 // Something wired happened here...
2404 print(__FUNCTION__.":<pre>");
2405 debug_print_backtrace();
2409 // Debug message logger
2410 function DEBUG_LOG ($file, $line, $message, $force=true) {
2411 // Is debug mode enabled?
2412 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2413 // Log this message away
2414 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2415 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2420 // Reads a directory with PHP files in and gets only files back
2421 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2425 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2428 while ($baseFile = readdir($dirPointer)) {
2429 // Load file only if extension is active
2431 $file = $baseDir.$baseFile;
2433 // Is this a valid reset file?
2434 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2435 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2436 // Remove both for extension name
2437 $extName = substr($baseFile, strlen($prefix), -4);
2440 $extId = GET_EXT_ID($extName);
2442 // Is the extension valid and active?
2443 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2444 // Then add this file
2446 } elseif ($extId == 0) {
2447 // Add non-extension files as well
2454 closedir($dirPointer);
2459 // Return array with include files
2462 // Load more reset scripts
2463 function RESET_ADD_INCLUDES () {
2464 // Is the reset set or old sql_patches?
2465 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2470 // Get more daily reset scripts
2471 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2474 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2476 // Create current week mark
2477 $currWeek = date("W", time());
2480 if (getConfig('last_week') != $currWeek) {
2481 // Include weekly reset scripts
2482 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2485 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2488 // Create current month mark
2489 $currMonth = date("m", time());
2492 if (getConfig('last_month') != $currMonth) {
2493 // Include monthly reset scripts
2494 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2497 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2503 // Handle extra values
2504 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2505 // Default is the value itself
2508 // Do we have a special filter function?
2509 if (!empty($filterFunction)) {
2510 // Does the filter function exist?
2511 if (function_exists($filterFunction)) {
2512 // Do we have extra parameters here?
2513 if (!empty($extraValue)) {
2514 // Put both parameters in one new array by default
2515 $args = array($value, $extraValue);
2517 // If we have an array simply use it and pre-extend it with our value
2518 if (is_array($extraValue)) {
2519 // Make the new args array
2520 $args = merge_array(array($value), $extraValue);
2523 // Call the multi-parameter call-back
2524 $ret = call_user_func_array($filterFunction, $args);
2526 // One parameter call
2527 $ret = call_user_func($filterFunction, $value);
2535 // Check if given FQFN is a readable file
2536 function FILE_READABLE($fqfn) {
2538 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2540 // Converts timestamp selections into a timestamp
2541 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2542 // Init test variable
2545 // Get last three chars
2546 $test = substr($id, -3);
2548 // Improved way of checking! :-)
2549 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2550 // Found a multi-selection for timings?
2551 $test = substr($id, 0, -3);
2552 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)) {
2553 // Generate timestamp
2554 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2555 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2557 // Remove data from array
2558 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2559 unset($POST[$test."_".$rem]);
2563 unset($id); $skip = true; $test2 = $test;
2566 // Process this entry
2567 $skip = false; $test2 = "";
2570 // Reverts the german decimal comma into Computer decimal dot
2571 function REVERT_COMMA ($str) {
2572 // Default float is not a float... ;-)
2575 // Which language is selected?
2576 switch (GET_LANGUAGE()) {
2577 case "de": // German language
2578 // Remove german thousand dots first
2579 $str = str_replace(".", "", $str);
2581 // Replace german commata with decimal dot and cast it
2582 $float = (float)str_replace(",", ".", $str);
2585 default: // US and so on
2586 // Remove thousand dots first and cast
2587 $float = (float)str_replace(",", "", $str);
2595 // Handle menu-depending failed logins and return the rendered content
2596 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2597 // Default output is empty ;-)
2600 // Is the session data set?
2601 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2602 // Ignore zero values
2603 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
2604 // Non-guest has login failures found, get both data and prepare it for template
2605 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2607 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
2608 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2612 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
2615 // Reset session data
2616 set_session('mxchange_'.$accessLevel.'_failures', "");
2617 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2620 // Return rendered content
2625 function REBUILD_CACHE ($cache, $inc="") {
2626 global $cacheInstance, $CSS;
2628 // Shall I remove the cache file?
2629 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2631 if ($cacheInstance->loadCacheFile($cache)) {
2633 $cacheInstance->destroyCacheFile();
2636 // Include file given?
2639 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
2641 // Is the include there?
2642 if (FILE_READABLE($INC)) {
2643 // And rebuild it from scratch
2644 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2647 // Include not found!
2648 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2654 // Purge admin menu cache
2655 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2656 global $cacheInstance;
2658 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2659 if (!EXT_IS_ACTIVE("cache")) {
2660 // Cache extension not active
2662 } elseif (!is_object($cacheInstance)) {
2663 // No cache instance!
2664 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2666 } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2667 // Caching disabled (currently experiemental!)
2671 // Experiemental feature!
2672 trigger_error("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2675 // Translates the "pool type" into human-readable
2676 function TRANSLATE_POOL_TYPE ($type) {
2677 // Default type is unknown
2678 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2680 // Generate constant
2681 $constName = sprintf("POOL_TYPE_%s", $type);
2684 if (defined($constName)) {
2686 $translated = constant($constName);
2689 // Return "translation"
2693 // "Getter" for remote IP number
2694 function GET_REMOTE_ADDR () {
2695 // Get remote ip from environment
2696 $remoteAddr = getenv('REMOTE_ADDR');
2698 // Is removeip installed?
2699 if (EXT_IS_ACTIVE("removeip")) {
2700 // Then anonymize it
2701 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2707 // "Getter" for remote hostname
2708 function GET_REMOTE_HOST () {
2709 // Get remote ip from environment
2710 $remoteHost = getenv('REMOTE_HOST');
2712 // Is removeip installed?
2713 if (EXT_IS_ACTIVE("removeip")) {
2714 // Then anonymize it
2715 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2721 // "Getter" for user agent
2722 function GET_USER_AGENT () {
2723 // Get remote ip from environment
2724 $userAgent = getenv('HTTP_USER_AGENT');
2726 // Is removeip installed?
2727 if (EXT_IS_ACTIVE("removeip")) {
2728 // Then anonymize it
2729 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2735 // "Getter" for referer
2736 function GET_REFERER () {
2737 // Get remote ip from environment
2738 $referer = getenv('HTTP_REFERER');
2740 // Is removeip installed?
2741 if (EXT_IS_ACTIVE("removeip")) {
2742 // Then anonymize it
2743 $referer = GET_ANONYMOUS_REFERER($referer);
2750 // Adds a bonus mail to the queue
2751 // This is a high-level function!
2752 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2753 // Use mode from data if not set and availble ;-)
2754 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2756 // Generate receiver list
2757 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2760 if (!empty($RECEIVER)) {
2761 // Add bonus mail to queue
2762 ADD_BONUS_MAIL_TO_QUEUE(
2774 // Mail inserted into bonus pool
2775 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
2776 } elseif ($output) {
2777 // More entered than can be reached!
2778 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
2781 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2784 // Determines referal id and sets it
2785 function DETERMINE_REFID () {
2786 global $CLICK, $_SERVER;
2788 // Check if refid is set
2789 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2790 // The variable user comes from the click-counter script click.php and we only accept this here
2791 $GLOBALS['refid'] = bigintval($_GET['user']);
2792 } elseif (!empty($_POST['refid'])) {
2793 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2794 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2795 } elseif (!empty($_GET['refid'])) {
2796 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2797 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2798 } elseif (!empty($_GET['ref'])) {
2799 // Set refid=ref (the referal link uses such variable)
2800 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2801 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2802 // Set session refid als global
2803 $GLOBALS['refid'] = bigintval(get_session('refid'));
2804 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2805 // Set default refid as refid in URL
2806 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2807 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2808 // Select a random user which has confirmed enougth mails
2809 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2811 // No default ID when sql_patches is not installed or none set
2812 $GLOBALS['refid'] = 0;
2815 // Set cookie when default refid > 0
2816 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2818 set_session('refid', $GLOBALS['refid']);
2821 // Return determined refid
2822 return $GLOBALS['refid'];
2825 // Destroys the admin session
2826 function DESTROY_ADMIN_SESSION ($destroy = true) {
2827 // Kill maybe existing session variables including array elements
2828 set_session('admin_login', "");
2829 set_session('admin_md5' , "");
2830 set_session('admin_last' , "");
2831 set_session('admin_to' , "");
2833 // Destroy session and return status
2835 return @session_destroy();
2838 // All fine if we shall not really destroy the session
2842 // Checks if a given apache module is loaded
2843 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2844 // Check it and return result
2845 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2848 // Getter for $_CONFIG entries
2849 function getConfig ($entry) {
2855 // Is the entry there?
2856 if (isset($_CONFIG[$entry])) {
2858 $value = $_CONFIG[$entry];
2865 // @TODO Rewrite all language constants to this function.
2866 // "Getter" for language strings
2867 function getMessage ($messageId) {
2868 // Default is not found!
2869 $return = "!".$messageId."!";
2871 // Is the language string found?
2872 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2873 // Language array element found in small_letters
2874 $return = $GLOBALS['msg'][$messageId];
2875 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2876 // @DEPRECATED Language array element found in BIG_LETTERS
2877 $return = $GLOBALS['msg'][$messageId];
2878 } elseif (defined(strtoupper($messageId))) {
2879 // @DEPRECATED Deprecated constant found
2880 $return = constant($messageId);
2882 // Missing language constant
2883 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2886 // Return the string
2890 // Get current theme name
2891 function GET_CURR_THEME() {
2892 global $INC_POOL, $CSS, $cacheArray;
2894 // The default theme is 'default'... ;-)
2897 // Load default theme if not empty from configuration
2898 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2900 if (!isSessionVariableSet('mxchange_theme')) {
2901 // Set default theme
2902 set_session('mxchange_theme', $ret);
2903 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2904 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2905 // Get theme from cookie
2906 $ret = get_session('mxchange_theme');
2909 if (THEME_GET_ID($ret) == 0) {
2910 // Fix it to default
2913 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2914 // Prepare FQFN for checking
2915 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_GET['theme']));
2917 // Installation mode active
2918 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2919 // Set cookie from URL data
2920 set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
2921 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_POST['theme'])))) {
2922 // Set cookie from posted data
2923 set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
2927 $ret = get_session('mxchange_theme');
2929 // Invalid design, reset cookie
2930 set_session('mxchange_theme', $ret);
2933 // Add (maybe) found theme.php file to inclusion list
2934 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
2936 // Try to load the requested include file
2937 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2939 // Return theme value
2943 // Get id from theme
2944 function THEME_GET_ID ($name) {
2947 // Is the extension "theme" installed?
2948 if (!EXT_IS_ACTIVE("theme")) {
2956 // Is the cache entry there?
2957 if (isset($cacheArray['themes']['id'][$name])) {
2958 // Get the version from cache
2959 $id = $cacheArray['themes']['id'][$name];
2962 incrementConfigEntry('cache_hits');
2963 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2964 // Check if current theme is already imported or not
2965 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2966 array($name), __FILE__, __LINE__);
2969 if (SQL_NUMROWS($result) == 1) {
2971 list($id) = SQL_FETCHROW($result);
2975 SQL_FREERESULT($result);
2982 // Increment or init with given value or 1 as default the given config entry
2983 function incrementConfigEntry ($configEntry, $value=1) {
2986 // Increment it if set or init it with 1
2987 if (getConfig($configEntry) > 0) {
2988 $_CONFIG[$configEntry] += $value;
2990 $_CONFIG[$configEntry] = $value;
2994 // Read a given file
2995 function READ_FILE ($FQFN, $sqlPrepare = false) {
2997 if (function_exists('file_get_contents')) {
2999 $content = file_get_contents($FQFN);
3001 // Fall-back to implode-file chain
3002 $content = implode("", file($FQFN));
3005 // Prepare SQL queries?
3006 if ($sqlPrepare === true) {
3007 // Remove some unwanted chars
3008 $content = str_replace("\r", "", $content);
3009 $content = str_replace("\n\n", "\n", $content);
3012 // Return the content
3016 // Writes content to a file
3017 function WRITE_FILE ($FQFN, $content) {
3018 // Is the function there?
3019 if (function_exists('file_put_contents')) {
3020 // Write it directly
3021 file_put_contents($FQFN, $content);
3023 // Write it with fopen
3024 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
3025 fwrite($fp, $content);
3033 // Generates an error code from given account status
3034 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3035 // Default error code if unknown account status
3036 $ERROR = CODE_UNKNOWN_STATUS;
3038 // Generate constant name
3039 $constantName = sprintf("CODE_ID_%s", $status);
3041 // Is the constant there?
3042 if (defined($constantName)) {
3044 $ERROR = constant($constantName);
3047 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3050 // Return error code
3054 // Clears the output buffer. This function does *NOT* backup sent content.
3055 function clearOutputBuffer () {
3056 // Trigger an error on failure
3057 if (!ob_end_clean()) {
3059 trigger_error(__FUNCTION__.": Failed to clean output buffer.");
3063 // "Getter" for revision/version data
3064 function getActualVersion ($type = 0) {
3065 // By default nothing is new... ;-)
3068 // FQFN of revision file
3069 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
3071 // Check for revision file
3072 if (!FILE_READABLE($FQFN)) {
3073 // Not found, so we need to create it
3076 // Revision file found
3077 $ins_vers = explode("\n", READ_FILE($FQFN));
3079 // Is the content valid?
3080 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
3081 // File needs update!
3084 // Revision-File has valid Data and isn't 'new' so return the Rev-Number
3085 return trim($ins_vers[$type]);
3090 // no Revision-File or has no valid Data so read the Revision from the Server.
3091 $version = GET_URL("check-updates3.php");
3094 $akt_vers[] = trim($version[10]);
3095 $akt_vers[] = trim($version[9]);
3096 $akt_vers[] = trim($version[8]);
3099 WRITE_FILE($FQFN, implode("\n", $akt_vers));
3101 // Return requested content
3102 return trim($akt_vers[$type]);
3106 // Loads an include file and logs any missing files for debug purposes
3107 function LOAD_INC ($INC) {
3108 // Get constant path
3109 $PATH = constant('PATH');
3111 // Use the include file name directly
3112 // @TODO Try to find all locations where an FQFN is given to these two
3113 // @TODO functions and avoid it.
3116 // Check if PATH is in $INC
3117 if (substr($INC, 0, $PATH) != $PATH) {
3118 // Add it. This is why we need a trailing slash in config.php
3119 $FQFN = $PATH . $INC;
3122 // Is the include file there?
3123 if (!FILE_READABLE($FQFN)) {
3124 // Not there so log it
3125 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Include file %s not found.", basename($INC)));
3133 // Loads an include file once
3134 function LOAD_INC_ONCE ($INC) {
3137 // Is it not loaded?
3138 if (!isset($cacheArray['load_once'][$INC])) {
3139 // Then try to load it
3142 // And mark it as loaded
3143 $cacheArray['load_once'][$INC] = true;
3147 //////////////////////////////////////////////////
3148 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3149 //////////////////////////////////////////////////
3151 if (!function_exists('html_entity_decode')) {
3152 // Taken from documentation on www.php.net
3153 function html_entity_decode ($string) {
3154 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3155 $trans_tbl = array_flip($trans_tbl);
3156 return strtr($string, $trans_tbl);