<?php

require_once dirname(dirname(dirname(__FILE__))) . '/class/core/ActionBase.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/Enum.class.php';
require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';

class Xoonips_SystemBasicAction extends Xoonips_ActionBase {

	protected function doInit(&$request, &$response) {

		// get configs
		$config_keys = array(
			'moderator_gid' => 'i',
			'upload_dir' => 's',
			'magic_file_path' => 's',
		);
		$config_values = Xoonips_Utils::xoonipsAdminGetConfigs($config_keys, 'e', $this->dirname, $this->trustDirname);

		// >> upload_dir
		$upload_dir = $config_values['upload_dir'];

		// >> magic_file_path
		$magic_file_path = $config_values['magic_file_path'];

		// get common viewdata
		$viewData = $this->setViewData($config_values['moderator_gid'], $upload_dir, $magic_file_path);

		$response->setViewData($viewData);
		$response->setForward('init_success');
		return true;
	}

	private function setViewData($moderator_gid, $upload_dir, $magic_file_path) {
		// title
		$title = _AM_XOONIPS_SYSTEM_BASIC_TITLE;
		$description = _AM_XOONIPS_SYSTEM_BASIC_DESC;

		// breadcrumbs
		$breadcrumbs = array(
			array(
			    'name' => _AM_XOONIPS_TITLE,
			    'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/index.php'
			),
			array(
			    'name' => _AM_XOONIPS_SYSTEM_TITLE,
			    'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/system.php'
			),
			array(
			    'name' => $title,
			    'url' => ''
			)
		);
		
		// >> moderator_gid
		$xmember_handler =& xoops_gethandler( 'member' );
		$grouplist =& $xmember_handler->getGroupList( new Criteria( 'groupid', XOOPS_GROUP_ANONYMOUS, '!=' ) );
		$moderator = array();
		foreach ( $grouplist as $gid => $name ) {
			$selected = ( $gid == $moderator_gid ) ? 'yes' : 'no';
			$moderator[] = array(
		    	'label' => $name,
		    	'value' => $gid,
		    	'selected' => $selected,
			);
		}

		// token ticket		
		$token_ticket = $this->createToken($this->modulePrefix('admin_system_basic'));

		// get common viewdata
		$viewData = array();

		// assign template variables
		$viewData['breadcrumbs'] = $breadcrumbs;
		$viewData['token_ticket'] = $token_ticket;
		$viewData['title'] = $title;
		$viewData['description'] = $description;
		$viewData['dirname'] = $this->dirname;
		
		// >> moderator gid
		$viewData['moderator_gid'] = $moderator;		

		// >> file upload directory
		$viewData['upload_dir'] = $upload_dir;		

		// >> magic file path for fileinfo functions
		$viewData['magic_file_path'] = $magic_file_path;
		return $viewData;
	}

	protected function doUpdate(&$request, &$response) {
		// check token ticket		
		if (!$this->validateToken($this->modulePrefix('admin_system_basic'))) {
			$response->setSystemError('Ticket error');
			return false;
		}
			
		// get requests
		$post_keys = array(
			'moderator_gid' => array('i', false, true),
			'upload_dir' => array('s', false, true),
			'magic_file_path' => array('s', false, true)
		);
		$post_vals = Xoonips_Utils::xoonipsAdminGetRequests('post', $post_keys);

		$errors = new Xoonips_Errors();
		if (!$this->doUploadCheck($post_vals['upload_dir'], $errors)
				|| !$this->doMagicFilePathCheck($post_vals['magic_file_path'], $errors)) {
			$viewData = $this->setViewData($post_vals['moderator_gid'],
					$post_vals['upload_dir'], $post_vals['magic_file_path']);
			$viewData['errors'] = $errors->getView($this->dirname);
		
			$response->setViewData($viewData);
			$response->setForward('init_success');
			return true;
		}

		// set config keys
		$config_keys = array();
		foreach ($post_keys as $key => $attributes) {
			list($data_type, $is_array, $required) = $attributes;
			$config_keys[$key] = $data_type;
		}

		// get old configs
		$config_vals = Xoonips_Utils::xoonipsAdminGetConfigs($config_keys, 'e', $this->dirname, $this->trustDirname);
		if ($post_vals['moderator_gid'] != $config_vals['moderator_gid']) {
			$this->setModuleAdminRight($config_vals['moderator_gid'], $post_vals['moderator_gid']);
		}
		
		// update db values
		foreach ($config_keys as $key => $type) {
			Xoonips_Utils::xoonipsAdminSetConfig($key, $post_vals[$key], $type, $this->dirname, $this->trustDirname);
		}
		
		$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/admin/system_basic.php';
		$viewData['redirect_msg'] = _AM_XOONIPS_MSG_DBUPDATED;
		
		$response->setViewData($viewData);
		$response->setForward('update_success');
		return true;
	}

