needs to be global :(
[mailer.git] / inc / extensions.php
index fa5e463b8f089aef5cefb1bc9beb4074473875bb..ab142b07cd88253789c76f107bb19c3726291c23 100644 (file)
  ************************************************************************/
 
 // Some security stuff...
-if (ereg(basename(__FILE__), $_SERVER['PHP_SELF']))
-{
+if (!defined('__SECURITY')) {
        $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
        require($INC);
 }
-//
-function EXTENSION_REGISTER ($ext_name, $id, $dry_run=false)
-{
-       global $NOTES, $_CONFIG, $INC_POOL, $cacheInstance;
-       // We want to register an extension and registration status is by default "failed" (= false)
-       $EXT_LOAD_MODE = "register"; $ret = false; $SQLs = array();
+
+// Load the extension and maybe found language and function files.
+function LOAD_EXTENSION ($ext_name, $EXT_LOAD_MODE = "", $EXT_VER = "", $dry_run = false) {
+       global $EXT_LOADED, $_CONFIG, $CSS, $cacheMode, $SQLs, $EXT_VER_HISTORY;
+       global $INC_POOL, $EXT_UPDATE_DEPENDS, $EXT_DEPRECATED, $UPDATE_NOTES;
+       global $EXT_VERSION, $EXT_ALWAYS_ACTIVE;
+
+       // Init array
        $INC_POOL = array();
 
+       // Is the extension already loaded?
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Loading extension {$ext_name}, mode={$EXT_LOAD_MODE}, ver={$EXT_VER}.");
+       if ((isset($EXT_LOADED['ext'][$ext_name])) && (empty($EXT_LOAD_MODE))) {
+               // Debug message
+               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s already loaded.", $ext_name));
+               return false;
+       } // END - if
+
+       // Construct FQFN for extension file
+       $extInclude = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
+
+       // Is the extension file NOT there?
+       if (!FILE_READABLE($extInclude)) {
+               // Debug message
+               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s not found.", $ext_name));
+
+               // Abort here
+               return false;
+       } // END - if
+
+       // Construct FQFN for language file
+       $langInclude = sprintf("%sinc/language/%s_%s.php", PATH, $ext_name, GET_LANGUAGE());
+
+       // Is this include there?
+       if ((FILE_READABLE($langInclude)) && (!isset($EXT_LOADED['lang'][$ext_name]))) {
+               // Then load it
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "--- Language loaded.");
+               $EXT_LOADED['lang'][$ext_name] = true;
+               require($langInclude);
+       } // END - if
+
+       // Construct FQFN for functions file
+       $funcsInclude = sprintf("%sinc/libs/%s_functions.php", PATH, $ext_name);
+
+       // Is this include there?
+       if ((FILE_READABLE($funcsInclude)) && (!isset($EXT_LOADED['funcs'][$ext_name]))) {
+               // Then load it
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "--- Functions loaded.");
+               $EXT_LOADED['funcs'][$ext_name] = true;
+               require($funcsInclude);
+       } // END - if
+
+       // Extensions are not deprecated by default
+       $EXT_DEPRECATED = "N";
+
+       // Extensions are not always active by default
+       $EXT_ALWAYS_ACTIVE = "N";
+
+       // By default an extension update does not depend on other extensions
+       $EXT_UPDATE_DEPENDS = "";
+
+       // Extension update notes
+       $UPDATE_NOTES = "";
+
+       // Include the extension file
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Extension loaded.");
+       require($extInclude);
+
+       // Is this extension deprecated?
+       if ($EXT_DEPRECATED == "Y") {
+               // Deactivate the extension
+               DEACTIVATE_EXTENSION($ext_name);
+
+               // Abort here
+               return false;
+       } // END - if
+
+       // Mark it as loaded in normal mode
+       if (empty($EXT_LOAD_MODE)) {
+               // Mark it now...
+               $EXT_LOADED['ext'][$ext_name] = true;
+       } // END - if
+
+       // All fine!
+       return true;
+}
+
+//
+function EXTENSION_REGISTER ($ext_name, $task_id, $dry_run=false) {
+       global $UPDATE_NOTES, $_CONFIG, $INC_POOL, $cacheInstance;
+       global $EXT_VER_HISTORY, $SQLs, $NOTES, $EXT_ALWAYS_ACTIVE, $EXT_VERSION;
+
        // This shall never do a non-admin user!
        if (!IS_ADMIN()) return false;
 
        // Is this extension already installed?
        if (EXT_IS_ACTIVE($ext_name)) return false;
 
-       // Generate file name
-       $file = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
+       // Init variables
+       $ret = false; $SQLs = array();
+       $NOTES = "";
+       $INC_POOL = array();
 
-       // Does this extension exists?
-       if (file_exists($file) && is_readable($file))
-       {
-               // Extension was found so we can load it in registration mode
-               require($file);
+       // By default the language prefix is the extension's name
+       // @TODO: Do we really need this one anymore? Can't we just take $ext_name and done?
+       // By default we have no failtures
+       $EXT_REPORTS_FAILURE = false;
 
+       // Does this extension exists?
+       if (LOAD_EXTENSION($ext_name, "register", "", $dry_run)) {
                // And run possible updates
-               $EXT_LOAD_MODE = "update"; $EXT_UPDATE_DEPENDS = "";
-               foreach ($EXT_VER_HISTORY as $EXT_VER)
-               {
-                       require($file);
-                       if (((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['verbose_sql'] == "Y")) || (!EXT_IS_ACTIVE("sql_patches")))
-                       {
-                               if (!empty($UPDATE_NOTES))
-                               {
+               $history = $EXT_VER_HISTORY;
+               foreach ($history as $ver) {
+                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ext_name={$ext_name}, ext_ver={$ver}");
+                       // Load extension in update mode
+                       LOAD_EXTENSION($ext_name, "update", $ver, $dry_run);
+
+                       // Do we have an update?
+                       if (((GET_EXT_VERSION("sql_patches") != "") && (getConfig('verbose_sql') == "Y")) || (!EXT_IS_ACTIVE("sql_patches"))) {
+                               if (!empty($UPDATE_NOTES)) {
                                        // Update notes found
-                                       $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".$UPDATE_NOTES."<br /><br />\n";
+                                       $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".$UPDATE_NOTES."</div>");
                                        $UPDATE_NOTES = "";
-                               }
-                                elseif (($EXT_VER == "0.0") || ($EXT_VER == "0.0.0"))
-                               {
+                               } elseif (($ver == "0.0") || ($ver == "0.0.0")) {
                                        // Initial release
-                                       $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".INITIAL_RELEASE."<br /><br />\n";
-                               }
-                                else
-                               {
-                                       $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br /><I>".NO_UPDATE_NOTES."</I><br /><br />\n";
+                                       $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".INITIAL_RELEASE."</div>");
+                               } else {
+                                       // No update notes found!
+                                       $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br /><I>".NO_UPDATE_NOTES."</I></div>");
                                }
-                       }
-               }
+                       } // END - if
+               } // END - foreach
 
                // Does this extension depends on an outstanding update of another update?
-               if (!empty($EXT_UPDATE_DEPENDS))
-               {
+               if (!empty($EXT_UPDATE_DEPENDS)) {
                        // Backup SQL commands and clear current
-                       $SQLs2 = $SQLs;  $SQLs = array(); $test = false;
-
-                       // Backup language as well
-                       $LANG_BCK = $EXT_LANG_PREFIX; $EXT_ALWAYS_ACTIVE = "N";
-
-                       // Load required extension also in update mode
-                       $file = sprintf("%sinc/extensions/ext-%s.php", PATH, $EXT_UPDATE_DEPENDS);
+                       $SQLs2 = $SQLs;
+                       $SQLs  = array();
+                       $test  = false;
 
                        // Check for required file
-                       if (file_exists($file) && is_readable($file))
-                       {
-                               // File exists so let's load it
-                               $VER_BACKUP = $EXT_VERSION;
-                               require($file);
-                               $EXT_VERSION = $VER_BACKUP;
-
+                       if (LOAD_EXTENSION($EXT_UPDATE_DEPENDS, "register", "", $dry_run)) {
                                // If versions mismatch update extension first
                                $ext_ver = GET_EXT_VERSION($EXT_UPDATE_DEPENDS);
-                               if (empty($ext_ver))
-                               {
+
+                               // Extension version set? If empty the extension is not registered
+                               if (empty($ext_ver)) {
                                        // Extension not registered so far so first load task's ID...
                                        $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE task_type='EXTENSION' AND subject LIKE '[%s:]%%' LIMIT 1",
-                                        array($EXT_UPDATE_DEPENDS), __FILE__, __LINE__);
-                                       if (SQL_NUMROWS($result) == 1)
-                                       {
+                                               array($EXT_UPDATE_DEPENDS), __FILE__, __LINE__);
+
+                                       // Entry found?
+                                       if (SQL_NUMROWS($result) == 1) {
                                                // Task found so load task's ID and register extension...
                                                list($task) = SQL_FETCHROW($result);
-                                               SQL_FREERESULT($result);
+
+                                               // Try to register the extension
                                                $test = EXTENSION_REGISTER($EXT_UPDATE_DEPENDS, $task, $dry_run);
-                                       }
-                               }
-                                elseif ($ext_ver != $EXT_VERSION)
-                               {
+                                       } // END - if
+
+                                       // Free result
+                                       SQL_FREERESULT($result);
+                               } elseif ($ext_ver != $EXT_VERSION) {
                                        // Ok, update this extension now
                                        EXTENSION_UPDATE(basename($file), $EXT_UPDATE_DEPENDS, $ext_ver, $dry_run);
 
                                        // All okay!
                                        $test = true;
-                               }
-                                else
-                               {
+                               } else {
                                        // Nothing to register / update before...
                                        $test = true;
                                }
-                       }
-                        else
-                       {
+                       } else {
                                // Required file for update does not exists!
                                $test = true;
                                // But this is fine for the first time...
@@ -143,10 +216,7 @@ function EXTENSION_REGISTER ($ext_name, $id, $dry_run=false)
 
                        // Finally restore previous SQLs
                        $SQLs = $SQLs2; unset($SQLs2);
-                       $EXT_LANG_PREFIX = $LANG_BCK;
-               }
-                else
-               {
+               } else {
                        // Does not depend on an other extension
                        $test = true;
                }
@@ -154,6 +224,9 @@ function EXTENSION_REGISTER ($ext_name, $id, $dry_run=false)
                // Switch back to register mode
                $EXT_LOAD_MODE = "register";
 
+               // Remains true if extension registration reports no failtures
+               $test = ($test && !$EXT_REPORTS_FAILURE);
+
                // Does everthing before wents ok?
                if ($test) {
                        // "Dry-run-mode" activated?
@@ -177,13 +250,7 @@ function EXTENSION_REGISTER ($ext_name, $id, $dry_run=false)
                                } // END - foreach
 
                                // Remove cache file(s) if extension is active
-                               if ((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) {
-                                       //* DEBUG: */ echo __LINE__.": DESTROY!<br />\n";
-                                       // Remove cache files
-                                       if ($cacheInstance->cache_file("extensions", true)) $cacheInstance->cache_destroy();
-                                       if ($cacheInstance->cache_file("mod_reg", true))    $cacheInstance->cache_destroy();
-                                       if ($cacheInstance->cache_file("config", true))     $cacheInstance->cache_destroy();
-                               } // END - if
+                               RUN_FILTER('post_extension_installed', $ext_name);
 
                                // Check for added include files
                                if (count($INC_POOL > 0)) {
@@ -191,18 +258,26 @@ function EXTENSION_REGISTER ($ext_name, $id, $dry_run=false)
                                        foreach ($INC_POOL as $inc) {
                                                require_once($inc);
                                        } // END - foreach
-                               }
+
+                                       // Remove array
+                                       unset($INC_POOL);
+                               } // END - if
 
                                // Register extension
-                               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_extensions (ext_name, ext_lang_file, ext_active, ext_version) VALUES ('%s', '%s', '%s', '%s')",
-                                array($ext_name, $EXT_LANG_PREFIX, $EXT_ALWAYS_ACTIVE, $EXT_VERSION), __FILE__, __LINE__);
+                               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_extensions (ext_name, ext_active, ext_version) VALUES ('%s','%s','%s')",
+                                       array($ext_name, $EXT_ALWAYS_ACTIVE, $EXT_VERSION), __FILE__, __LINE__);
 
                                // Update task management
-                               $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_task_system SET status='SOLVED' WHERE id=%s LIMIT 1",
-                                array(bigintval($id)), __FILE__, __LINE__);
+                               ADMIN_SOLVE_TASK($task_id);
+
+                               // @TODO This causes the whole (!) menu cache being purged
+                               CACHE_PURGE_ADMIN_MENU();
 
                                // In normal mode return a true on success
-                               $ret = true; unset($SQLs);
+                               $ret = true;
+
+                               // Remove SQLs
+                               unset($SQLs);
                        } else {
                                // Rewrite SQL command to keep { and } inside
                                foreach ($SQLs as $key => $sql) {
@@ -220,39 +295,47 @@ function EXTENSION_REGISTER ($ext_name, $id, $dry_run=false)
                        // No, an error occurs while registering extension :-(
                        $ret = false;
                }
-       } elseif (($id > 0) && (!empty($ext_name))) {
+       } elseif (($task_id > 0) && (!empty($ext_name))) {
                // Remove task from system when id and extension's name is valid
                $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_task_system WHERE id=%s AND status='NEW' LIMIT 1",
-                array(bigintval($id)), __FILE__, __LINE__);
+                array(bigintval($task_id)), __FILE__, __LINE__);
        }
 
        // Is this the sql_patches?
-       //* DEBUG: */ echo __LINE__.":{$ext_name}/{$EXT_LOAD_MODE}<br />\n";
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":{$ext_name}/{$EXT_LOAD_MODE}");
        if (($ext_name == "sql_patches") && (($EXT_LOAD_MODE == "register") || ($EXT_LOAD_MODE == "remove")) && (!$dry_run) && ($test)) {
                // Then redirect to logout
-               //* DEBUG: */ echo __LINE__.": LOAD!<br />\n";
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": LOAD!");
                LOAD_URL("modules.php?module=admin&logout=1&".$EXT_LOAD_MODE."=sql_patches");
        } // END - if
 
        // Return status code
        return $ret;
 }
