<?php
/**
 * ownCloud - registration
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Pellaeon Lin <pellaeon@cnmc.tw>
 * @author Julius Härtl <jus@bitgrid.net>
 * @copyright Pellaeon Lin 2015
 */

namespace OCA\Registration\Controller;

use \OCP\IRequest;
use \OCP\AppFramework\Http\TemplateResponse;
use \OCP\AppFramework\Http\DataResponse;
use \OCP\AppFramework\Http;
use \OCP\AppFramework\Controller;
use \OCP\IGroupManager;
use \OCP\IL10N;
use \OCP\IConfig;

class SettingsController extends Controller {

	/** @var IL10N */
	private $l10n;
	/** @var IConfig */
	private $config;
	/** @var IGroupManager */
	private $groupmanager;
	/** @var string */
	protected $appName;

	public function __construct($appName, IRequest $request, IL10N $l10n, IConfig $config, IGroupManager $groupmanager){
		parent::__construct($appName, $request);
		$this->l10n = $l10n;
		$this->config = $config;
		$this->groupmanager = $groupmanager;
		$this->appName = $appName;
	}

	

	/**
	 * @AdminRequired
	 *
	 * @param string $registered_user_group all newly registered user will be put in this group
	 * @param string $allowed_domains Registrations are only allowed for E-Mailadresses with these domains
     * @param bool $admin_approval_required newly registered users have to be validated by an admin
	 * @return DataResponse
	 */
	public function admin($registered_user_group, $allowed_domains, $admin_approval_required,
                $client_id, $secret_id, $appPackage, $authrize_url,$close_userlogin_from) {
		// handle domains
		if ( ( $allowed_domains==='' ) || ( $allowed_domains === NULL ) ){
			$this->config->deleteAppValue($this->appName, 'allowed_domains');
		}else{
			$this->config->setAppValue($this->appName, 'allowed_domains', $allowed_domains);
		}
               $this->config->setAppValue($this->appName, 'client_id', $client_id);
               $this->config->setAppValue($this->appName, 'secret_id', $secret_id);
               $this->config->setAppValue($this->appName, 'appPackage', $appPackage);
               $this->config->setAppValue($this->appName, 'authrize_url', $authrize_url);
               $this->config->setAppValue($this->appName, 'close_userlogin_from', $close_userlogin_from ? "yes" : "no");
		// handle admin validation
		$this->config->setAppValue($this->appName, 'admin_approval_required', $admin_approval_required ? "yes" : "no");
                /*绑定域名*/
                $mac = $this->config->getSystemValue('macnostr');
                if(empty($mac)){
                   $instanceid = $this->config->getSystemValue('instanceid');
                   $mac = md5($instanceid); 
                   $this->config->setSystemValue('macnostr', $mac);
                 
                }
                $nostr = $mac; //md5($instanceid);
                $saveok = false;
                if(!empty($appPackage) &&  !empty($authrize_url)){
                    $preg = "/^http(s)?:\\/\\/.+/";
                    if(!preg_match($preg, $appPackage) || !preg_match($preg, $authrize_url)){
                        return new DataResponse(array(
				'data' => array(
					'message' => (string) $this->l10n->t('Wrong format of web address'),
				),
				'status' => 'error'
			), Http::STATUS_NOT_FOUND);
                    }
                    $urls = parse_url($appPackage);
                    $host = $urls['host'].((!empty($urls['port'])&& $urls['port']!=='80') ? ":".$urls['port'] : "" );
                    //$file = \OC::$SERVERROOT  ."/config/config.php";
                    //include $file;
                    $trusted_domains = $this->config->getSystemValue('trusted_domains');
                    $none = true;
                    foreach($trusted_domains as $key => $domain){
                        if($domain == $host){
                            $none = false && $none;
                        }
                    }
                    if( $none ){ //不重复添加
                        //缓存                  
                       array_push($trusted_domains , $host);
                       $this->config->setSystemValue('trusted_domains', $trusted_domains);
                       $saveok = true;
                    }
                }
		// handle groups
		$groups = $this->groupmanager->search('');
		$group_id_list = array();
		foreach ( $groups as $group ) {
			$group_id_list[] = $group->getGid();
		}
		if ( $registered_user_group === 'none' ) {
			$this->config->deleteAppValue($this->appName, 'registered_user_group');
			return new DataResponse(array(
				'data' => array(
					'message' => (string) $this->l10n->t('Saved'),
				),
				'status' => 'success'
				
			));
		} else if ( in_array($registered_user_group, $group_id_list) ) {
			$this->config->setAppValue($this->appName, 'registered_user_group', $registered_user_group);
			return new DataResponse(array(
				'data' => array(
					'message' => (string) $this->l10n->t('Saved'),
				),
				'status' => 'success'
			));
		} else if( $saveok){
               return new DataResponse(array(
				'data' => array(
                    'data'=> json_decode(['saved'=>'ok'], true),
					'message' => (string) $this->l10n->t('Saved'),
				),
				'status' => 'success'
				
			));
        }    else {
                
			return new DataResponse(array(
				'data' => array(
					'message' => (string) $this->l10n->t('No such group'),
				),
				'status' => 'error'
			), Http::STATUS_NOT_FOUND);
		}
	}
        /**
         *  @AdminRequired
         *  @return DataResponse
         */
        public function domainPanel(){
            $enews = $this->request->getParam('enews');
            $host = $this->request->getParam('domain');
            $localUrl = $this->request->getServerProtocol()."://$host";
            //
            $nostr =  $this->config->getSystemValue('macnostr');
            $authrize_url = $this->config->getAppValue($this->appName, 'authrize_url');
            $ret = null;
            
            if(empty($authrize_url)){
                $authrize_url = 'https://cloud.xfplay.com';
                $this->config->setAppValue($this->appName, 'authrize_url', $authrize_url);                
            }
            /*$authrize_url = 'http://test2020.xfplay.com:82';      */      
            if($enews =='delete'){
                $trusted_domains = $this->config->getSystemValue('trusted_domains');
                if($this->request->getInsecureServerHost() !== $host){
                    foreach($trusted_domains as $key => $domain){
                        if($key>0){ //默认不能删除
                            if($domain == $host){
                                unset($trusted_domains[$key]);
                            }
                        }
                    }  
                    $regmac  = $this->request->getParam('regmac');
                    $yzmcode  = $this->request->getParam('password');
                    $code = $this->config->getAppValue('registration', 'domainCode');
                    if(!empty($regmac) && ($regmac != $nostr)){
                        $nostr = $regmac; /**登记过的删掉，先删除云端的记录 */
                    }
                    $this->config->setSystemValue('trusted_domains', $trusted_domains); 
                    if(!empty($yzmcode) && ($yzmcode == $code)){
                        /*删除云端记录需要验证码*/       
                        $ret = file_get_contents( $authrize_url ."/?do=delLocalUrl&localUrl=$localUrl&nostr=$nostr&yzmcode=$yzmcode");
                    }else{
                        $ret = '{"code":"error'.$code.$yzmcode.'"}';
                    }
                }
                //修改域名
            }else if($enews == 'editDomain'){
                $idx = $this->request->getParam('idx');
                $newdomain = $this->request->getParam('newdomain');
                $regmac = $this->request->getParam('regmac');
                $ret = json_encode(['data'=> $nostr, 'error'=>['errorCode'=>0]]);
                //0号域名不能修改               
                if(($idx>0) && ($newdomain !== $host)){
                    $trusted_domains = $this->config->getSystemValue('trusted_domains');
                    //$file = \OC::$SERVERROOT  ."/config/config.php";
                    //include $file;                    
                    $trusted_domains[$idx] = $newdomain;                
                    $this->config->setSystemValue('trusted_domains', $trusted_domains);
                    /*$text='<?php  $CONFIG = '.var_export($CONFIG,true).';'; 
                    if(false!==fopen($file,'w+')){ 
                      file_put_contents($file,$text); 
                    }*/
                    if(!empty($regmac) && ($regmac !== $nostr)){
                        $nostr = $regmac;
                    }
                    $ret = file_get_contents( $authrize_url ."/?do=delLocalUrl&localUrl=$localUrl&nostr=$nostr");
                }
            }else if($enews =='getCode'){
                            /*解决默认没端口号问题*/
                   $curr = $this->request->getServerProtocol()."://" .$this->request->getInsecureServerHost();
                    $urls = parse_url($curr);
                    $port = ((!empty($urls['port'])&& $urls['port']!=='80') ? ":".$urls['port'] : "" );
                    $urls = parse_url($localUrl);                    
                    $port2 = ((!empty($urls['port'])&& $urls['port']!=='80') ? ":".$urls['port'] : "" );
                    $trusted_domains = $this->config->getSystemValue('trusted_domains');
                    $ok = false;
                    foreach($trusted_domains as $k=>$dm){
                        if($dm == $host){
                            $idx = $k;
                            $ok = true;
                            break;
                        }
                    }
                    /*修复没有端口的域名
                    if(empty($port2) && ($port !== $port2)){ 
                        $host = $urls['host'] ;//.$port;
                        $localUrl = $urls['scheme']."://".$urls['host'] ;//.$port;
                        if($ok){
                            $trusted_domains[$idx] = $host;
                            $this->config->setSystemValue('trusted_domains', $trusted_domains);
                        }
                    }*/
                    /**清除之前的值 */
                $this->config->setAppValue($this->appName, 'domainCode','');
                /*&nostr=$nostr&localUrl=$appPackage&sign=$sign*/
                $ret = file_get_contents( $authrize_url ."/?do=getCode&localUrl=$localUrl");
                
            }else if($enews == 'loaclCode'){
                $code = $this->config->getAppValue($this->appName, 'domainCode');
                if(!empty($code)){
                    $ret  = json_encode( ['data'=> $code ,'error'=>['errorCode'=>0]] );
                }
                
            /**
             * 获取 验证码，/apps/registration/setCode?code=2222   
             * 注册服务器通过 这个接口 存验证码在 应用变量中
             */    
            }else if($enews == 'validateLocalUrl'){
                 
                $ret = file_get_contents( $authrize_url ."/?do=validateLocalUrl&localUrl=$localUrl");
            /**
             * 验证 管理员输入的 验证码是否正确
             */    
            }else if($enews == 'confirm'){
                //应用变量中的验证码
                $code = $this->config->getAppValue('registration', 'domainCode');
                $verify =   $this->request->getParam('password');
                if(($code !== $verify) || empty($code) || empty($verify)){
                        return new DataResponse(array(
                            'data' => array(
                                'message' => (string) $this->l10n->t('No such group'),
                            ),
                            'status' => 'error'
                        ), Http::STATUS_NOT_FOUND);
                }
            /**
             * 激活域名，如果域名已经绑定过，只是mac 不一致，把本地mac值修改为注册服务器的；
             * 如果域名未绑定过，这执行setLocalUrl 操作
             */ 
            }else if($enews =='activeDomain'){ 
                $nostr = $this->config->getSystemValue('macnostr');
                $regmac =  $this->request->getParam('regmac');
                $password  = $this->request->getParam('password'); /*验证码*/
                $idx =  $this->request->getParam('idx');
                if(empty($regmac)){
                    $curr = $this->request->getServerProtocol()."://" .$this->request->getInsecureServerHost();
                    $urls = parse_url($curr);
                    $port = ((!empty($urls['port'])&& $urls['port']!=='80') ? ":".$urls['port'] : "" );
                    $urls = parse_url($localUrl);                    
                    $port2 = ((!empty($urls['port'])&& $urls['port']!=='80') ? ":".$urls['port'] : "" );
                   /* if(empty($port2) && ($port !== $port2)){ //修复端口问题
                        $localUrl = $urls['scheme']."://".$urls['host'].$port;
                    }*/
                    $ret = file_get_contents( $authrize_url ."?do=setLocalUrl&nostr=$nostr&localUrl=$localUrl&sign=$password");
                }else{
                    if($nostr !== $regmac){
                        $this->config->setSystemValue('macnostr', $regmac);
                    }
                    $ret = json_encode(['data'=>$regmac, 'error'=>['errorCode'=>0]] );
                }
                /*设置为默认域名*/
            }else if($enews =='setDefault'){
                 $idx = $this->request->getParam('idx');
                 $password  = $this->request->getParam('password'); /*验证码*/
                 $yzm = $this->config->getAppValue('registration', 'domainCode');
                 if($password === $yzm){
                      $trusted_domains = $this->config->getSystemValue('trusted_domains');
                      $last = array_slice($trusted_domains,1) ;
                      $default = array_shift($trusted_domains) ;                      
                      $last[0] = $host;
                      $last[$idx] = $default;
                      $this->config->setSystemValue('trusted_domains', $last);
                      //修改成功
                      $ret = json_encode(['data'=>$host, 'error'=>['errorCode'=>0]] );
                 }
            }
            
            
            return new DataResponse(array(
                'ret' => json_decode($ret, true),
				'data' => array(
					'message' => (string) $this->l10n->t('Saved'),
                    'localUrl'=> $localUrl,
				),
				'status' => 'success'
			));
        }
       