	private function doUploadCheck($upload_dir, &$errors) {
	    if (!is_dir($upload_dir)) {
	    	$parameters[] = _AM_XOONIPS_SYSTEM_BASIC_UPLOAD_DIR_TITLE;
	    	$errors->addError('_AM_XOONIPS_ERROR_NOT_EXIST', 'upload_dir', $parameters);
	    	return false;
	    } elseif (!is_writable($upload_dir) || !is_readable($upload_dir)
	    		|| (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' && !is_executable($upload_dir))) {
	    	$errors->addError('_AM_XOONIPS_ERROR_UPLOAD_DIRECTORY', 'upload_dir', array());
	    	return false;
		} elseif (!is_dir($upload_dir . '/item')) {
			mkdir($upload_dir . '/item');
		}
		return true;
	}

	private function doMagicFilePathCheck($magic_file_path, &$errors) {
		if (!defined('PHP_VERSION_ID')) {
    		$version = explode('.', PHP_VERSION);
		    define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
		}
		if ($magic_file_path == '') {
			if (PHP_VERSION_ID < 50300) {
				$parameters[] = _AM_XOONIPS_SYSTEM_BASIC_MAGIC_FILE_PATH_TITLE;
				$errors->addError('_MD_XOONIPS_ERROR_REQUIRED', magic_file_path, $parameters);
				return false;
			}
		} elseif (!is_file($magic_file_path)) {
			$parameters[] = _AM_XOONIPS_SYSTEM_BASIC_MAGIC_FILE_PATH_TITLE;
			$errors->addError('_AM_XOONIPS_ERROR_NOT_EXIST', 'magic_file_path', $parameters);
	    	return false;	
		} else {
	      	$finfo = new finfo(FILEINFO_MIME, $magic_file_path);
	      	if (!$finfo) {
				$errors->addError('_AM_XOONIPS_ERROR_MAGIC_FILE_PATH', 'magic_file_path', array());
    	  		return false;
      		}
      		$test_file = XOOPS_ROOT_PATH . '/images/index.html';
	      	$mimetype = preg_replace('/[,; ].*$/', '', $finfo->file($test_file));
	      	if ($mimetype != 'text/html' && $mimetype != 'text/plain') {
				$errors->addError('_AM_XOONIPS_ERROR_MAGIC_FILE_PATH', 'magic_file_path', array());
    	  		return false;
	      	}
		}
		return true;
	}

	private function setModuleAdminRight($oldGid, $newGid) {
		global $xoopsModule;

		$mids[] = $xoopsModule->get('mid');

  		$modulehandler =& xoops_gethandler('module');
		$module =& $modulehandler->getByDirname(XCUBE_CORE_USER_MODULE_NAME);
		$mids[] = $module->get('mid');

		$module =& $modulehandler->getByDirname(Xoonips_Enum::XLEPROGRESS);
		if ($module) {
			$mids[] = $module->get('mid');
		}

		foreach ($mids as $mid) {
			if ($oldGid != 1) {
				$this->setAdminRight(true, $mid, $oldGid, false);
				$this->setAdminRight(false, $mid, $oldGid, false);
			}
			$this->setAdminRight(true, $mid, $newGid, true);
			$this->setAdminRight(false, $mid, $newGid, true);
		}
	}

	private static function setAdminRight($isAdmin, $mid, $gid, $isAdd) {
    	$name = $isAdmin ? 'module_admin' : 'module_read';
    	$criteria = new CriteriaCompo(new Criteria('gperm_name', $name));
    	$criteria->add(new Criteria('gperm_groupid', $gid));
    	$criteria->add(new Criteria('gperm_itemid', $mid));
    	$criteria->add(new Criteria('gperm_modid', 1));
    	$gperm_handler =& xoops_gethandler('groupperm');
    	$gperm_objs =& $gperm_handler->getObjects($criteria);
    	if (count($gperm_objs) > 0) {
      		// already exists
      		$gperm_obj = $gperm_objs[0];
      		if (!$isAdd) {
        		$gperm_handler->delete($gperm_obj);
      		}
    	} else {
      		// not found
      		if ($isAdd) {
        		$gperm_handler->addRight($name, $mid, $gid);
      		}
    	}
		return true;
	}
}