-//
-function EXTENSION_RUN_SQLS($id, $EXT_LOAD_MODE) {
-       global $cacheInstance;
-       $SQLs = array();
+
+// Run SQL queries for given extension id
+// @TODO Change from ext_id to ext_name (not just even the variable! ;-) )
+function EXTENSION_RUN_SQLS ($ext_id, $load_mode) {
+       global $cacheInstance, $_CONFIG, $SQLs;
+
+       // Extensions are never active by default
+       $EXT_ALWAYS_ACTIVE = "N";
+
+       // By default no SQL has been executed
+       $sqlRan = false;
 
        // This shall never do a non-admin user!
        if (!IS_ADMIN()) return false;
 
        // Get extension's name
-       $ext_name = GET_EXT_NAME($id);
+       $ext_name = GET_EXT_NAME($ext_id);
        if (empty($ext_name)) return false;
 
        // Load extension in detected mode
-       $file = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
-       if (file_exists($file) && is_readable($file)) require($file);
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":ext_name[{$ext_id}]={$ext_name}");
+       LOAD_EXTENSION($ext_name, $load_mode);
 
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":SQLs::count=".count($SQLs)."");
        if ((is_array($SQLs) && (sizeof($SQLs) > 0))) {
                // Run SQL commands...
                foreach ($SQLs as $sql) {
@@ -262,6 +345,7 @@ function EXTENSION_RUN_SQLS($id, $EXT_LOAD_MODE) {
                        // Is there still an SQL query?
                        if (!empty($sql)) {
                                // Do we have an "ALTER TABLE" command?
+                               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":SQL={$SQL}");
                                if (substr(strtolower($sql), 0, 11) == "alter table") {
                                        // Analyse the alteration command
                                        SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
@@ -269,87 +353,88 @@ function EXTENSION_RUN_SQLS($id, $EXT_LOAD_MODE) {
                                        // Run regular SQL command
                                        $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
                                }
+
+                               // An SQL has been executed
+                               $sqlRan = true;
                        } // END - if
                } // END - foreach
 
                // Removal mode?
-               if ($EXT_LOAD_MODE == "remove") {
+               if ($load_mode == "remove") {
                        // Delete this extension (remember to remove it from your server *before* you click on welcome!
-                       $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_extensions WHERE id=%s LIMIT 1",
-                        array($id), __FILE__, __LINE__);
+                       $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
+                               array($ext_name), __FILE__, __LINE__);
                } // END - if
+       } // END - if
 
