<?php
/*
 * member/download/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.'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');
if( file_exists(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'admin'
.DIRECTORY_SEPARATOR.'DaoAdminMember.class.php') ) {
	require_once( dirname(dirname(dirname(__FILE__)))
	.DIRECTORY_SEPARATOR.'admin'
	.DIRECTORY_SEPARATOR.'DaoAdminMember.class.php');
}
class member_download_Execute extends system_login_ModuleBase {
	function member_download_Execute(){
		array_push($this->require_module_array,'database2.Connect');
	}
	function execute( & $request ) {
		// 変数取得
		$dbo						= $request->getAttribute( 'dbo' );
		$member_class				= stripslashes( $_GET['mc'] );
		$select_type				= trim(stripslashes( $_GET['stype'] ));
		$session_name_csv_column	= MEMBER_SESSION_NAME_DOWNLOAD_CSV_COLUMN_DEFINITION . $member_class;
		if( 'q' != $select_type && 's' != $select_type ) {
			$select_type		= 'q';
		}
		// 一度に書き込む数を固定
		$write_at_once	= MEMBER_DOWNLOAD_WORK_AT_ONCE;

		// カラム定義
		$download_column_definition			= $GLOBALS['MEMBER_UPLOAD_COLUMN_DEFINITION'];
		$download_column_name_definition	= $GLOBALS['MEMBER_UPLOAD_COLUMN_NAME_DEFINITION'];
		// 指定されたカラム定義を取得
		$column_definition	= $request->getSession($session_name_csv_column);
		if( !is_array($column_definition) ) {
			$column_definition	= $download_column_definition;
		}
		// ダウンロードカラムを確認する
		$require_column_count	= 0;
		$not_has_required		= false;
		$has_not_numeric		= false;
		$item_key_array = array();
		foreach( $download_column_definition as $item_key => $order_number ) {
			$number = $request->getParam($item_key,'post');
			if( strlen(trim($number)) > 0 ) {
				if( is_numeric( $number ) && preg_match('/^[0-9]+$/', $number ) > 0 ) {
					$column_definition[$item_key]	= $number;
					if( $number > $require_column_count ) {
						$require_column_count	= $number;
					}
				} else {
					if( !$has_not_numeric ) {
						$request->addLocaledError('member.error.common.invalidorder',SPIDER_LOG_LEVEL_FATAL,array());
						$has_not_numeric	= true;
					}
				}
			}
		}
		if ( count($column_definition)==0 ) {
			$request->addLocaledError('system.error.common.csvdl.selectcolumn',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else {
			asort( $column_definition );
			$request->setSession( $session_name_csv_column, $column_definition );
		}
		
		// 現在のオフセットを確認し登録されていなければ0に設定
		$offset			= $request->getSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_OFFSET);
		if( preg_match('/^[0-9]+$/', $offset) == 0 ) {
			$offset		= 0;
		}

		// 取得データの情報を得る
		$total_count		= 0;
		$member_id_array	= array();
		// 検索結果全件ダウンロード
		if( 'q' == $select_type ) {
			$load_count_query	= $request->getSession(MEMBER_SESSION_NAME_LOADCOUNT_QUERY);
			$load_list_query	= $request->getSession(MEMBER_SESSION_NAME_LOADLIST_QUERY);
		} else if( 's' == $select_type ) {
			$sessionSelectedHash			= $request->getSession( MEMBER_SESSION_NAME_SELECTED_LIST );
			if( !is_array($sessionSelectedHash) ) {
				$sessionSelectedHash		= array();
			}
			$query_condition	= " WHERE member_id IN ('" . implode( "','", array_keys($sessionSelectedHash) ) . "')";
			$load_count_query	= "SELECT COUNT(DISTINCT(member_id)) FROM " . TABLE_NAME_MEMBER . $query_condition;
			$load_list_query	= "SELECT DISTINCT(member_id) FROM " . TABLE_NAME_MEMBER . $query_condition;
		}
		if( strlen(trim($load_count_query)) == 0 || strlen(trim($load_count_query)) == 0 ) {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else {
			$total_count	= $dbo->queryOne($load_count_query);
			if ( $total_count === false ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($load_count_query));
			} else {
				$dbo->setLimit( $write_at_once, $offset );
				$result			= $dbo->queryAll( $load_list_query,null,'hash' );
				if ( $result === false ) {
					$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($load_list_query));
				} else {
					foreach( $result as $row ) {
						$member_id	= trim($row['member_id']);
						array_push( $member_id_array, $member_id );
					}
				}
			}
		}
		// 一時ファイルパスの作成
		$downloadUri		= '';
		$download_file_path = '';
		if( !$request->isError() ) {
			// CSVファイルパス
			$downloadUri			= $request->getSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_FILE_URI);
			if( strlen($downloadUri) > 0 ) { 
				$download_file_path		= system_DataFileWriter::getRealAbsolutePath( $request, $downloadUri, DIR_NAME_TMP );
				if( strlen($download_file_path) <= strlen(MEMBER_DIR_PATH_DOWNLOAD_CSV_TMP) ) {
					$request->addLocaledError('member.error.csv.download.failtotempfile',SPIDER_LOG_LEVEL_FATAL,array());
				} else {
					// 問題ないファイルパスが登録されている
				}
			} else {
				// ファイルパスが生成されていないので作成
				$downloadUri	= '/member.download.csv/MEMBER_CSV_'.date('YmdHi').session_id().'.csv';
				$request->setSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_FILE_URI,$downloadUri);
			}
		}
		if( !$request->isError() ) {
			// エラーがなければファイルへの書き込み開始
			$fp		= new system_DataFileWriter();
			if( $fp->open( $request, $downloadUri, 'a+', DIR_NAME_TMP ) ) {
				if( 0 == $offset ) {
					// オフセットが0の場合カラム名を一行目に出力する
					$column_name_array = array();
					foreach ( $column_definition as $key=>$val ) {
						$column_name	= '"'.str_replace('"','""'
							,$GLOBALS['MEMBER_UPLOAD_COLUMN_NAME_DEFINITION'][$key]).'"';
						array_push($column_name_array,$column_name);
					}
					// カラム名の書き込み
					$values_string	= implode( ',', $column_name_array );
					$values_string 	= mb_convert_encoding( $values_string, 'SJIS-win', 'UTF-8' );
					$csv_data	= $values_string . "\n";
					$fp->write( $csv_data );
				}
				// 個人情報データの読み込み
				$i	= 0;
				foreach( $member_id_array as $member_id ) {
					$member_object	= spider_Controller::createObject('member_DaoMember');
					if( $dbo->loadById( $member_object, $member_id ) ) {
						// 読み込みに問題なければCSV行を作成して書き込み
						$csv_data	= $member_object->getCsvString($column_definition);
						$csv_data	= mb_convert_encoding( $csv_data, 'SJIS-win', 'UTF-8' );
						$fp->write( $csv_data );
					} else {
						$num	= $offset + $i;
						$request->addLocaledError('member.error.csv.download.failtoreadmemberline',SPIDER_LOG_LEVEL_FATAL,array($num,$member_id));
					}
					$i++;
				}
				$fp->close( $request );
				// 書き込み処理完了後、ファイルのパスを取得
				$download_file_path		= system_DataFileWriter::getRealAbsolutePath( $request, $downloadUri, DIR_NAME_TMP );
			} else {
				$request->addLocaledError('member.error.csv.download.failtotempfile',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		}
		// CSV書き込み処理後にエラーを確認
		if( $request->isError() ) {
			// エラーが発生したら処理を中断してセッション等を削除
			$request->removeSession($session_name_csv_column);
			$request->removeSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_OFFSET);
		} else {
			// エラーがないならオフセットを進める
			$offset	+= $write_at_once;
			if( $offset >= $total_count ) {
				// 総数より進んだら処理完了してダウンロード
				$request->removeSession($session_name_csv_column);
				$request->removeSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_OFFSET);
				$download_file_name = 'personal_' . date('YmdHi') . '.csv';					
//				$request->setResponseHeader( 'Content-Type', 'application/octet-stream; charset="Shift_JIS"' );
				$request->setResponseHeader( 'Content-Type', 'application/comma-separated-values; charset="Shift_JIS"' );
				$request->setResponseHeader( 'Content-Disposition', 'attachment; filename="' . $download_file_name . '"' );
				// 2009-05-18 IEでのダウンロードができないため追加
				$request->setResponseHeader( 'Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0' );
				$request->setResponseHeader( 'Pragma', '' );
				$request->setResponseHeader( 'Expires', '0' );
				$request->setResponseFile( $download_file_path );
			} else {
				// 総数より少ないならオフセットを更新して作成処理を続行 
				$request->setSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_OFFSET,$offset);
			}
		}
		$request->setAttribute('member.download.write_at_once', $write_at_once );
		$request->setAttribute('member.download.offset', $offset );
		$request->setAttribute('member.download.total_count', $total_count );
		$request->setAttribute('member.download.select_type', $select_type );
		$request->setAttribute(MEMBER_SESSION_NAME_DOWNLOAD_CSV_COLUMN_DEFINITION, $column_definition );
	}
	/**
	 * モジュールの後処理を行います。
	 * このメソッドをオーバーライドすることにより、モジュールの後処理として実行されます。
	 * @param $request 
	 */
	function post_process( & $request ) {
		$offset	= $request->getSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_OFFSET);
		if( preg_match('/^[0-9]+$/', $offset) == 0 ) {
			// オフセットが設定されていないなら一時ファイルを削除
			$downloadUri	= $request->getSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_FILE_URI);
			if ( strlen( $downloadUri ) > 0 ) {
				if ( system_DataFileWriter::delete( $request, $downloadUri, DIR_NAME_TMP ) ) {
				}
			}
			$request->removeSession(MEMBER_SESSION_NAME_DOWNLOAD_CSV_FILE_URI);
		}
	}
}
?>