<?php
/*
 * member/upload/Confirm.class.php
 * 
 * CopyRight(C) 2010 Shopformer Development Team. All Right Reserved
 * URL: http://sourceforge.jp/projects/shopformer/
 * 
 * 
 * Mail: m_nakashima@users.sourceforge.jp
 * Auther: Masanori Nakashima
 * Last Update: 2010-06-18
 */
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'system'
.DIRECTORY_SEPARATOR.'login'
.DIRECTORY_SEPARATOR.'ModuleBase.class.php');
require_once( dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'PackageConfig.class.php');
require_once( dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoMember.class.php');
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'system'
.DIRECTORY_SEPARATOR.'DataFileWriter.class.php');
class member_upload_Confirm extends system_login_ModuleBase {
	function member_upload_Confirm(){
		array_push($this->require_module_array,'database2.Connect');
	}
	function execute( & $request ) {
		$dbo					= $request->getAttribute( 'dbo' );
		$sessionHashName		= 'member.upload.columnSelectedArray';
		$sessionInfoName		= 'member.upload.registInformationHash';
		$ignoreFirstLine		= $request->getParam('ignore_first_line','post');
		$encodePasswordColumn	= $request->getParam('crypt_password_column','post');
		$columnSelectedArray	= $request->getParam('selected_items','post','array');
		$csvFile				= $_FILES['csvfile'];
		$registInformationHash	= $request->getSession($sessionInfoName);
		
		// 一連の操作でアップロード済みのファイルがある場合は削除
		if( is_array($registInformationHash) && strlen($registInformationHash['temporaryUri']) > 0 ) {
			if( system_DataFileWriter::isExists( $request, $registInformationHash['temporaryUri'], DIR_NAME_TMP ) ) {
				system_DataFileWriter::delete( $request, $registInformationHash['temporaryUri'], DIR_NAME_TMP );
			}
		}
		// 一行目無視フラグの設定
		$registInformationHash	= array();
		if( preg_match('/^[tT](|[rR][uU][eE])|[yY](|[eE][sS])|1$/',$ignoreFirstLine)  > 0 ) {
			$registInformationHash['ignoreFirstLine']	= true;
		} else {
			$registInformationHash['ignoreFirstLine']	= false;
		}
		// パスワード暗号化の有無
		if( preg_match('/^[tT](|[rR][uU][eE])|[yY](|[eE][sS])|1$/',$encodePasswordColumn)  > 0 ) {
			$registInformationHash['encodePasswordColumn']	= true;
		} else {
			$registInformationHash['encodePasswordColumn']	= false;
		}
		// 登録選択カラムの確認
		if( !is_array($columnSelectedArray) && strlen($columnSelectedArray) == 0 ) {
			$request->addLocaledError('system.error.common.csvup.selectcolumn',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else if( !in_array('member_id',$columnSelectedArray) ) {
			$request->addLocaledError('system.error.common.csvup.selectcolumn',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else {
			if( !is_array($columnSelectedArray) ) {
				$str	= $columnSelectedArray;
				$columnSelectedArray	= array();
				array_push($columnSelectedArray,$str);
			}
			foreach( $columnSelectedArray as $orderNumber => $columnName ) {
				if( !array_key_exists($columnName, $GLOBALS['MEMBER_UPLOAD_COLUMN_NAME_DEFINITION']) ) {
				$request->addLocaledError('system.error.common.csvup.columnnotfound',SPIDER_LOG_LEVEL_FATAL,array($orderNumber));
				}
			}
			if( $request->isError() ) {
				$request->removeSession($sessionHashName);
			} else {
				$request->setSession( $sessionHashName, $columnSelectedArray );
			}
		}
		// エラーがないならファイルアップロード
		if( !$request->isError() ) {
			if ( defined('UPLOAD_ERR_INI_SIZE') && UPLOAD_ERR_INI_SIZE == $csvFile['error'] ) {
				$request->addLocaledError('system.error.common.upload.overinisize',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if ( defined('UPLOAD_ERR_FORM_SIZE') && UPLOAD_ERR_FORM_SIZE == $csvFile['error'] ) {
				$request->addLocaledError('system.error.common.upload.overpostsize',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if ( defined('UPLOAD_ERR_PARTIAL') && UPLOAD_ERR_PARTIAL == $csvFile['error'] ) {
				$request->addLocaledError('system.error.common.upload.cruched',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if ( defined('UPLOAD_ERR_NO_FILE') && UPLOAD_ERR_NO_FILE == $csvFile['error'] ) {
				$request->addLocaledError('system.error.common.csvup.requirecsv',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if ( defined('UPLOAD_ERR_NO_TMP_DIR') && UPLOAD_ERR_NO_TMP_DIR == $csvFile['error'] ) {
				$request->addLocaledError('system.error.common.upload.failtotmpsave',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if ( defined('UPLOAD_ERR_OK') && UPLOAD_ERR_OK != $csvFile['error'] ) {
				$request->addLocaledError('system.error.common.upload.failtomove',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if ( !is_uploaded_file($csvFile['tmp_name']) ) {
				$request->addLocaledError('system.error.common.upload.failtomove',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if( preg_match('/\\.[cC][sS][vV]$/',basename($csvFile['name'])) == 0 ) {
				$request->addLocaledError('system.error.common.csvup.requirecsv',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else {
				// アップロードに問題ないなら一時ファイルとして保存
				$registInformationHash['temporaryUri']	= '/member/upload/'.time().'.csv';
				$tmpPath	= DIR_PATH_TMP.DIRECTORY_SEPARATOR.time().'.csv';
				if (move_uploaded_file($csvFile['tmp_name'], $tmpPath)) {
					if( system_DataFileWriter::import( $request, $registInformationHash['temporaryUri'], $tmpPath, DIR_NAME_TMP ) ) {
						// アップロードに成功
						$this->getRecordCount( $request, $registInformationHash );
					}
					if( file_exists($tmpPath) ) {
						@unlink($tmpPath);
					}
				} else {
					$request->addLocaledError('system.error.common.upload.failtomove',SPIDER_LOG_LEVEL_FATAL,array(''));
				}
				if( $request->isError() ) {
					system_DataFileWriter::delete( $request, $registInformationHash['temporaryUri'], DIR_NAME_TMP );
				}
			}
		}
		
		if( $request->isError() ) {
			$request->removeSession($sessionHashName);
			$request->removeSession($sessionInfoName);
		} else {
			$request->setSession( $sessionHashName, $columnSelectedArray );
			$request->setSession( $sessionInfoName, $registInformationHash );
		}
		$request->setAttribute($sessionHashName, $columnSelectedArray);
		$request->setAttribute($sessionInfoName, $registInformationHash );		
	}
	/**
	 * 登録ファイルの行数を確認する
	 */
	function getRecordCount( & $request, & $registInformationHash ) {
		$absolutePath	= system_DataFileWriter::getRealAbsolutePath( $request, $registInformationHash['temporaryUri'], DIR_NAME_TMP );
		$dataRowNumber	= 0;
		$fp				= @fopen($absolutePath,'r');
		if( $fp ) {
			if ( @flock($fp, LOCK_SH)) {
				$dataRowNumber	= 0;
				$dataLine		= '';
				for ( $lineNumber = 1; !feof( $fp ); $lineNumber++ ) {
					$line			= fgets( $fp );
					// 一行目を無視する場合は行を取得してポインタを進めてから評価
					if( $lineNumber == 1 && $registInformationHash['ignoreFirstLine'] ) {
						continue;
					}
					mb_internal_encoding('UTF-8');
					$line		= mb_convert_encoding( $line, 'UTF-8', 'SJIS-win' );
					$dataLine		.= $line;
					$quoteCount	= substr_count( $dataLine, '"' );
					if( $quoteCount % 2 != 0 ) {
						// クォータ数が偶数でない場合は行でデータが完結していないので次の行へ
						continue;
					} else if( strlen(trim($dataLine)) > 0 ) {
						$dataRowNumber++;
						$dataLine	= '';
					}
				}
				// 最後の行があるなら処理する
				if( strlen(trim($dataLine)) > 0 ) {
					$dataRowNumber++;
				}
				@flock( $fp, LOCK_UN );
			}
			@fclose( $fp );
		}
		$registInformationHash['totalCount']	= $dataRowNumber;
		return $dataRowNumber;
	}
}
?>