-               // Remove cache file(s) if extension is active
-               if ((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) {
-                       //* DEBUG: */ echo __LINE__.": DESTROY!<br />\n";
-                       // Remove cache files
-                       if ($cacheInstance->cache_file("extensions", true)) $cacheInstance->cache_destroy();
-                       if ($cacheInstance->cache_file("mod_reg", true))    $cacheInstance->cache_destroy();
-                       if ($cacheInstance->cache_file("config", true))     $cacheInstance->cache_destroy();
-               } // END - if
+       // Remove cache file(s) if extension is active
+       if (((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) && (((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($load_mode == "activate") || ($load_mode == "deactivate"))) {
+               // Run filters
+               RUN_FILTER('post_extension_run_sql', $ext_name);
 
-               // Is this the sql_patches?
-               //* DEBUG: */ echo __LINE__.": {$id}/{$ext_name}/{$EXT_LOAD_MODE}<br />\n";
-               if (($ext_name == "sql_patches") && (($EXT_LOAD_MODE == "register") || ($EXT_LOAD_MODE == "remove"))) {
-                       // Then redirect to logout
-                       //* DEBUG: */ echo __LINE__.": LOAD!<br />\n";
-                       LOAD_URL("modules.php?module=admin&logout=1&".$EXT_LOAD_MODE."=sql_patches");
-               } // END - if
+               // @TODO This causes the whole (!) menu cache being purged
+               CACHE_PURGE_ADMIN_MENU();
+       } // END - if
+
+       // Is this the sql_patches?
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": {$ext_id}/{$ext_name}/{$load_mode}");
+       if (($ext_name == "sql_patches") && (($load_mode == "register") || ($load_mode == "remove"))) {
+               // Then redirect to logout
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": LOAD!");
+               LOAD_URL("modules.php?module=admin&logout=1&".$load_mode."=sql_patches");
        } // END - if
 }
+
 // Check if given extension is active
-function EXT_IS_ACTIVE ($ext_name, $ignore_admin = false, $ignore_cache = false) {
+function EXT_IS_ACTIVE ($ext_name) {
        global $cacheArray, $_CONFIG;
 
        // Extensions are all inactive during installation
        if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing')) || (empty($ext_name))) return false;
 
-       // Extension's file name will also be checked
-       $file = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
-       if ((!file_exists($file)) && (!is_readable($file))) return false;
-       //* DEBUG: */ echo "*".$ext_name."(".count($cacheArray).")<br />";
+       // Not active is the default
+       $active = "N";
 
-       // Failed is the default
-       $ret = false;
-       if ((!empty($cacheArray['extensions']['ext_active'][$ext_name])) && (!$ignore_cache)) {
+       // Check cache
+       if (!empty($cacheArray['extensions']['ext_active'][$ext_name])) {
                // Load from cache
-               //* DEBUG: */ echo "CACHE!<br />\n";
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "CACHE! ext_name={$ext_name}");
                $active = $cacheArray['extensions']['ext_active'][$ext_name];
 
                // Count cache hits
-               if (isset($_CONFIG['cache_hits'])) $_CONFIG['cache_hits']++;
-       } else {
-               //* DEBUG: */ echo "DB!<br />\n";
+               if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
+       } elseif (($ext_name == "cache") || (GET_EXT_VERSION("cache") == "")) {
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
                // Load from database
                $result = SQL_QUERY_ESC("SELECT ext_active FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
-                array($ext_name), __FILE__, __LINE__);
+                       array($ext_name), __FILE__, __LINE__);
+
+               // Entry found?
                if (SQL_NUMROWS($result) == 0) {
                        // Extension was not found!
                        return false;
-               }
+               } // END - if
+
+               // Load entry
                list($active) = SQL_FETCHROW($result);
+
+               // Free result
                SQL_FREERESULT($result);
 
                // Write cache array
+               //* DEBUG: */ echo $ext_name."[DB]: {$active}");
                $cacheArray['extensions']['ext_active'][$ext_name] = $active;
+       } else {
+               // Extension not active!
+               //* DEBUG: */ echo $ext_name.": Not active!");
+               $cacheArray['extensions']['ext_active'][$ext_name] = "N";
        }
 
+       // Debug message
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " ext_name={$ext_name},active={$active}");
+
        // Is this extension activated? (For admins we always have active extensions...)
