<?php
/*
 * member/member/Complete.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(__FILE__))
.DIRECTORY_SEPARATOR.'PackageConfig.class.php');
require_once( dirname(__FILE__)
.DIRECTORY_SEPARATOR.'Execute.class.php' );
/**
 * spider : 会員テーブル操作 会員登録完了用アクションモジュールクラス
 * 
 * @package member 会員管理パッケージ
 * @subpackage member 会員テーブル操作パッケージ
 * @version 1.0.0
 * @author  <m_nakashima@users.sourceforge.jp>
 * @since PHP 4.0
 */
class member_member_Complete extends system_login_ModuleBase {
	function member_member_Complete() {
		array_push($this->require_module_array,'database2.Connect');
	}
	function execute( & $request ) {
		// 入力取得
		$dbo				= $request->getAttribute( 'dbo' );
		$memberId			= stripslashes( $_GET['mjmi'] );
		$authKey			= stripslashes( $_GET['mjak'] );
		$memberObject		= spider_Controller::createObject('member_DaoMember');

		if( strlen( $authKey ) == 0 ) {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
			return false;
		}
		
		$tmpUri	= '';
		if( preg_match('/^[nN][eE][wW]$/',$memberId) > 0 ) {
			// 新規登録の場合
			$tmpUri		= '/member/join/'.$authKey.'.tmp';
		} else if( strlen(trim($memberId)) > 0 ) {
			// 更新の可能性がある場合
			$tmpUri		= '/member/modify/'.$authKey.'.tmp';
		} else {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
		}

		if( !$request->isError() ) {
			if( system_DataFileWriter::isExists( $request, $tmpUri, DIR_NAME_TMP ) ) {
				// 存在するなら
				$tmpStrings		= system_DataFileWriter::getContents( $request, $tmpUri, DIR_NAME_TMP );
				$memberObject	= unserialize($tmpStrings);
				if( 'member_daomember' != strtolower(get_class($memberObject)) ) {
					$request->addLocaledError('member.error.join.crusheddata',SPIDER_LOG_LEVEL_FATAL,array(''));
				} else {
					// 正常にオブジェクト復元できたらログイン状態にする
					$memberObject->setLoginUserAgent($_SERVER['HTTP_USER_AGENT']);
					$memberObject->setLoginRemoteAddress($_SERVER['REMOTE_ADDR']);
					$memberObject->setLastLoginDate(date('Y-m-d H:i:s'));
					$memberObject->registLoginHistory( $request, '0' );
					$request->setSession( SYSTEM_SESSION_NAME_LOGIN_INFORMATION, $memberObject, SPIDER_SESSION_SCOPE_GLOBAL );
					$request->setSession( SYSTEM_SESSION_NAME_LOGIN_CLASS_NAME, get_class($memberObject), SPIDER_SESSION_SCOPE_GLOBAL );
					$request->removeSession( SYSTEM_SESSION_NAME_LAST_LOGIN_ERROR_URI, SPIDER_SESSION_SCOPE_GLOBAL );
					$request->setAttribute('system.login.logininformation', $memberObject );
					$isLogin	= true;
					$request->setAttribute('system.login.is_login', $isLogin );
					$loginUserObject	= $this->getLoginUserObject( $request );
					// データベースに登録済みか確認
					$sql	= 'SELECT COUNT(*) FROM '.TABLE_NAME_MEMBER.' WHERE login_id='.$dbo->quote($memberObject->login_id)
						.' AND auth_key='.$dbo->quote( $memberObject->auth_key );
					$result	= $dbo->queryOne( $sql );
					if( $result === false ) {
						$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
					} else if( $result > 0 ) {
						$request->addLocaledError('member.error.join.registeddata',SPIDER_LOG_LEVEL_FATAL,array(''));
					} else {
						if( strlen(trim($memberObject->member_number)) > 0 ) {
							$this->updateMember( $request, $memberObject, $loginUserObject );
						} else {
							member_member_Execute::insertNewMember( $request, $memberObject, $loginUserObject );
						}
					}
				}
			} else {
				$request->addLocaledError('member.error.join.registeddata',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		}

		if( $request->isError() ) {
			return false;
		}
		
		// 通知メール送信判断
		$templateType		= '';
		$deliveryAddress	= '';
		if( strlen(trim($memberObject->member_number_org)) > 0
		&& strlen($memberObject->member_class_org)>0 && $memberObject->member_class_org > 0
		&& strlen($memberObject->status_flag_org)>0 && $memberObject->status_flag_org == 101 ) {
			// 更新の場合
			$templateType	= 'MEMBERMODCMP';
		} else {
			// 新規登録の場合
			$templateType	= 'MEMBERJOINCMP';
		}
		if( $memberObject->changePcMail && strlen($memberObject->pc_mail)>0 ) {
			// パソコンアドレスが変更されて入力されている場合
			$deliveryAddress	= $memberObject->pc_mail;
			$isMobile			= false;
		} if( $memberObject->changeMobileMail && strlen($memberObject->mb_mail)>0 ) {
			// 携帯アドレスが変更されて入力されている場合
			$deliveryAddress	= $memberObject->mb_mail;
			$isMobile			= true;
		} else if( 'default' == $request->agentClass ) {
			// ユーザーエージェントがdefaultの場合はPCアドレスに配信
			$deliveryAddress	= $memberObject->pc_mail;
			$isMobile			= false;
		} else {
			// defaultでない場合は携帯宛てと判断
			$deliveryAddress	= $memberObject->mb_mail;
			$isMobile			= true;
		}
		if(strlen($templateType)>0 && strlen($deliveryAddress)==0) {
			// 自動判断で送信が必要なのにメールアドレスが空の場合設定されている方のアドレスにする
			if( $isMobile ) {
				$deliveryAddress	= $memberObject->pc_mail;
				$isMobile		= false;
			} else {
				$deliveryAddress	= $memberObject->mb_mail;
				$isMobile		= true;
			}
		}

		// 通知メールが必要な場合の処理
		if( strlen($templateType) > 0 && strlen($deliveryAddress) > 0 ) {
			$templateName	= $templateType;
			$mailTemplateObject	= spider_Controller::createObject('member_DaoMemberMailTemplate');
			// ロケール確認
			$isExists	= false;
			$templateId = $templateName.'_'.$request->locale;
			if( $dbo->loadById($mailTemplateObject,$templateId) ){
				$isExists	= true;
			} else if( $dbo->loadById($mailTemplateObject,$templateName) ) {
				$isExists	= true;
			}
			if( $isExists ) {
				$replaceWordHash				= array();
				// パスワードは通知メールに記載しない
				$loginPassword					= $memberObject->login_password;
				$memberObject->login_password	= '設定済みパスワード';
				$replaceWordHash['member']		= $memberObject;
				// 登録完了用URL文字列の作成
				$completeUrl	= '';
				if( $templateType=='MEMBERMODCNF' ) {
					$completeUrl	= dirname(MEMBER_MODIFY_MAIL_URL).'/complete.php?mjmi='.$memberObject->member_id.'&mjak='.$memberObject->auth_key;
				} else if( $templateType=='MEMBERJOINCNF' ) {
					$completeUrl	= dirname(MEMBER_REGIST_MAIL_URL).'/complete.php?mjmi=new&mjak='.$memberObject->auth_key;
				}
				$replaceWordHash['url_complete']	= $completeUrl;
				$replaceWordHash['complete_url']	= $completeUrl;
				// 
				// メール送信実行
				$deliveryStatus	= $mailTemplateObject->sendMail( $request, $deliveryAddress, $replaceWordHash );
				if( 1 != $deliveryStatus ) {
					$request->addLocaledError('member.error.common.sendmail',SPIDER_LOG_LEVEL_FATAL,array($deliveryStatus));
				}
				$memberObject->login_password	= $loginPassword;
			} else {
				$request->addLocaledError('member.error.common.mailnobody',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		}
		// ログインパスワードを暗号化
		if( !$request->isError()
		&& $memberObject->login_password_org != $memberObject->login_password
		&& strlen($memberObject->login_password) > 0 ) {
			$sql	= 'UPDATE '.TABLE_NAME_MEMBER
			.' SET login_password='.$dbo->quote($memberObject->encodePassword( $request, $memberObject->login_password ))
			.' WHERE member_id='.$dbo->quote($memberObject->member_id);
			if($dbo->query($sql)) {
			} else {
				$request->addLocaledError('database2.error.update',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		}
		// 1時間以上経過した一時ファイルを削除する
		member_member_Execute::deleleteTempFiles( $request, 'join' );
		member_member_Execute::deleleteTempFiles( $request, 'modify' );

		// エラーがないならログイン状態にする
		if( !$request->isError() ) {
			// ログインに成功している場合
			$memberObject->setLoginUserAgent($_SERVER['HTTP_USER_AGENT']);
			$memberObject->setLoginRemoteAddress($_SERVER['REMOTE_ADDR']);
			$memberObject->setLastLoginDate(date('Y-m-d H:i:s'));
			$memberObject->registLoginHistory( $request, '0' );
			// 情報をログイン情報をセッションに登録
			$request->setSession( SYSTEM_SESSION_NAME_LOGIN_INFORMATION, $memberObject, SPIDER_SESSION_SCOPE_GLOBAL );
			$request->setSession( SYSTEM_SESSION_NAME_LOGIN_CLASS_NAME, get_class($memberObject), SPIDER_SESSION_SCOPE_GLOBAL );
			$request->removeSession( SYSTEM_SESSION_NAME_LAST_LOGIN_ERROR_URI, SPIDER_SESSION_SCOPE_GLOBAL );
			$request->setAttribute('system.login.logininformation', $memberObject );
			$isLogin	= true;
			$request->setAttribute('system.login.is_login', $isLogin );
		}
		$request->setAttribute('member.member.memberObject',$memberObject);
	}
	/**
	 * 会員情報を更新する
	 */
	function updateMember( & $request, & $memberObject, & $loginUserObject ) {
		$dbo	= $request->getAttribute( 'dbo' );
		if( $memberObject->canEditData( $request, $loginUserObject ) ) {
			if( $this->lockData( $request, $memberObject ) ) {
				// 編集ロックを再取得できたら更新
				$memberObject->updated_date	= date('Y-m-d H:i:s');
				$errors	= array();
				if( $dbo->update($memberObject,true) ) {
					// パッケージコネクタの追加更新処理をおこなう
					if( is_array($GLOBALS['member.existsConnectorHash'] ) ) {
						foreach( $GLOBALS['member.existsConnectorHash'] as $packageId => $connectorObject ) {
							$connectorObject->additionalPostUpdateProcess( $request, $memberObject );
						}
					}
				} else {
					$request->addLocaledError('database2.error.update',SPIDER_LOG_LEVEL_FATAL,array(""));
				}
				$this->unlockData( $request, $memberObject );
			} else {
				$request->addLocaledError('system.error.common.data.locked',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		} else {
			$request->addLocaledError('system.error.login.user.noauthexec',SPIDER_LOG_LEVEL_FATAL,array(''));
		}
		if ( $request->isError() ) {
			return false;
		} else {
			return true;
		}
	}
}
?>