<?php
/*
 * member/upload/Execute.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.'DaoMember.class.php');
require_once( dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoMemberPointHistory.class.php');
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'system'
.DIRECTORY_SEPARATOR.'DataFileWriter.class.php');
class member_upload_Execute extends system_login_ModuleBase {
	function member_upload_Execute(){
		array_push($this->require_module_array,'database2.Connect');
	}
	function execute( & $request ) {
		$dbo						= $request->getAttribute( 'dbo' );
		$sessionHashName			= 'member.upload.columnSelectedArray';
		$sessionInfoName			= 'member.upload.registInformationHash';
		$registInformationHash		= $request->getSession($sessionInfoName);
		$columnSelectedArray		= $request->getSession($sessionHashName);
		$loginUserObject			= $this->getLoginUserObject( $request );

		if( !is_array($columnSelectedArray) && strlen($columnSelectedArray) == 0 ) {
			$request->addLocaledError('system.error.common.session.timeout',SPIDER_LOG_LEVEL_FATAL,array(''));
			$registInformationHash['totalCount']	= -1;
		} else if( !is_array($registInformationHash) ) {
			$request->addLocaledError('system.error.common.session.timeout',SPIDER_LOG_LEVEL_FATAL,array(''));
			$registInformationHash['totalCount']	= -1;
		} else if( strlen($registInformationHash['temporaryUri']) == 0
			|| !system_DataFileWriter::isExists( $request, $registInformationHash['temporaryUri'], DIR_NAME_TMP )
		) {
			$request->addLocaledError('system.error.common.session.timeout',SPIDER_LOG_LEVEL_FATAL,array(''));
			$registInformationHash['totalCount']	= -1;
		} else {
			// 現在のオフセットを確認し登録されていなければ0に設定
			if( preg_match('/^[0-9]+$/', $registInformationHash['offset']) == 0 ) {
				$registInformationHash['offset']			= 0;
				$registInformationHash['writeAtOnce']		= 1;
			}
			// 妥当性検査が完了しているかの確認フラグを設定
			if( $registInformationHash['validated'] !== true ) {
				$registInformationHash['validated']	= false;
			}
			// CSVデータ行の取り出し
			$recordHashArray	= system_DataFileWriter::getCsvRecordHashArray( $request, $columnSelectedArray,
				$registInformationHash['temporaryUri'], DIR_NAME_TMP,
				$registInformationHash['offset'], $registInformationHash['writeAtOnce'], $registInformationHash['ignoreFirstLine'] );
			foreach( $recordHashArray as $num => $columValueHath ) {
				$recordNumber	= $registInformationHash['offset']+$num+1;
				// 指定されている個人情報オブジェクトを生成
				$memberObject		= spider_Controller::createObject('member_DaoMember');
				$tmpHttpRequest		= spider_Controller::createObject('spider_HttpRequest');
				$tmpHttpRequest->setAttribute('dbo',$dbo);
				if( strlen($columValueHath['member_id']) > 0 ) {
					if( $dbo->loadById( $memberObject, $columValueHath['member_id'], true ) ){
					}
					// 更新値を設定
					foreach( $columValueHath as $varName => $value ) {
						if( is_array($memberObject->$varName) ) {
							$memberObject->$varName	= explode(',',$value);
						} else {
							$memberObject->$varName	= $value;
						}
					}
					$memberObject->updated_date	= date('Y-m-d H:i:s');
					if( strlen($memberObject->registered_date) == 0 ) {
						$memberObject->registered_date	= date('Y-m-d H:i:s');
					}
					if( !$request->isError() ) {
						// 実行処理
						if( $registInformationHash['validated'] ) {
							// 妥当性検査が完了してるなら登録処理
							$memberObject->validate( $tmpHttpRequest );
							if( count($tmpHttpRequest->errors) > 0 ) {
								foreach( $tmpHttpRequest->errors as $errorMsg ) {
									$request->addLocaledError('member.error.csv.common',SPIDER_LOG_LEVEL_FATAL,array($recordNumber,$errorMsg));
								}
							} else {
								// パスワードを暗号化するなら登録前に暗号化
								if( $registInformationHash['encodePasswordColumn'] ) {
									$memberObject->login_password	= $memberObject->encodePassword( $request, $memberObject->login_password );
								}
								if( preg_match('/^[0-9]+$/',$memberObject->member_number) > 0 ) {
									// 個人情報更新
									if( $dbo->update($memberObject,false) ) {
										// ポイント履歴記録
										$this->insertPointHistory( $request, $memberObject );
									} else {
										$request->addLocaledError('database2.error.csv.update',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
									}
								} else {
									// 個人情報新規
									if( $dbo->insert($memberObject) ){
										// ポイント履歴記録
										$this->insertPointHistory( $request, $memberObject );
									} else {
										$request->addLocaledError('database2.error.csv.insert',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
									}
								}
							}
						} else {
							// 妥当性検査が完了していないなら妥当性検査のみ
							$memberObject->validate( $tmpHttpRequest );
							if( count($tmpHttpRequest->errors) > 0 ) {
								foreach( $tmpHttpRequest->errors as $errorMsg ) {
									$request->addLocaledError('member.error.csv.common',SPIDER_LOG_LEVEL_FATAL,array($recordNumber,$errorMsg));
								}
							}
						}
					}
				} else {
					$request->addLocaledError('member.error.csv.requireid',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
				}
			}
			// エラーの有無にかかわらずオフセットを進める
			$registInformationHash['offset']++;
			if( $registInformationHash['validated'] ) {
				// 妥当性検査済みの場合
				if( $registInformationHash['offset'] <= $registInformationHash['totalCount'] ) {
					$request->setSession( $sessionInfoName, $registInformationHash );
				} else {
					// 最後のレコードに達しているなら一時ファイルを削除して終了
					system_DataFileWriter::delete( $request, $registInformationHash['temporaryUri'], DIR_NAME_TMP );
					$request->removeSession($sessionHashName);
					$request->removeSession($sessionInfoName);
				}
			} else {
				// 妥当性検査が完了していない場合
				if( $registInformationHash['offset'] <= $registInformationHash['totalCount'] ) {
					// 最後のレコードに達していない場合
					$registInformationHash['validated']	= false;
				} else {
					$registInformationHash['offset']		= 0;
					$registInformationHash['validated']	= true;
				}
				$request->setSession( $sessionInfoName, $registInformationHash );
			}
		}

		$request->setAttribute($sessionHashName, $columnSelectedArray);
		$request->setAttribute($sessionInfoName, $registInformationHash );
	}
	/**
	 * ポイント履歴を記録する
	 */
	function insertPointHistory( & $request, & $memberObject ) {
		$dbo	= $request->getAttribute( 'dbo' );
		if( $memberObject->point != $memberObject->point_org ) {
			// ポイントが更新前の値と異なるならポイント履歴を挿入する
			$pointHistory	= spider_Controller::createObject('member_DaoMemberPointHistory');
			$pointHistory->member_id	= $memberObject->member_id;
			// ポイント増減値は差分
			$pointHistory->action_point	= $memberObject->point - $memberObject->point_org;
			// ポイントラベルと詳細
			$pointHistory->action_label		= 'CSV一括登録';
			$pointHistory->action_detail	= $memberObject->action_detail;
			$pointHistory->modifier_id		= $memberObject->modifier_id;
			$pointHistory->owner_id			= $memberObject->owner_id;
			if( $dbo->insert($pointHistory) ){
			} else {
				$request->addLocaledError('database2.error.insert',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		}
	}
}
?>