<?php
/**
 * CodeIgniter Controller
 *
 * @category CodeIgniter
 * @license /_licenses/untermStrich/agb_normal.pdf
 * @author Christian Koller
 * @copyright 2009 untermStrich
 * @package controllers
 * @version $Id: start.php 16153 2018-07-11 09:58:46Z christian $
*/

/**
 * The simple controller for untermStrich
 */
class Simple extends My_Controller
{
    public function __construct()
    {
        $this->in_simple_mode = true;
        parent::__construct();
    }
    
    /**
     * Opens a page XAJAX
     *
     * <pre>
     * $_POST string section   Section
     * $_POST string page      Page
     * $_POST string xjxcookie Xajax cookie
     * </pre>
     * 
     * @return void
     */
    public function openxping()
    {
        if ( !$this->login->is_logged_in() ) {
            $this->load->library('US_Xajax_response', '', 'xajax');
            $this->xajax->redirect(site_url($this->config->item('sess_login_page')));
            $this->xajax->write();
            return;
        }
        
        $this->login->restrict_xsrf($this->input->post('xjxcookie'), self::M_XAJAX);
        
        try {
            $this->load->page('ping', 'index', self::M_XAJAX);
        } catch (Exception $exc) {
            $this->load->library('US_Xajax_response', '', 'xajax');
            $msg = 'Fehler/Error in openxping '.$exc->getCode().': '.$exc->getMessage();
            $this->xajax->message($msg, US_Xajax_response::MSGM_ERROR);
            log_message('error', $msg);
            $this->xajax->write();
        }        
    }
    
    /**
     * A shared ping using shared us_pinger AJAX
     *
     * <pre>
     * $_POST string xjxcookie Ajax cookie
     * </pre>
     * 
     * @return  void
     */
    public function openxsharedping()
    {
        if ( !$this->login->is_logged_in() ) {
            return;
        }
        
        $this->login->restrict_xsrf($this->input->post('xjxcookie'), self::M_REST);
        
        try {
            if ($this->session->sess_update(false)) {
                if (!headers_sent()) {
                    set_status_header(200);
                }
                echo 'OK FULL';
            } else {
                if (!headers_sent()) {
                    set_status_header(200);
                }
                echo 'OK PART';
            }
            
        } catch (Exception $exc) {
            $msg = 'Fehler/Error in openxsharedping '.$exc->getCode().': '.$exc->getMessage();
            basic_error($msg, self::M_REST, __CLASS__.'::'.__FUNCTION__, 500);
        }        
    }

    /**
     * Get the portlets list for us_dexie_worker
     *
     * <pre>
     * $_POST string xjxcookie Ajax cookie
     * </pre>
     * 
     * @return  void
     */
    public function get_portlets()
    {
        if ( !$this->login->is_logged_in() ) {
            return;
        }

        if (!headers_sent()) {
            set_status_header(200);
            header('Content-type: application/json');
        }

        $this->load->helper('us_html');
        $this->lang->load('basic', $this->web_settings->getLanguage());

        $portlets = $this->load->list_widgets(self::M_REST, true);
        #log_message('error', print_r($portlets, true));
        $data = array();
        foreach ($portlets as $portlet) {
            if (!empty($portlet['is_react'])) {
                continue;
            }
            $tmp = new stdClass();
            $tmp->name = $portlet['name'];
            $tmp->portlet_id = $portlet['class']; //Classfilename
            $tmp->is_purchased = $portlet['is_purchased'];
            $tmp->main_title = $this->lang->line_ns(strtolower($portlet['widget_information']->main_title));//need to translate
            $tmp->title = $portlet['widget_information']->title;
            $tmp->col_preset = (isset($portlet['widget_information']->col_preset)) ? $portlet['widget_information']->col_preset : 3;
            $tmp->title_lang = str_ireplace('&shy;', '', $portlet['widget_information']->title_lang);
            $tmp->keywords = [mb_strtolower($tmp->title_lang), mb_strtolower($tmp->main_title)]; //need to translate

            if (isset($portlet['widget_information']->keywords) && is_array($portlet['widget_information']->keywords) && count($portlet['widget_information']->keywords) > 0) {
                foreach ($portlet['widget_information']->keywords as $keyword) {
                    $tmp->keywords[] = mb_strtolower($this->lang->line_ns($keyword));
                }
            }  

            $data[] = $tmp;
        }

        echo us_json_encode($data);
    }

    /**
     * Get my used portlets list for us_dexie_worker
     *
     * <pre>
     * $_POST string xjxcookie Ajax cookie
     * </pre>
     * 
     * @return  void
     */
    public function get_my_portlets()
    {
        if ( !$this->login->is_logged_in() ) {
            return;
        }

        if (!headers_sent()) {
            set_status_header(200);
        }

        $this->load->helper('us_html');
        $this->load->model('Portlets_model', 'portlets', true);
        $this->lang->load('basic', $this->web_settings->getLanguage());

        $available_portlets = array();
        foreach ($this->load->list_widgets(self::M_REST, true) as $portlet) {
            $available_portlets[$portlet['class']] = array(
                mb_strtolower($this->lang->line_ns(strtolower($portlet['widget_information']->main_title ?? ''))),
                mb_strtolower(str_ireplace('&shy;', '', $portlet['widget_information']->title_lang ?? ''))
            );

            if (isset($portlet['widget_information']->keywords) && is_array($portlet['widget_information']->keywords) && count($portlet['widget_information']->keywords) > 0) {
                foreach ($portlet['widget_information']->keywords as $keyword) {
                    $available_portlets[$portlet['class']][] = mb_strtolower($this->lang->line_ns($keyword));
                }
            }
        }

        $request_vars = new stdClass();
        $request_vars->staff_id = $this->login->get_user_id();
        $portlets = $this->portlets->get_list($request_vars);

        $data = array();
        foreach ($portlets as $portlet) { 
            $tmp = new stdClass();
            $tmp->portlet_id = $portlet->portlet_id . '___' . $portlet->unique_id;
            $tmp->page_id = empty($portlet->page_id) ? null : $portlet->page_id;
            $tmp->tab_id = empty($portlet->tab) ? null : $portlet->tab;
            $tmp->keywords = array(str_replace('&shy;', '',mb_strtolower($portlet->title ?? '')));

            if (!empty($available_portlets[$portlet->portlet_id])) {
                $tmp->keywords = array_merge($tmp->keywords, $available_portlets[$portlet->portlet_id]);
            }

            $data[] = $tmp;
        }

        echo us_json_encode($data);
    }
    
    /**
     * Oauth logout done page
     */
    public function oauth_logout_done()
    {
        $data = array(
            'action'        => 'window.opener.webApp.oauth.onLogoutDo();window.close();',
            'wait'          => '3000',
            'us_version_ue' => urlencode($this->config->item('us_version')),
            'css_path'      => $this->config->item('us_css_path'),
            'js_path'       => $this->config->item('us_js_path'),
            'title'         => 'Logout successful'
        );
        $this->load->view('Basic/startpage_oauth', $data);
    }
    
}
