<?php
/**
 * Install portlets controller
 *
 * @property Installation     $installation
 * @author christian.k
 */
class Install_portlets extends My_Controller
{

    public function __construct()
    {
        parent::__construct();

        date_default_timezone_set($this->config->item('date_default_timezone'));

        if ($this->agent->supports_lang('de')) {
            define('LANG', 'german');
        } else {
            define('LANG', 'english');
        }
        $this->lang->load('basic', LANG);

        //Preload libraries
        $this->load->library('Security', null, 'security');

        require_once(APPPATHLIVE . 'libraries/US_Portlet_install.php');
        require_once(APPPATHLIVE . 'libraries/US_Portlet_update.php');
        $this->us_portlet_install = new US_Portlet_install();
        $this->us_portlet_update = new US_Portlet_update();

        require_once(APPPATHLIVE . 'helpers/xml_errors_helper.php');
        require_once(APPPATHLIVE . 'helpers/us_portlet_helper.php');
        require_once(APPPATHLIVE . 'helpers/recurse_copy_helper.php');
        require_once(APPPATH . 'helpers/secure_url_get_contents_helper.php');
    }

    public function index()
    {

        //Validate key
        $update_key = $this->input->post('update_key');
        if ($update_key===false) {
            $this->_write_error('Cannot validate update_key 1'); //Update key missing
            return;
        }
        $update_file_filename = WRITEABLEPATH.'applications/update.php';
        if (!is_readable($update_file_filename)) {
            $this->_write_error('Cannot validate update_key 2'); //Update key file missing
            return;
        }
        $update_file_info = file_get_contents($update_file_filename);
        if ($update_file_info===false) {
            $this->_write_error('Cannot validate update_key 3'); //Update key file not read valid
            return;
        }
        list($update_file_key, $update_file_serial) = explode(';', $update_file_info, 2);
        if ($update_file_key!==$update_key) {
            $this->_write_error('Cannot validate update_key 4'); //Update key does not match
            return;
        }
        
        //Validate method
        $method = $this->input->post('method');
        if ($method===false || ($method!=='update' && $method!=='installation')) {
            $this->_write_error('Cannot validate method'); //Method missing
            return;
        }
        
        //Validate key
        $add_hoai = ('add'===$this->input->post('add_hoai')) ? true : false;
        
        //Prevent from memory / timeout errors
        ignore_user_abort(true);
        @ini_set('memory_limit', '200M');
        @set_time_limit(36000);
        
        //Start flush
        @ini_set('zlib.output_compression', 0);
        @ob_implicit_flush(true);
        while (@ob_get_level()) {
            @ob_end_flush();
        }
        
        //Install
        echo $this->load->view('header', array(), true);
        echo '<h2>'.lang('do_install_portlets').'</h2>';
        
        $to_view = array(
            'portlet_update_key' => $update_file_key,
            'method' => $method,
        );
        
        //Install portlets
        $msg = $this->_install_portlets($update_file_serial, $add_hoai);
        if ($msg!==false) {
            $to_view['error_task'] = $msg;
        } elseif (!unlink($update_file_filename)) {
            $to_view['error_task'] = 'Cannot remove update_key file.';
        } else {
            $to_view['ok_task'] = 'Successful / Erfolgreich';
        }
        
        echo $this->load->view('step4', $to_view, true);
        
        echo $this->load->view('footer', array(), true);
    }
    
    /**
     * Install portlets
     * 
     * @param   string      $serial     Serial number
     * @param   boolean     $add_hoai   Add HOAI
     * @return  mixed       Either false or an error message
     */
    private function _install_portlets($serial, $add_hoai)
    {
        $to_install = array(
            'com_untermstrich_modify_office_files',
            'com_untermstrich_crm_addresses',
            'org_apache_tika',
            'com_untermstrich_budget_evaluation_for_project_leaders',
            'com_untermstrich_liqui',
            'com_untermstrich_budget_liqui',
        );
        
        if ($add_hoai) {
            $to_install[] = 'com_untermstrich_hoai';
        }
        
        //Hinweis: Mitarbeiterstundensatz - com_untermstrich_employee_hourly_rate wird in X4 entfernt
        
        try {
            $this->us_portlet_update->set_serial($serial);
            $xml = $this->us_portlet_update->load_update_info();
        } catch (Exception $exc) {
            return 'No access to under web services / Keine Zugriff auf untermStrich Webservices: <br />'.$exc->getMessage();
        }
        
        try {
            foreach ($xml->entry as $entry) {
                $portlet_name = (string) $entry->name;

                if (in_array($portlet_name, $to_install)) {
                    $portlet_title = (string) $entry->title;
                    $portlet_link = (string) $entry->link;
                    $portlet_size = intval($entry->size);
                    
                    echo '<br /><small>Installing: '.$portlet_title.'</small>';
                    echo '<br />&nbsp;&nbsp;';
                    $msg = $this->_install_portlet($portlet_link, $portlet_size);
                    if ($msg!==false) {
                        return (string)$msg;
                    }
                }
            }
        } catch (Exception $exc) {
            return 'Error processing portlets: <br />'.$exc->getMessage();
        }
        echo '<br />&nbsp;';

        return false;
    }
    
    /**
     * Install a single portlet
     * 
     * @param   string      $link               Link to download
     * @param   integer     $file_length        File length
     * @return  mixed       Either false or an error message
     */
    private function _install_portlet($link, $file_length)
    {
        try {
            //Download file
            echo '<small>Download... </small>';
            $to_file = $this->config->item('us_updatesdir').pathinfo($link, PATHINFO_BASENAME);

            $info = secure_url_get_contents($link, $to_file, $file_length*2);
            if ($info===false) {
                return 'The zip file "'.$link.'" cannot be read.';
            }

            //Install file
            echo '<small>Install... </small>';
            $ok = $this->us_portlet_install->install($to_file, '473gf791dh8hwc');
            if ($ok!==false) {
                return 'Error installing portlet "'.$ok.'".';
            }

            echo '<small>Done.</small>';
        } catch (Exception $exc) {
            return 'Error installing portlet: <br />'.$exc->getMessage();
        }

        return false;
    }
    
    /**
     * Write the error message only
     * 
     * @param   string      $msg        Message
     */
    private function _write_error($msg)
    {
        $this->load->view('header');
        
        $this->load->view('_errorinfo', array(
            'error_task' => $msg
        ));
        log_message('error', print_r($msg, true));
        
        $this->load->view('footer');
    }

}