        /**
	 * @AdminRequired
	 *
	 * @return TemplateResponse
	 */
	public function displayPanel() {
		// handle groups
		$groups = $this->groupmanager->search('');
		$group_id_list = [];
		foreach ( $groups as $group ) {
			$group_id_list[] = $group->getGid();
		}
		$current_value = $this->config->getAppValue($this->appName, 'registered_user_group', 'none');
                
                $this->config->setSystemValue('default_language', 'zh_CN');
		// handle domains
		$allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', '');

		// handle admin validation
		$admin_approval_required = $this->config->getAppValue($this->appName, 'admin_approval_required', "no");

                $client_id = $this->config->getAppValue($this->appName, 'client_id', '');
                $secret_id = $this->config->getAppValue($this->appName, 'secret_id', '');
                $appPackage = $this->config->getAppValue($this->appName, 'appPackage', '');
                $authrize_url = $this->config->getAppValue($this->appName, 'authrize_url', '');
                if(empty($authrize_url)){
                    $authrize_url = 'https://cloud.xfplay.com';
                    $this->config->setAppValue($this->appName, 'authrize_url', $authrize_url );
                }
                $close_userlogin_from = $this->config->getAppValue($this->appName, 'close_userlogin_from', "no");
                $nostr =  $this->config->getSystemValue('macnostr');
                if(empty($nostr)){
                    $nostr = md5( $this->config->getSystemValue('instanceid'));
                    $this->config->setSystemValue('macnostr', $nostr);
                }
                //增加绑定域名信息
                $trusted_domains = $this->config->getSystemValue('trusted_domains');
		return new TemplateResponse('registration', 'admin', [
			'groups' => $group_id_list,
			'current' => $current_value,
			'allowed' => $allowed_domains,
			'approval_required' => $admin_approval_required,
                        'client_id'=> $client_id,
                        'secret_id' => $secret_id,
                        'appPackage' => $appPackage,
                        'trusted_domains'=> $trusted_domains,
                        'authrize_url' => $authrize_url,
                        'nostr' => $nostr,
                    'close_userlogin_from'=>$close_userlogin_from
		], '');
	}
         
}
