Fixed endless loop, if no sql_patches is installed and modules.php?module=index was...
[mailer.git] / inc / functions.php
index 992c4a7373af6cc475fd21b82865921d640073eb..e255045bb0f459f463401a1a8cc05877383636b2 100644 (file)
@@ -233,11 +233,12 @@ function LOAD_TEMPLATE($template, $return=false, $content=array()) {
        $template = strtolower($template);
 
        // Count the template load
-       if (getConfig('num_templates') == null) {
-               $_CONFIG['num_templates'] = 1;
-       } else {
-               $_CONFIG['num_templates']++;
-       }
+       incrementConfigEntry('num_templates');
+
+       // Prepare IP number and User Agent
+       $REMOTE_ADDR     = GET_REMOTE_ADDR();
+       if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
+       $HTTP_USER_AGENT = GET_USER_AGENT();
 
        // Init some data
        $ret = "";
@@ -337,7 +338,7 @@ function LOAD_TEMPLATE($template, $return=false, $content=array()) {
                $tmpl_file = implode("", file($file));
 
                // Replace ' to our own chars to preventing them being quoted
-               while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
+               while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
 
                // Do we have to compile the code?
                $ret = "";
@@ -453,15 +454,12 @@ function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
        if (empty($HTML)) $HTML = "N";
        if (isBooleanConstantAndTrue('DEBUG_MODE')) {
                // In debug mode we want to display the mail instead of sending it away so we can debug this part
-               echo "<pre>
+               print("<pre>
 ".htmlentities(trim($FROM))."
 To      : ".$TO."
 Subject : ".$SUBJECT."
 Message : ".$MSG."
-</pre>\n";
-
-               // Log the mail away
-               if (defined('DEBUG_MAIL')) DEBUG_LOG(__FUNCTION__, __LINE__, "to={$TO},subject={$SUBJECT},msg={$MSG}");
+</pre>\n");
        } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
                // Send mail as HTML away
                SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
@@ -528,8 +526,8 @@ function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
 //
 
 // Generate a password in a specified length or use default password length
-function GEN_PASS($LEN = 0) {
-       global $_CONFIG;
+function GEN_PASS ($LEN = 0) {
+       // Auto-fix invalid length of zero
        if ($LEN == 0) $LEN = getConfig('pass_len');
 
        // Initialize array with all allowed chars
@@ -746,8 +744,6 @@ function GET_LANGUAGE() {
 }
 //
 function SET_LANGUAGE($lang) {
-       global $_CONFIG;
-
        // Accept only first 2 chars!
        $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
 
@@ -756,7 +752,7 @@ function SET_LANGUAGE($lang) {
 }
 //
 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
-       global $DATA, $_CONFIG, $REPLACER;
+       global $DATA, $REPLACER;
 
        // Make sure all template names are lowercase!
        $template = strtolower($template);
@@ -921,7 +917,7 @@ function MAKE_TIME($H, $M, $S, $stamp) {
 }
 //
 function LOAD_URL($URL, $addUrlData=true) {
-       global $CSS, $_CONFIG, $footer;
+       global $CSS, $footer;
 
        // Compile out URI codes
        $URL = COMPILE_CODE($URL);
@@ -944,7 +940,7 @@ function LOAD_URL($URL, $addUrlData=true) {
        if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
 
        // Probe for bot from search engine
-       if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
+       if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
                // Search engine bot detected so let's rewrite many chars for the link
                $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
 
@@ -998,7 +994,7 @@ function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
        } // END - foreach
 
        // But shall I keep simple quotes for later use?
-       if ($simple) $code = str_replace("\'", '{QUOT}', $code);
+       if ($simple) $code = str_replace("'", '{QUOT}', $code);
 
        // Find $content[bla][blub] entries
        @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
@@ -1103,7 +1099,7 @@ function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums =
 }
 //
 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
-       global $MONTH_DESCR, $_CONFIG;
+       global $MONTH_DESCR;
        $OUT = "";
 
        if ($type == "yn") {
@@ -1231,8 +1227,6 @@ function TRANSLATE_YESNO($yn)
 // Optional   : $DATA
 //
 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
-       global $_CONFIG;
-
        // Fix missing _MAX constant
        if (!defined('_MAX')) define('_MAX', 15235);
 
@@ -1307,8 +1301,6 @@ function bigintval($num, $castValue = true) {
 }
 // Insert the code in $img_code into jpeg or PNG image
 function GENERATE_IMAGE($img_code, $header=true) {
-       global $_CONFIG;
-
        if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
                // Stop execution of function here because of over-sized code length
                return;
@@ -1358,8 +1350,6 @@ function GENERATE_IMAGE($img_code, $header=true) {
 }
 // Create selection box or array of splitted timestamp
 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
-       global $_CONFIG;
-
        // Calculate 2-seconds timestamp
        $stamp = round($timestamp);
        //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
@@ -1551,8 +1541,8 @@ function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="ce
        return $OUT;
 }
 //
-function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
-       global $_CONFIG;
+function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
+       // Initial return value
        $ret = 0;
 
        // Do we have a leap year?
@@ -1594,11 +1584,11 @@ function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
 
        // Check which admin shall receive this mail
        $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
-        array($template), __FILE__, __LINE__);
+               array($template), __FILE__, __LINE__);
        if (SQL_NUMROWS($result) == 0) {
                // Create new entry (to all admins)
-               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
-                array($template), __FILE__, __LINE__);
+               SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
+                       array($template), __FILE__, __LINE__);
        } else {
                // Load admin IDs...
                $aids = array();
@@ -1812,8 +1802,6 @@ function POST_URL ($script, $postData) {
 
 // Sends a raw request to another host
 function SEND_RAW_REQUEST ($host, $request) {
-       global $_CONFIG;
-
        // Initialize array
        $response = array("", "", "");
 
@@ -1999,7 +1987,7 @@ function ADD_CATEGORY_TABLE ($MODE, $return=false) {
        return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
 }
 // Generate an email link
-function CREATE_EMAIL_LINK($email, $table="admins") {
+function CREATE_EMAIL_LINK ($email, $table = "admins") {
        // Default email link (INSECURE! Spammer can read this by harvester programs)
        $EMAIL = "mailto:".$email;
 
@@ -2023,7 +2011,7 @@ function CREATE_EMAIL_LINK($email, $table="admins") {
 }
 // Generate a hash for extra-security for all passwords
 function generateHash ($plainText, $salt = "") {
-       global $_CONFIG, $_SERVER;
+       global $_SERVER;
 
        // Is the required extension "sql_patches" there and a salt is not given?
        if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
@@ -2075,8 +2063,6 @@ function generateHash ($plainText, $salt = "") {
 }
 //
 function scrambleString($str) {
-       global $_CONFIG;
-
        // Init
        $scrambled = "";
 
@@ -2108,7 +2094,6 @@ function scrambleString($str) {
 }
 //
 function descrambleString($str) {
-       global $_CONFIG;
        // Scramble only 40 chars long strings
        if (strlen($str) != 40) return $str;
 
@@ -2156,8 +2141,8 @@ function genScrambleString($len) {
 }
 // Append data like session ID or referal ID to the given URL which would
 // normally be stored in cookies
-function ADD_URL_DATA($URL) {
-       global $_CONFIG;
+function ADD_URL_DATA ($URL) {
+       // Init add
        $ADD = "";
 
        // Determine URL binder
@@ -2192,8 +2177,6 @@ function ADD_URL_DATA($URL) {
 }
 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
 function generatePassString($passHash) {
-       global $_CONFIG;
-
        // Return vanilla password hash
        $ret = $passHash;
 
@@ -2261,8 +2244,6 @@ function mxchange_die ($msg) {
 
 // Display parsing time and number of SQL queries in footer
 function DISPLAY_PARSING_TIME_FOOTER() {
-       global $_CONFIG;
-
        // Is the timer started?
        if (!isset($GLOBALS['startTime'])) {
                // Abort here
@@ -2465,8 +2446,6 @@ function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
 }
 // Load more reset scripts
 function RESET_ADD_INCLUDES () {
-       global $_CONFIG;
-
        // Is the reset set or old sql_patches?
        if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
                // Then abort here
@@ -2627,7 +2606,7 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
 }
 // Rebuild cache
 function REBUILD_CACHE ($cache, $inc="") {
-       global $cacheInstance, $_CONFIG, $CSS;
+       global $cacheInstance, $CSS;
 
        // Shall I remove the cache file?
        if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
@@ -2784,7 +2763,7 @@ function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
 }
 // Determines referal id and sets it
 function DETERMINE_REFID () {
-       global $_CONFIG, $CLICK, $_SERVER;
+       global $CLICK, $_SERVER;
 
        // Check if refid is set
        if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
@@ -2824,7 +2803,7 @@ function DETERMINE_REFID () {
 }
 
 // Destroys the admin session
-function DESTROY_ADMIN_SESSION () {
+function DESTROY_ADMIN_SESSION ($destroy = true) {
        // Kill maybe existing session variables including array elements
        set_session('admin_login', "");
        set_session('admin_md5'  , "");
@@ -2832,7 +2811,12 @@ function DESTROY_ADMIN_SESSION () {
        set_session('admin_to'   , "");
 
        // Destroy session and return status
-       return @session_destroy();
+       if ($destroy) {
+               return @session_destroy();
+       } // END - if
+
+       // All fine if we shall not really destroy the session
+       return true;
 }
 
 // Checks if a given apache module is loaded
@@ -2858,6 +2842,128 @@ function getConfig ($entry) {
        return $value;
 }
 
+// @TODO Rewrite all language constants to the function getLanguage().
+// "Getter" for language strings
+function getMessage ($messageId) {
+       // Default is not found!
+       $return = "!".$messageId."!";
+
+       // Is the language string found?
+       if (isset($GLOBALS['msg'][$messageId])) {
+               // Language array element found
+               $return = $GLOBALS['msg'][$messageId];
+       } elseif (defined($messageId)) {
+               // @DEPRECATED Deprecated constant found
+               $return = constant($messageId);
+       } else {
+               // Missing language constant
+               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
+       }
+
+       // Return the string
+       return $return;
+}
+
+// Get current theme name
+function GET_CURR_THEME() {
+       global $INC_POOL, $CSS, $cacheArray;
+
+       // The default theme is 'default'... ;-)
+       $ret = "default";
+
+       // Load default theme if not empty from configuration
+       if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
+
+       if (!isSessionVariableSet('mxchange_theme')) {
+               // Set default theme
+               set_session("mxchange_theme", $ret);
+       } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
+               //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
+               // Get theme from cookie
+               $ret = get_session('mxchange_theme');
+
+               // Is it valid?
+               if (THEME_GET_ID($ret) == 0) {
+                       // Fix it to default
+                       $ret = "default";
+               } // END - if
+       } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
+               // Prepare FQFN for checking
+               $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_GET['theme']));
+
+               // Installation mode active
+               if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
+                       // Set cookie from URL data
+                       set_session("mxchange_theme", SQL_ESCAPE($_GET['theme']));
+               } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_POST['theme'])))) {
+                       // Set cookie from posted data
+                       set_session("mxchange_theme", SQL_ESCAPE($_POST['theme']));
+               }
+
+               // Set return value
+               $ret = get_session('mxchange_theme');
+       } else {
+               // Invalid design, reset cookie
+               set_session("mxchange_theme", $ret);
+       }
+
+       // Add (maybe) found theme.php file to inclusion list
+       $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($ret));
+
+       // Try to load the requested include file
+       if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
+
+       // Return theme value
+       return $ret;
+}
+
+// Get id from theme
+function THEME_GET_ID ($name) {
+       global $cacheArray;
+
+       // Is the extension "theme" installed?
+       if (!EXT_IS_ACTIVE("theme")) {
+               // Then abort here
+               return 0;
+       } // END - if
+
+       // Default id
+       $id = 0;
+
+       // Is the cache entry there?
+       if (isset($cacheArray['themes']['id'][$name])) {
+               // Get the version from cache
+               $id = $cacheArray['themes']['id'][$name];
+
+               // Count up
+               incrementConfigEntry('cache_hits');
+       } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
+               // Check if current theme is already imported or not
+               $result = SQL_QUERY_ESC("SELECT id FROM `"._MYSQL_PREFIX."_themes` WHERE theme_path='%s' LIMIT 1",
+                       array($name), __FILE__, __LINE__);
+
+               // Entry found?
+               if (SQL_NUMROWS($result) == 1) {
+                       // Fetch data
+                       list($id) = SQL_FETCHROW($result);
+               } // END - if
+
+               // Free result
+               SQL_FREERESULT($result);
+       }
+
+       // Return id
+       return $id;
+}
+
+// Increment or init with 1 the given config entry
+function incrementConfigEntry ($configEntry) {
+       global $_CONFIG;
+
+       // Increment it if set or init it with 1
+       if (getConfig($configEntry) > 0) { $_CONFIG[$configEntry]++; } else { $_CONFIG[$configEntry] = 1; }
+}
+
 //////////////////////////////////////////////////
 //                                              //
 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //