<?php
class setting extends control
{
    /**
     * Configuration of xuanxuan.
     *
     * @param  string $type
     * @access public
     * @return void
     */
    public function xuanxuan($type = '')
    {
        if($type != 'edit' && empty($this->config->xuanxuan->server)) $this->locate(inlink('xuanxuan', 'type=edit'));
        if($type != 'edit' && (!zget($this->config->xuanxuan, 'key', '') or zget($this->config->xuanxuan, 'key', '') == str_repeat(8, 32))) $this->locate(inlink('xuanxuan', 'type=edit'));

        if(!isset($_SESSION['clearFileName'])) {
            $clearFileName = $this->app->getBasePath() . 'tmp' . DIRECTORY_SEPARATOR . uniqid('clear_') . '.txt';
            $this->session->set('clearFileName', $clearFileName);
        }
        $clearFileName = $this->session->clearFileName;

        $this->app->loadLang('im');
        if($_POST)
        {
            if(array_key_exists('key', $_POST))
            {
                $errors  = array();
                $setting = fixer::input('post')->get();

                if(strlen($this->post->key) != 32 or !validater::checkREG($this->post->key, '|^[A-Za-z0-9]+$|')) $errors['key'] = $this->lang->im->errorKey;
                if($this->post->key == str_repeat(8, 32)) $errors['key'] = $this->lang->im->defaultKey;

                if($setting->https == 'on')
                {
                    if(empty($setting->sslcrt)) $errors['sslcrt'] = $this->lang->im->errorSSLCrt;
                    if(empty($setting->sslkey)) $errors['sslkey'] = $this->lang->im->errorSSLKey;
                }

                if(strpos($setting->server, '127.0.0.1') !== false) $errors['server'][] = $this->lang->im->xxdServerError;
                if(strpos($setting->server, 'https://') !== 0 and strpos($setting->server, 'http://') !== 0) $errors['server'][] = $this->lang->im->xxdSchemeError;
                if(empty($setting->server)) $errors['server'][] = $this->lang->im->xxdServerEmpty;

                /* Check if value is a valid positive number. (float or int) */
                if(!is_numeric($setting->uploadFileSize) || (int)$setting->uploadFileSize < 0) $errors['uploadFileSize'] = $this->lang->im->xxdFileSizeErr;

                /* Check if value is a valid positive int. */
                if(!(is_numeric($setting->chatPort) && is_int($setting->chatPort + 0)) || (int)$setting->chatPort <= 0 || (int)$setting->chatPort > 65535) $errors['chatPort'] = $this->lang->im->xxdPortError;
                if(!(is_numeric($setting->commonPort) && is_int($setting->commonPort + 0)) || (int)$setting->commonPort <= 0 || (int)$setting->commonPort > 65535) $errors['commonPort'] = $this->lang->im->xxdPortError;
                if(!(is_numeric($setting->pollingInterval) && is_int($setting->pollingInterval + 0)) || (int)$setting->pollingInterval < 5) $errors['pollingInterval'] = $this->lang->im->xxdPollIntErr;
                if(!(is_numeric($setting->tokenLifetime) && is_int($setting->tokenLifetime  + 0)) || (int)$setting->tokenLifetime < 1) $errors['tokenLifetime'] = $this->lang->im->tokenLifetimeErr;
                if(!(is_numeric($setting->tokenAuthWindow) && is_int($setting->tokenAuthWindow  + 0)) || (int)$setting->tokenAuthWindow < 20) $errors['tokenAuthWindow'] = $this->lang->im->tokenAuthWindowErr;
                if(isset($setting->iceServers))
                {
                    $servers = array_map(
                        function($x) {return trim($x);},
                        array_filter(explode("\n", $setting->iceServers))
                    );
                    $setting->iceServers = implode(',', $servers);
                    foreach ($servers as $server)
                    {
                        if(strlen($server) > 5 && preg_match('/^(stun|turn):/', $server) === 1)
                        {
                            $result = parse_url(substr($server, 5));
                            if($result !== false && count($result) === 2 && array_key_exists('host', $result) && array_key_exists('port', $result))
                            {
                                continue;
                            }
                        }
                        $errors['iceServers'] = $this->lang->im->iceServersErr ;
                        break;
                    }
                }
                if(isset($setting->fileEncrypt) && $setting->fileEncrypt == 'on' && !isset($errors['key'])) $setting->fileEncryptionKey = $this->post->key;

                $comment = json_encode($_POST);
                if($errors)
                {
                    $this->setting->addSettingAction('paramProfile', 0, 'edit', 'fail', $comment);
                    $this->send(array('result' => 'fail', 'message' => $errors));
                }
                if(isset($setting->messageEncrypt) && $setting->messageEncrypt == 'on')
                {
                    if(!isset($this->config->xuanxuan->lastUnEncryptMessageId))
                    {
                        $lastUnEncryptMessageId = $this->loadModel('im')->message->getLastMessageId();
                        $this->loadModel('setting')->setItem('system.common.xuanxuan.lastUnEncryptMessageId', $lastUnEncryptMessageId);
                    }
                }

                $result = $this->loadModel('setting')->setItems('system.common.xuanxuan', $setting);
                if(!$result)
                {
                    $this->setting->addSettingAction('paramProfile', 0, 'edit', 'fail', $comment);
                    $this->send(array('result' => 'fail', 'message' => dao::getError()));
                }
                $this->setting->addSettingAction('paramProfile', 0, 'edit', 'success', $comment);
                $this->send(array('result' => 'success', 'message' => $this->lang->saveSuccess, 'locate' => inlink('xuanxuan')));
            }
            else if($this->config->product == 'xxb')
            {
                if(!isset($_SESSION['clearFileName']) || !file_exists($_SESSION['clearFileName']) || time() - filemtime($_SESSION['clearFileName']) > 60 * 2)
                {
                    $lang = $this->lang->setting->createClearFile . ' ' . addslashes($_SESSION['clearFileName']);
                    $this->send(array('result' => 'fail', 'message' => $lang));
                }

                $tableArr = array(
                    TABLE_ACTION,
                    TABLE_BLOCK,
                    TABLE_FILE,
                    TABLE_GROUP,
                    TABLE_GROUPPRIV,
                    TABLE_HISTORY,
                    TABLE_IM_CHATUSER,
                    TABLE_IM_CHAT_MESSAGE_INDEX,
                    TABLE_IM_CLIENT,
                    TABLE_IM_CONFERENCE,
                    TABLE_IM_CONFERENCEACTION,
                    TABLE_IM_MESSAGESTATUS,
                    TABLE_IM_MESSAGE_BACKUP,
                    TABLE_IM_QUEUE,
                    TABLE_IM_USERDEVICE,
                    TABLE_LANG,
                );

                foreach($tableArr as $table)
                {
                    $this->dao->delete()->from($table)->exec();
                }

                $this->dao->delete()->from(TABLE_IM_CHAT)->exec();
                $this->loadModel('im')->chatInitSystemChat();
                $tables = $this->loadModel('im')->messageGetAllTables();

                foreach($tables as $table)
                {
                    if($table->tableName == TABLE_IM_MESSAGE) $this->dao->delete()->from($table->tableName)->exec();
                    if($table->tableName != TABLE_IM_MESSAGE) $this->dao->exec('DROP TABLE ' . $table->tableName);
                }
                $this->dao->delete()->from(TABLE_IM_MESSAGE_INDEX)->exec();
                $this->dao->delete()->from(TABLE_CONFIG)
                    ->where('module')->eq('chat')
                    ->andWhere('`key`')->in(array('lastreadid', 'lastreadindex'))
                    ->exec();
                if($_POST['clearType'] == 'all')
                {
                    $this->dao->delete()->from(TABLE_USER)->where('account')->ne($this->app->user->account)->exec();
                    $this->dao->update(TABLE_USER)->set('dept')->eq(0)->where('account')->eq($this->app->user->account)->exec();
                    $this->dao->delete()->from(TABLE_USERGROUP)->exec();
                    $this->dao->delete()->from(TABLE_CATEGORY)->exec();
                }

                unset($_SESSION['clearFileName']);
                $this->send(array('result' => 'success', 'message' => $this->lang->setting->deleteSuccess, 'locate' => inlink('xuanxuan')));
            }
        }

        $os = 'win';
        if(strpos(strtolower(PHP_OS), 'win') !== 0) $os = strtolower(PHP_OS);

        if(isset($this->lang->client->menu))
        {
            $this->lang->setting->menu = $this->lang->client->menu;
            $this->lang->menuGroups->setting = 'client';
        }

        $this->view->title         = $this->lang->setting->param;
        $this->view->type          = $type;
        $this->view->os            = $os . '_' . php_uname('m');
        $this->view->server        = $this->loadModel('im')->getServer();
        $this->view->path          = $this->app->basePath;
        $this->view->clearType     = 'exceptUsers';
        $this->view->clearFileName = $clearFileName;
        $this->display();
    }
}
