<?php

require_once dirname(dirname(__FILE__)) . '/core/ActionBase.class.php';
require_once dirname(dirname(__FILE__)) . '/XmlItemImport.class.php';

class Xoonips_ItemImportAction extends Xoonips_ActionBase {

	protected function doInit(&$request, &$response) {
		// init import
		$this->doImport($request, $response);
		$response->setForward('import_success');
		return true;
	}

	protected function doLog(&$request, &$response) {
		// select order
		$import_id = $request->getParameter('import_id');
		if ($import_id) {
			// import log detail
			$this->doLogdetail($request, $response);
			$response->setForward('logdetail_success');
			return true;
		} else {
			// import log
			$this->doLogInit($request, $response);
			$response->setForward('log_success');
			return true;
		}
	}

	private function doImport(&$request, &$response) {
		// token ticket
		$token_ticket = $this->createToken($this->modulePrefix('do_item_import'));

		// get parameter
		$index_select = $request->getParameter('index_select');

		// breadcrumbs
		$breadcrumbs = array(
			array('name' => _MI_XOONIPS_USER_IMPORT_ITEM)
		);

		// select index
		$index_select_arr = array();
		$is['value'] = 'file';
		$is['label'] = _MD_XOONIPS_ITEM_IMPORT_INDEX_SELECT_MSG2;
		$is['selected'] = ($index_select == 'file' ) ? 'yes' : 'no';
		$index_select_arr[] = $is;
		$is['value'] = 'self';
		$is['label'] = _MD_XOONIPS_ITEM_IMPORT_INDEX_SELECT_MSG1;
		$is['selected'] = ($index_select == 'self' ) ? 'yes' : 'no';
		$index_select_arr[] = $is;

		// index tree
		global $xoopsUser;
		$uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : XOONIPS_UID_GUEST;
		$indexBean = Xoonips_BeanFactory::getBean('IndexBean', $this->dirname, $this->trustDirname);
		$groupIndexes = array();
		$privateIndex = false;
		$publicIndex = $indexBean->getPublicIndex();
		$publicGroupIndexes = $indexBean->getPublicGroupIndex();

		if ($uid != XOONIPS_UID_GUEST) {
			$groupIndexes = $indexBean->getGroupIndex($uid);
			$privateIndex = $indexBean->getPrivateIndex($uid);
		}
		$groupIndexes = $indexBean->mergeIndexes($publicGroupIndexes, $groupIndexes);
		$indexes = array();
		$url = false;
		// public index
		if ($publicIndex) {
			$trees = array();
			$indexes[] = $publicIndex;
			$tree = array();
			$tree['index_id'] = $publicIndex['index_id'];
			$tree['html'] = $indexBean->creatIndexTreeForImport($publicIndex['index_id'], $url, true, $uid);
			$trees[] = $tree;
		}
		// group index
		if ($groupIndexes) {
			foreach ($groupIndexes as $index) {
				$indexes[] = $index;
				$tree = array();
				$tree['index_id'] = $index['index_id'];
				$tree['html'] = $indexBean->creatIndexTreeForImport($index['index_id'], $url, true, $uid);
				$trees[] = $tree;
			}
		}
		// private index
		if ($privateIndex) {
			$privateIndex['title'] = 'Private';
			$indexes[] = $privateIndex;
			$tree = array();
			$tree['index_id'] = $privateIndex['index_id'];
			$tree['html'] = $indexBean->creatIndexTreeForImport($privateIndex['index_id'], $url, true, $uid);
			$trees[] = $tree;
		}

		$viewData['xoops_breadcrumbs'] = $breadcrumbs;
		$viewData['token_ticket'] = $token_ticket;
		$viewData['select_tab'] = 1;
		$viewData['index_select_arr'] = $index_select_arr;
		$viewData['index_self'] = ($index_select == 'self' ) ? true : false;
		$viewData['indexes'] = $indexes;
		$viewData['trees'] = $trees;
		$viewData['dirname'] = $this->dirname;
		$response->setViewData($viewData);
	}