-       $inc = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
-       // Shorter way
-       return (
-               (
-                       ($active == "Y") || (
-                               (IS_ADMIN()) &&
-                               (!$ignore_admin) &&
-                               (!empty($active))
-                       )
-               ) && (
-                       file_exists($inc)
-               ) && (
-                       is_readable($inc)
-               )
-       );
+       return ($active == "Y");
 }
 // Get version from extensions
 function GET_EXT_VERSION ($ext_name) {
@@ -358,14 +443,16 @@ function GET_EXT_VERSION ($ext_name) {
 
        // Extensions are all inactive during installation
        if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing'))) return "";
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ext_name={$ext_name}");
 
        // Is the cache written?
        if (!empty($cacheArray['extensions']['ext_version'][$ext_name])) {
                // Load data from cache
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": CACHE!");
                $ret = $cacheArray['extensions']['ext_version'][$ext_name];
 
                // Count cache hits
-               if (isset($_CONFIG['cache_hits'])) $_CONFIG['cache_hits']++; else $_CONFIG['cache_hits'] = 1;
+               if (getConfig('cache_hits') > 0) $_CONFIG['cache_hits']++; else $_CONFIG['cache_hits'] = 1;
        } elseif (!is_object($cacheInstance)) {
                // Load from database
                $result = SQL_QUERY_ESC("SELECT ext_version FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
@@ -376,67 +463,75 @@ function GET_EXT_VERSION ($ext_name) {
                // Set cache
                $cacheArray['extensions']['ext_version'][$ext_name] = $ret;
        }
+
+       // Return result
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ret={$ret}");
        return $ret;
 }
 //
-function EXTENSION_UPDATE($file, $ext, $EXT_VER, $dry_run=false)
-{
+function EXTENSION_UPDATE ($file, $ext_name, $ext_ver, $dry_run=false) {
        // This shall never do a non-admin user!
-       global $cacheInstance, $_CONFIG, $NOTES; $SQLs = array();
-       if ((!IS_ADMIN()) || (empty($ext))) return false;
+       global $cacheInstance, $_CONFIG, $UPDATE_NOTES, $NOTES, $EXT_VER_HISTORY;
+       global $EXT_UPDATE_DEPENDS, $EXT_VERSION;
+
+       // Init arrays
+       $SQLs = array(); $INC_POOL = array();
+
+       // Only admins are allowed to update extensions
+       if ((!IS_ADMIN()) || (empty($ext_name))) return false;
 
        // Load extension in update mode
-       $EXT_LOAD_MODE = "update"; $EXT_UPDATE_DEPENDS = ""; $NOTES = "";
-       include(PATH."inc/extensions/".$file);
-       if (!empty($EXT_UPDATE_DEPENDS))
-       {
+       LOAD_EXTENSION($ext_name, "update". $ext_ver, $dry_run);
+
+       if (!empty($EXT_UPDATE_DEPENDS)) {
                // Update another extension first!
                $test = EXTENSION_UPDATE(("ext-".$EXT_UPDATE_DEPENDS.".php"), $EXT_UPDATE_DEPENDS, GET_EXT_VERSION($EXT_UPDATE_DEPENDS), $dry_run);
        }
 
+       // Save version history
+       $history = $EXT_VER_HISTORY;
+
        // Check if version is updated
-       if ((($EXT_VERSION != $EXT_VER) || ($dry_run)) && (is_array($EXT_VER_HISTORY)))
-       {
+       if ((($EXT_VERSION != $ext_ver) || ($dry_run)) && (is_array($history))) {
                // Search for starting point
-               $start = array_search($EXT_VER, $EXT_VER_HISTORY);
+               $start = array_search($ext_ver, $history);
                $NOTES = "";
 
                // And load SQL queries in order of version history
-               for ($idx = ($start + 1); $idx < sizeof($EXT_VER_HISTORY); $idx++)
-               {
+               for ($idx = ($start + 1); $idx < sizeof($history); $idx++) {
                        // Remove old SQLs array to prevent possible bugs
                        if (!$dry_run) { unset($SQLs); $SQLs = array(); }
 
-                       // Set version
-                       $EXT_VER = $EXT_VER_HISTORY[$idx];
+                       // Set extension version
+                       $ver = $history[$idx];
 
-                       // Include again...
-                       include(PATH."inc/extensions/".$file);
+                       // Load again...
+                       LOAD_EXTENSION($ext_name, "update", $ver, $dry_run);
 
                        // Add notes
-                       if ($_CONFIG['verbose_sql'] == "Y")
-                       {
-                               $EXT_VER = $EXT_VER_HISTORY[$idx];
-                               if (!empty($UPDATE_NOTES))
-                               {
+                       if (getConfig('verbose_sql') == "Y") {
+                               if (!empty($UPDATE_NOTES)) {
                                        // Update notes found
-                                       $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".$UPDATE_NOTES."<br /><br />\n";
+                                       $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".$UPDATE_NOTES."</div>");
                                        $UPDATE_NOTES = "";
-                               }
-                                elseif ($EXT_VER == "0.0")
-                               {
+                               } elseif ($ver == "0.0") {
                                        // Initial release
-                                       $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".INITIAL_RELEASE."<br /><br />\n";
-                               }
-                                else
-                               {
-                                       $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br /><I>".NO_UPDATE_NOTES."</I><br /><br />\n";
+                                       $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".INITIAL_RELEASE."</div>");
+                               } else {
+                                       $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br /><I>".NO_UPDATE_NOTES."</I></div>");
                                }
-                       }
+                       } // END - if
+
+                       // In real-mode execute any existing includes
+                       if ((!$dry_run) && (count($INC_POOL) > 0)) {
+                               // Include all files
+                               foreach ($INC_POOL as $fqfn) {
+                                       require_once($fqfn);
+                               } // END - foreach
+                       } // END - if
 
                        // Run SQLs
-                       if ((is_array($SQLs)) && (!$dry_run))
-                       {
+                       if ((is_array($SQLs)) && (!$dry_run)) {
                                // Run SQL commands
                                foreach ($SQLs as $sql)
                                {
@@ -457,141 +552,256 @@ function EXTENSION_UPDATE($file, $ext, $EXT_VER, $dry_run=false)
                                // Remove SQLs if extension is not installed
                                $SQLs = array();
                        }
-               }
+               } // END - for
 
-               if (!$dry_run)
-               {
+               if (!$dry_run) {
                        // In normal mode insert task and update extension's version...
-                       $ext_subj = "[UPDATE-".$ext."-".$EXT_VERSION.":] ".ADMIN_UPDATE_EXT_SUBJ;
+                       $ext_subj = "[UPDATE-".$ext_name."-".$EXT_VERSION.":] ".ADMIN_UPDATE_EXT_SUBJ;
 
                        // Create task
-                       $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE subject='%s' LIMIT 1",
-                        array($ext_subj), __FILE__, __LINE__);
-                       if (SQL_NUMROWS($result) == 0)
-                       {
-                               // Task not created so it's a brand-new extension which we need to register and create a task for!
-                               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created) VALUES ('%s', '0', 'NEW', 'EXTENSION_UPDATE', '%s', '%s', UNIX_TIMESTAMP())",
-                                array(GET_ADMIN_ID(SQL_ESCAPE(get_session('admin_login'))), $ext_subj, addslashes($NOTES)), __FILE__, __LINE__);
-                       }
-
-                       // Free memory
-                       SQL_FREERESULT($result);
+                       CREATE_EXTENSION_UPDATE_TASK(GET_CURRENT_ADMIN_ID(), $ext_subj, addslashes($NOTES));
 
                        // Update extension's version
                        $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_version='%s' WHERE ext_name='%s' LIMIT 1",
-                        array($EXT_VERSION, $ext), __FILE__, __LINE__);
-
-                       // Update cache
-                       if (EXT_IS_ACTIVE("cache"))
-                       {
-                               if ($cacheInstance->cache_file("extensions", true) == true) $cacheInstance->cache_destroy();
-                               if ($cacheInstance->cache_file("config", true) == true)     $cacheInstance->cache_destroy();
-                               if ($cacheInstance->cache_file("mod_reg", true) == true)    $cacheInstance->cache_destroy();
-                       }
+                               array($EXT_VERSION, $ext_name), __FILE__, __LINE__);
 
                        // Remove array
                        unset($SQLs);
-               }
-                else
-               {
+
+                       // Run filters on success extension update
+                       RUN_FILTER('extension_update', $ext_name);
+               } else {
                        // In "dry-run" mode return array with SQL commands
                        return $SQLs;
                }
        }
 }
-//
-function EXTENSION_VERBOSE_TABLE($SQLs, $title = ADMIN_SQLS_EXECUTED_ON_REMOVAL, $dashed = "", $switch = false, $WIDTH = "480") {
-       global $_CONFIG;
 
+// Output verbose SQL table for extension
+function EXTENSION_VERBOSE_TABLE ($queries = array(), $title = ADMIN_SQLS_EXECUTED_ON_REMOVAL, $dashed = "", $switch = false, $width = "480") {
+       global $_CONFIG, $SQLs;
+
+       // Are there some queries in $queries?
+       if (count($queries) > 0) {
+               // Then use them instead!
+               $SQLs = $queries;
+       } // END - if
+
+       // Init variables
        $S = false; $SW = 2; $i = 1;
        $OUT = "";
-       if ((is_array($SQLs)) && (GET_EXT_VERSION("sql_patches")) && ($_CONFIG['verbose_sql'] == "Y")) {
-               $OUT  = "<DIV align=\"center\">
-<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"".$WIDTH."\" align=\"center\"".$dashed.">
-<TR>
-  <TD colspan=\"2\" align=\"center\" class=\"admin_title bottom2\" height=\"24\">
-    <STRONG>".$title.":</STRONG>
-  </TD>
-</TR>\n";
+
+       // Do we have queries?
+       if ((is_array($SQLs)) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
+               $OUT  = "<div align=\"center\">
+<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"".$width."\" align=\"center\"".$dashed.">
+<tr>
+  <td colspan=\"2\" align=\"center\" class=\"admin_title bottom2\" height=\"24\">
+    <strong>".$title.":</strong>
+  </td>
+</tr>\n";
                foreach ($SQLs as $idx => $sql) {
                        $sql = trim($sql);
                        if (!empty($sql)) {
                                $S = true;
-                               $OUT .= "<TR>
-  <TD class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 2px\" width=\"30\">".$i.".</TD>
-  <TD class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 5px; padding-right: 5px\">
+                               $OUT .= "<tr>
+  <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 2px\" width=\"30\">".$i.".</td>
+  <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 5px; padding-right: 5px\">
     ".$sql."
-  </TD>
-</TR>\n";
+  </td>
+</tr>\n";
                                if ($switch) $SW = 3 - $SW;
                                $i++;
                        }
                }
        }
 
-       if ((!$S) && (GET_EXT_VERSION("sql_patches")) && ($_CONFIG['verbose_sql'] == "Y")) {
+       if ((!$S) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
                // No addional SQL commands to run
-               $OUT .= "<TR>
-  <TD colspan=\"2\" align=\"center\" class=\"switch_sw2 bottom2\" height=\"24\">
-    <FONT class=\"admin_note\">".ADMIN_NO_ADDIONAL_SQLS."</FONT>
-  </TD>
-</TR>\n";
+               $OUT .= "<tr>
+  <td colspan=\"2\" align=\"center\" class=\"switch_sw2 bottom2\" height=\"24\">
+    <font class=\"admin_note\">".ADMIN_NO_ADDIONAL_SQLS."</font>
+  </td>
+</tr>\n";
        }
 
        if (!empty($OUT)) {
                // Add missing close-table tag
-               $OUT .= "</TABLE>
-</DIV>\n";
+               $OUT .= "</table>
+</div>\n";
        }
 
        // Return output
        return $OUT;
 }
-//
-function GET_EXT_NAME($id)
-{
-       $ret = "";
+
+// Get extension name from id
+function GET_EXT_NAME ($ext_id) {
        global $cacheArray, $_CONFIG;
-       if (!empty($cacheArray['extensions']['ext_id'][$id]))
-       {
+
+       // Init extension name
+       $ret = "";
+
+       // Is cache there?
+       if (!empty($cacheArray['extensions']['ext_name'][$ext_id])) {
                // Load from cache
-               $ret = $cacheArray['extensions']['ext_id'][$id];
+               $ret = $cacheArray['extensions']['ext_name'][$ext_id];
 
                // Count cache hits
-               $_CONFIG['cache_hits']++;
-       }
-        else
-       {
+               if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
+       } elseif (!EXT_IS_ACTIVE("cache")) {
                // Load from database
                $result = SQL_QUERY_ESC("SELECT ext_name FROM "._MYSQL_PREFIX."_extensions WHERE id=%s LIMIT 1",
-                array(bigintval($id)), __FILE__, __LINE__);
+                       array(bigintval($ext_id)), __FILE__, __LINE__);
                list($ret) = SQL_FETCHROW($result);
                SQL_FREERESULT($result);
        }
        return $ret;
 }
-//
-function GET_EXT_ID($name)
-{
-       $ret = "0";
+
+// Get extension id from name
+function GET_EXT_ID ($ext_name) {
        global $cacheArray, $_CONFIG;
-       if ((isset($cacheArray['extensions']['ext_id'])) && (is_array($cacheArray['extensions']['ext_id'])))
-       {
+
+       // Init ID number
+       $ret = 0;
+       if (isset($cacheArray['extensions']['ext_id'][$ext_name])) {
                // Load from cache
-               $ret = array_search($name, $cacheArray['extensions']['ext_id']);
+               $ret = $cacheArray['extensions']['ext_id'][$ext_name];
 
                // Count cache hits
-               $_CONFIG['cache_hits']++;
-       }
-        else
-       {
+               if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
+       } elseif (!EXT_IS_ACTIVE("cache")) {
                // Load from database
                $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
-                array($name), __FILE__, __LINE__);
+                       array($ext_name), __FILE__, __LINE__);
                list($ret) = SQL_FETCHROW($result);
                SQL_FREERESULT($result);
        }
+
+       // Return value
        return $ret;
 }
+
+// Activate given extension
+function ACTIVATE_EXTENSION ($ext_name) {
+       // Activate the extension
+       $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='Y' WHERE ext_name='%s' LIMIT 1",
+               array($ext_name), __FILE__, __LINE__);
+
+       // Extension has been activated?
+       if (SQL_AFFECTEDROWS() == 1) {
+               // Then run all queries
+               EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "activate");
+       } // END - if
+}
+
+// Deactivate given extension
+function DEACTIVATE_EXTENSION($ext_name) {
+       // Activate the extension
+       $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='N' WHERE ext_name='%s' LIMIT 1",
+               array($ext_name), __FILE__, __LINE__);
+
+       // Extension has been activated?
+       if (SQL_AFFECTEDROWS() == 1) {
+               // Then run all queries
+               EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "deactivate");
+
+               // Create new task
+               CREATE_EXTENSION_DEACTIVATION_TASK($ext_name);
+
+               // Notify the admin
+               SEND_ADMIN_NOTIFICATION(ADMIN_SUBJECT_EXTENSION_DEACTIVATED, "admin_ext_deactivated", array('ext_name' => $ext_name));
+       } // END - if
+}
+
+// Checks wether the extension is older than given
+function EXT_VERSION_IS_OLDER ($ext_name, $ext_ver) {
+       // Get current extension version
+       $currVersion = GET_EXT_VERSION($ext_name);
+
+       // Remove all dots from both versions
+       $currVersion = str_replace(".", "", $currVersion);
+       $ext_ver = str_replace(".", "", $ext_ver);
+
+       // Now compare both and return the result
+       return ($currVersion < $ext_ver);
+}
+
+// Creates a new task for updated extension
+function CREATE_EXTENSION_UPDATE_TASK ($admin_id, $subject, $notes) {
+       // Check if task is not there
+       $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE subject='%s' LIMIT 1",
+               array($subject), __FILE__, __LINE__);
+       if (SQL_NUMROWS($result) == 0) {
+               // Task not created so it's a brand-new extension which we need to register and create a task for!
+               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created) VALUES ('%s','0','NEW','EXTENSION_UPDATE','%s','%s', UNIX_TIMESTAMP())",
+                       array($admin_id, $subject, $notes), __FILE__, __LINE__);
+       } // END - if
+
+       // Free memory
+       SQL_FREERESULT($result);
+}
+
+// Creates a new task for newly installed extension
+function CREATE_NEW_EXTENSION_TASK ($admin_id, $subject, $ext) {
+       // Not installed and do we have created a task for the admin?
+       $result = SQL_QUERY_ESC("SELECT `id` FROM `"._MYSQL_PREFIX."_task_system` WHERE `subject` LIKE '%s%%' LIMIT 1",
+               array($subject), __FILE__, __LINE__);
+       if ((SQL_NUMROWS($result) == 0) && (GET_EXT_VERSION($ext) == "")) {
+               // Template file
+               $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
+                       PATH,
+                       GET_LANGUAGE(),
+                       $ext
+               );
+
+               // Load text for task
+               if (FILE_READABLE($tpl)) {
+                       // Load extension's own text template (HTML!)
+                       $msg = LOAD_TEMPLATE("ext_".$ext, true);
+               } else {
+                       // Load default message
+                       $msg = LOAD_TEMPLATE("admin_new_ext", "", 0);
+               }
+
+               // Task not created so it's a brand-new extension which we need to register and create a task for!
+               $result_insert = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created)
+VALUES (%s,0,'NEW','EXTENSION','%s','%s',UNIX_TIMESTAMP())",
+                       array(
+                               $admin_id,
+                               $subject,
+                               addslashes($msg),
+                       ),  __FILE__, __LINE__, true, false
+               );
+       } // END - if
+
+       // Free memory
+       SQL_FREERESULT($result);
+}
+
+// Creates a task for automatically deactivated (deprecated) extension
+function CREATE_EXTENSION_DEACTIVATION_TASK ($ext) {
+       // Create subject line
+       $subject = sprintf("[%s:] %s", $ext, TASK_SUBJ_EXTENSION_DEACTIVATED);
+
+       // Not installed and do we have created a task for the admin?
+       $result = SQL_QUERY_ESC("SELECT `id` FROM `"._MYSQL_PREFIX."_task_system` WHERE `subject` = '%s' LIMIT 1",
+               array($subject), __FILE__, __LINE__);
+       if ((SQL_NUMROWS($result) == 0) && (GET_EXT_VERSION($ext) != "")) {
+               // Task not created so add it
+               $result_insert = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created)
+VALUES (0,0,'NEW','EXTENSION_DEACTIVATION','%s','%s',UNIX_TIMESTAMP())",
+                       array(
+                               $subject,
+                               addslashes(LOAD_TEMPLATE("task_ext_deactivated", true, $ext)),
+                       ),  __FILE__, __LINE__, true, false
+               );
+       } // END - if
+
+       // Free memory
+       SQL_FREERESULT($result);
+}
+
 //
 ?>