<?PHP
#
#   FILE:  DBCleanUp.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

/**
* Database cleanup plugin, intended for use in development environments to
* clean up stray database entries resulting from interim or development code..
*/
class DBCleanUp extends Plugin {

    # ---- STANDARD PLUGIN INTERFACE -----------------------------------------

    /**
    * Set the plugin attributes.
    */
    function Register()
    {
        $this->Name = "Database Clean Up";
        $this->Version = "1.1.0";
        $this->Description = "Periodically looks for and removes"
                ." stray database entries, usually the result"
                ." of debugging or interim development code.";
        $this->Author = "Internet Scout";
        $this->Url = "http://scout.wisc.edu/cwis/";
        $this->Email = "scout@scout.wisc.edu";
        $this->Requires = array(
                "CWISCore" => "3.0.0");
        $this->EnabledByDefault = FALSE;

        $this->CfgSetup["Frequency"] = array(
                "Type" => "Option",
                "Label" => "Cleanup Frequency",
                "Help" => "How often database cleanup should be run.",
                "Options" => array(
                        self::FREQ_DAILY => "Daily",
                        self::FREQ_WEEKLY => "Weekly",
                        self::FREQ_MONTHLY => "Monthly",
                        ),
                );
        $this->CfgSetup["DoOptimize"] = array(
                "Type" => "Flag",
                "Label" => "Optimize Tables",
                "Help" => "Whether to run OPTIMIZE on appropriate tables"
                        ." when doing database cleanup.",
                "Default" => FALSE,
                );
    }

    /**
    * Perform any work needed when the plugin is first installed (for example,
    * creating database tables).
    * @return NULL if installation succeeded, otherwise a string containing
    *       an error message indicating why installation failed.
    */
    function Install()
    {
        $this->ConfigSetting("Frequency", self::FREQ_DAILY);
        return NULL;
    }

    /**
    * Declare the events this plugin provides to the application framework.
    * @return An array of the events this plugin provides.
    */
    public function DeclareEvents()
    {
        return array(
            "DBCleanUp_EXTERNAL_CLEAN"
              => ApplicationFramework::EVENTTYPE_DEFAULT);
    }

    /**
    * Hook methods to be called when specific events occur.
    * For events declared by other plugins the name string should start with
    * the plugin base (class) name followed by "::" and then the event name.
    * @return Array of method names to hook indexed by the event constants
    *       or names to hook them to.
    */
    function HookEvents()
    {
        switch ($this->ConfigSetting("Frequency"))
        {
            case self::FREQ_DAILY:  $ToHook = "EVENT_DAILY";  break;
            case self::FREQ_MONTHLY:  $ToHook = "EVENT_MONTHLY";  break;
            case self::FREQ_WEEKLY:  $ToHook = "EVENT_WEEKLY";  break;
        }
        return array(
                $ToHook => "CleanUp",
                );
    }


    # ---- HOOKED METHODS ----------------------------------------------------

    /**
    * Perform database cleanup tasks. Intended to be hooked to a periodic event.
    */
    function CleanUp()
    {
        # clean up any links from controlled names to resources that no longer exist
        $DB = new Database();
        $DB->Query("DELETE FROM ResourceNameInts"
                ." WHERE ResourceId NOT IN (SELECT ResourceId FROM Resources);");

        # clean up any links from classifications to resources that no longer exist
        $DB->Query("DELETE FROM ResourceClassInts"
                ." WHERE ResourceId NOT IN (SELECT ResourceId FROM Resources);");

        # if table optimization is turned on
        if ($this->ConfigSetting("DoOptimize"))
        {
            # optimize frequently-modified tables with variable-width columns
            $DB->Query("OPTIMIZE TABLE Resources");
            $DB->Query("OPTIMIZE TABLE Files");
            $DB->Query("OPTIMIZE TABLE Images");
            $DB->Query("OPTIMIZE TABLE ControlledNames");
            $DB->Query("OPTIMIZE TABLE VariantNames");
            $DB->Query("OPTIMIZE TABLE Classifications");
            $DB->Query("OPTIMIZE TABLE Folders");
        }

        # signal other plugins to perform cleanup tasks
        $GLOBALS["AF"]->SignalEvent("DBCleanUp_EXTERNAL_CLEAN");
    }

    /** Cleanup frequency intervals. */
    const FREQ_DAILY = 1;
    const FREQ_WEEKLY = 2;
    const FREQ_MONTHLY = 3;

}