	protected function doImportsave(&$request, &$response) {
		// check token ticket
		if (!$this->validateToken($this->modulePrefix('do_item_import'))) {
			return false;
		}

		// get parameter
		$index_select = $request->getParameter('index_select');

		// user info
		global $xoopsUser;
		$uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : XOONIPS_UID_GUEST;

		// for self index
		if ($index_select == 'self') {
			$indexBean = Xoonips_BeanFactory::getBean('IndexBean', $this->dirname, $this->trustDirname);
			$req_indexes = array();
			$indexes = $indexBean->getIndexAll();
			foreach ($indexes as $index) {
				$index_id = $index['index_id'];
				if ($request->getParameter($this->dirname.'_index_tree_chk_'.$index_id)) {
					$req_indexes[] = $index_id;
				}
			}

			if (count($req_indexes) == 0) {
				$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/itemimport.php';
				$viewData['redirect_msg'] = _AM_XOONIPS_POLICY_ITEMTYPE_IMPORT_FAILURE;
				$response->setViewData($viewData);
				$response->setForward('importsave_success');
				return true;
			}
		}

		$importfile = $request->getFile( 'import_file' );

		if ( empty( $importfile['name'] ) || $importfile['size'] == 0 ) {
			$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/itemimport.php';
			$viewData['redirect_msg'] = _AM_XOONIPS_POLICY_ITEMTYPE_IMPORT_FILE_NONE;
			$response->setViewData($viewData);
			$response->setForward('importsave_success');
			return true;
		}

		// check file exists
		if (!file_exists( $importfile['tmp_name'])) {
			die( "don't exist temporary file '${tmpdir1}'." );
		}

		// create temporary directry
		$tmp = '/var/tmp';
		$time = date("YmdHis");
		$tmpdir1 = "${tmp}/${time}-im1";
		if (!mkdir($tmpdir1, 0755)) {
			die( "can't create directry '${tmpdir1}'." );
		}
		$tmpdir2 = "${tmp}/${time}-im2";
		if (!mkdir($tmpdir2, 0755)) {
			die( "can't create directry '${tmpdir2}'." );
		}

		// transaction
		$err_chk = false;
		$transaction = Xoonips_Transaction::getInstance();
		$transaction->start();

		// unzip
		system("cd $tmpdir2; unzip -q ".$importfile['tmp_name']);

		// Import Log
		$import = array(
		'uid'=>$uid,
		'result'=>0,
		'log'=>"[Import Item] Begin\n",
		'timestamp'=>time(),
		);

		// Import Log
		$import['log'] .= "[Import Item] Zip File : ".$importfile['name']."\n";

		$num = 0;
		$items = array();
		$res_dir = opendir($tmpdir2);
		while (false !== ($itemzip = readdir($res_dir))) {
			if($itemzip == '.' || $itemzip == '..') continue;

			system("cd $tmpdir1; unzip -q ${tmpdir2}/$itemzip");

			$itemid = str_replace('.zip','',$itemzip);
			$items[$itemid] = array(
			'xml'=>'',
			'tmpinfo'=>array(),
			'tmpfiles'=>array(),
			'error'=>'',
			);

			$xmlimport = new XmlItemImport();
			$xmlimport->uid($uid);
			$xmlimport->set_db_lang('UTF-8');

			$num++;
			$res_dir2 = opendir($tmpdir1);
			while (false !== ($file = readdir($res_dir2))) {
				if($file == '.' || $file == '..') continue;

				// temp file
				if (is_dir($file)) {
					$res_dir3 = opendir("${tpmdir1}/$file");
					while (false !== ($tmpfile = readdir($res_dir3))) {
						$items[$itemid]['tmpinfo'][] = array(
						'id'=>$file,
						'name'=>$tmpfile,
						);
						$items[$itemid]['tmpfiles'][$tmpfile] = "${tmpdir1}/${file}/$tmpfile";

						// Import Log
						$import['log'] .= "[Import Item No.${num}] Temp File : ".$tmpfile."\n";
					}
					closedir($res_dir3);
				// xml file
				} else {
					$xml_file = "${tmpdir1}/$file";
					$items[$itemid]['xml'] = $xml_file;

					// Import Log
					$import['log'] .= "[Import Item No.${num}] XML File : ".$file."\n";

					$fp = fopen($xml_file, 'r');
					$tfp = fopen($xml_file.'.tmp', 'aw');
					while ($line = fgets($fp, 4096)) {
						$line_chk = trim($line);

						// omit index tag
						if ($index_select == 'self' &&
						(ereg('^<C:index*', $line_chk) || ereg('^</C:index*', $line_chk))){
							continue;
						}
						fwrite($tfp, $line);

						// Import Log
						$import['log'] .= "$line";
					}
					fclose($fp);
					fclose($tfp);
					unlink($xml_file);
					rename($xml_file.'.tmp', $xml_file);
				}
			}
			closedir($res_dir2);

			// import item
			$xmlimport->set_tmp_file_array($items[$itemid]['tmpfiles']);
			$xmlimport->xml_import_by_file($items[$itemid]['xml']);

			if(strlen($tmpdir1) > 4) system("rm -rf ${tmpdir1}/*");

			$new_id = $xmlimport->get_create_item_id();
			if (!($new_id > 0)) {
				$transaction->rollback();

				$items[$itemid]['error'] = $xmlimport->get_err_code();
				$items[$itemid]['err_line'] = $xmlimport->get_line_no();
				$items[$itemid]['err_msg'] = $xmlimport->get_err_msg();
				$err_chk = true;

				// Import Log
				$import['log'] .= "[Import Item No.${num}] Result : Error (Code : ".$items[$itemid]['error'].")\n";
				$import['log'] .= "[Import Item No.${num}] Result : Error (Message : ".$items[$itemid]['err_msg']." [".$items[$itemid]['err_line']."])\n";

				break;

			// update index item link
			} elseif ($new_id > 0 && $index_select == 'self') {
				$linkBean = Xoonips_BeanFactory::getBean('IndexItemLinkBean', $this->dirname, $this->trustDirname);
				$linkBean->delete($new_id);
				foreach ($req_indexes as $index) {
					$linkBean->insert($index, $new_id, 0);

					// Import Log
					$import['log'] .= "[Import Item No.${num}] Index ID : $index]\n";
				}
			}

			// Import Log
			$import['log'] .= "[Import Item No.${num}] Result : Success (Item ID : $new_id)]\n";
		}
		closedir($res_dir);

		// success
		$transaction->commit();

		// delete temporary
		rmdir( $tmpdir1 );
		system("rm -f $tmpdir2/*");
		rmdir( $tmpdir2 );

		// Import Log
		$import['result'] = ($err_chk) ? 0 : 1 ;
		$import['log'] .= "[Import Item] End";
		$import_id = $this->setLogDB($import, $items);

		if ($err_chk) {
			$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/itemimport.php?op=log&import_id='.$import_id;
			$viewData['redirect_msg'] = _AM_XOONIPS_POLICY_ITEMTYPE_IMPORT_FAILURE;
			$response->setViewData($viewData);
			$response->setForward('importsave_success');
			return true;
		}

		$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/itemimport.php?op=log&import_id='.$import_id;
		$viewData['redirect_msg'] = _AM_XOONIPS_POLICY_ITEMTYPE_IMPORT_SUCCESS;
		$response->setViewData($viewData);
		$response->setForward('importsave_success');
		return true;
	}

