<?php /*

 Composr
 Copyright (c) ocProducts, 2004-2016

 See text/EN/licence.txt for full licencing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/*EXTRA FUNCTIONS: mysql\_.+*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  ocProducts Ltd
 * @package    core_cleanup_tools
 */

/**
 * Hook class.
 */
class Hook_cleanup_mysql_optimise
{
    /**
     * Find details about this cleanup hook.
     *
     * @return ?array Map of cleanup hook info (null: hook is disabled).
     */
    public function info()
    {
        if (substr(get_db_type(), 0, 5) != 'mysql') {
            return null;
        }

        $info = array();
        $info['title'] = do_lang_tempcode('MYSQL_OPTIMISE');
        $info['description'] = do_lang_tempcode('DESCRIPTION_MYSQL_OPTIMISE');
        $info['type'] = 'optimise';

        return $info;
    }

    /**
     * Run the cleanup hook action.
     *
     * @return Tempcode Results
     */
    public function run()
    {
        $out = new Tempcode();

        $tables = $GLOBALS['SITE_DB']->query_select('db_meta', array('DISTINCT m_table'));
        if (count($GLOBALS['SITE_DB']->connection_write) > 4) { // Okay, we can't be lazy anymore
            $GLOBALS['SITE_DB']->connection_write = call_user_func_array(array($GLOBALS['SITE_DB']->static_ob, 'db_get_connection'), $GLOBALS['SITE_DB']->connection_write);
            _general_db_init();
        }
        $db = $GLOBALS['SITE_DB']->connection_write;

        $static_ob = $GLOBALS['SITE_DB']->static_ob;

        foreach ($tables as $table) {
            if ($table['m_table'] == 'sessions') {
                continue; // HEAP, so can't be repaired
            }

            $table = get_table_prefix() . $table['m_table'];

            // Check/Repair
            $result = $static_ob->db_query('CHECK TABLE ' . $table . ' FAST', $db);
            $status_row = end($result);
            if ($status_row['Msg_type'] != 'status') {
                $out->attach(paragraph(do_lang_tempcode('TABLE_ERROR', escape_html($table), escape_html($status_row['Msg_type']), array(escape_html($status_row['Msg_text']))), 'dfsdgdsgfgd'));
                $result2 = $static_ob->db_query('REPAIR TABLE ' . $table, $db);
                $status_row_2 = end($result2);
                $out->attach(paragraph(do_lang_tempcode('TABLE_FIXED', escape_html($table), escape_html($status_row_2['Msg_type']), array(escape_html($status_row_2['Msg_text']))), 'dfsdfgdst4'));
            }

            // Optimise
            $static_ob->db_query('OPTIMIZE TABLE ' . $table, $db);
        }

        return $out;
    }
}