	private function doLogInit( &$request, &$response ){
		// breadcrumbs
		$breadcrumbs = array(
			array('name' => _MI_XOONIPS_USER_IMPORT_ITEM)
		);

		// user info
		global $xoopsUser;
		$uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : XOONIPS_UID_GUEST;

		// get item import log
		$logBean = Xoonips_BeanFactory::getBean('ItemImportLogBean', $this->dirname, $this->trustDirname);
		$logs = $logBean->getImportLogByUID($uid);

		foreach ($logs as $key => $log) {
			$logs[$key]['display_time'] = date('Y-m-d H:i:s', $log['timestamp']);

			$items = $logBean->getImportLogItems($log['item_import_log_id']);
			$logs[$key]['items'] = count($items);
		}

		$viewData['xoops_breadcrumbs'] = $breadcrumbs;
		$viewData['select_tab'] = 2;
		$viewData['logs'] = $logs;
		$viewData['dirname'] = $this->dirname;
		$response->setViewData($viewData);
	}

	private function doLogdetail( &$request, &$response ){
		// get parameter
		$import_id = $request->getParameter('import_id');

		// breadcrumbs
		$breadcrumbs = array(
			array(
			    'name' => _MD_XOONIPS_ITEM_IMPORT_LOG_TITLE,
			    'url' => XOOPS_URL.'/modules/'.$this->dirname.'/itemimport.php?op=log'
		  	),
			array(
				'name' => _MD_XOONIPS_ITEM_IMPORT_LOGDETAIL_TITLE
			),
		);

		// get item import log
		$logBean = Xoonips_BeanFactory::getBean('ItemImportLogBean', $this->dirname, $this->trustDirname);
		$import = $logBean->getImportLogInfo($import_id);

		$import['display_time'] = date('Y-m-d H:i:s', $import['timestamp']);

		$items = $logBean->getImportLogItems($import_id);
		$import['items'] = count($items);

		$viewData['xoops_breadcrumbs'] = $breadcrumbs;
		$viewData['select_tab'] = 2;
		$viewData['import'] = $import;
		$viewData['dirname'] = $this->dirname;
		$response->setViewData($viewData);
	}

	private function setLogDB($import, $items){
		$import_id = 0;
		$logBean = Xoonips_BeanFactory::getBean('ItemImportLogBean', $this->dirname, $this->trustDirname);

		$logBean->insert($import);
		$import_id = $logBean->getInsertId();

		if ($import['result'] == 1) {
			foreach ($items as $item_id => $val) {
				$logBean->insertLink($import_id, $item_id);
			}
		}
		return $import_id;
	}

}
?>
