<?php
/*
 * shopping/product/unit/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.'PackageConfig.class.php');
class shopping_product_upload_Execute extends system_login_ModuleBase {
	function shopping_product_upload_Execute(){
	}
	function execute( & $request ) {
		$dbo						= $request->getAttribute( 'dbo' );
		$sessionHashName			= 'shopping.product.upload.columnSelectedArray';
		$sessionInfoName			= 'shopping.product.upload.registInformationHash';
		$sessionLastProductId	= 'shopping.product.upload.lastProductId';
		$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_ERROR,array());
			$registInformationHash['totalCount']	= -1;
		} else if( !is_array($registInformationHash) ) {
			$request->addLocaledError('system.error.common.session.timeout',SPIDER_LOG_LEVEL_ERROR,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_ERROR,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;
			}
			// 処理分岐
			$recordArray	= $this->getNextRecordArray( $request, $registInformationHash );
			foreach( $recordArray as $num => $recordLine ) {
				if( strlen($recordLine) > 0 ) {
					$recordNumber	= $registInformationHash['offset']+$num+1;
					$columValueHath	= $this->getColumnValueHash( $request, $recordLine, $columnSelectedArray );
					// 指定されている商品オブジェクトを生成
					$shoppingProductObject		= spider_Controller::createObject('shopping_DaoShoppingProduct');
					$shoppingProductUnitObject	= null;
					$tmpHttpRequest				= spider_Controller::createObject('spider_HttpRequest');
					$tmpHttpRequest->setAttribute('dbo',$dbo);
					if( strlen($columValueHath['product_id']) > 0 ) {
						if( $dbo->loadById( $shoppingProductObject, $columValueHath['product_id'], true ) ){
						} else if( $columValueHath['status_flag'] >= 200 ){
							continue;
						}
						// 更新値を設定
						$includeUnitInformation	= false;
						foreach( $columValueHath as $varName => $value ) {
							if( 'unit_string' == $varName || preg_match( '/^unit\\_/', $varName ) == 0 ) {
								if( is_array($shoppingProductObject->$varName) ) {
									$shoppingProductObject->$varName	= explode(',',$value);
								} else {
									$shoppingProductObject->$varName	= $value;
								}
							} else {
								$includeUnitInformation	= true;
							}
						}
						// 閲覧権限
						if ( strlen($shoppingProductObject->member_viewable)>0 ) {
							$valArray		= explode('/',$shoppingProductObject->member_viewable);
							$memberClassArray	= array();
							foreach($valArray as $key => $val ){
								if( preg_match('/^[0-9]{1,3}$/',$val) == 0
								&& is_array($GLOBALS['MEMBER_MEMBER_CLASS_HASH']) ){
									foreach( $GLOBALS['MEMBER_MEMBER_CLASS_HASH'] as $k => $v ){
										if( $val == $v ){
											array_push($memberClassArray,$k);
											break;
										}
									}
								}else if( preg_match('/^[0-9]{1,3}$/',$val) > 0){
									array_push($memberClassArray,$val);
								}
							}
							$shoppingProductObject->memberViewableArray	= $memberClassArray;
						}
						// 更新権限
						if ( strlen($shoppingProductObject->member_purchasable)>0 ) {
							$valArray		= explode('/',$shoppingProductObject->member_purchasable);
							$memberClassArray	= array();
							foreach($valArray as $key => $val ){
								if( preg_match('/^[0-9]{1,3}$/',$val) == 0
								&& is_array($GLOBALS['MEMBER_MEMBER_CLASS_HASH']) ){
									foreach( $GLOBALS['MEMBER_MEMBER_CLASS_HASH'] as $k => $v ){
										if( $val == $v ){
											array_push($memberClassArray,$k);
											break;
										}
									}
								}else if( preg_match('/^[0-9]{1,3}$/',$val) > 0){
									array_push($memberClassArray,$val);
								}
							}
							$shoppingProductObject->memberPurchasableArray	= $memberClassArray;
						}
						// カテゴリのチェック
						$newCategoryIdArray	= array();
						foreach( $shoppingProductObject->categoryIdArray as $categoryId ) {
							$categoryObject	= spider_Controller::createObject('shopping_DaoShoppingCategory');
							if( $dbo->loadById($categoryObject,$categoryId,false) ) {
								// カテゴリが存在するならOK
								array_push($newCategoryIdArray,$categoryId);
							} else if( strlen($categoryId) > 0 && preg_match('/^[0-9a-zA-Z]+$/', $shoppingCategoryObject->category_id) == 0 ) {
								// 存在しないで指定カテゴリIDの書式が文言である場合はカテゴリ自動作成
								if( $categoryId = $this->getCategoryIdByName( $request, $categoryId ) ) {
									array_push($newCategoryIdArray,$categoryId);
								}
							} else {
								// カテゴリIDが存在しない場合はカテゴリ登録をしない
							}
						}
						$shoppingProductObject->categoryIdArray	= $newCategoryIdArray;
						// 更新日
						$shoppingProductObject->updated_date	= date('Y-m-d H:i:s');
						if( strlen($shoppingProductObject->registered_date) == 0 ) {
							$shoppingProductObject->registered_date	= date('Y-m-d H:i:s');
						}
						if( $includeUnitInformation ) {
							// 販売単位情報を含むなら
							$shoppingProductUnitObject	= spider_Controller::createObject('shopping_DaoShoppingProductUnit');
							if( strlen($columValueHath['unit_unit_id']) > 0 ) {
								if( $dbo->loadById( $shoppingProductUnitObject, $columValueHath['unit_unit_id'], true ) ){
								}
								// 更新値を設定
								foreach( $columValueHath as $varName => $value ) {
									if( preg_match( '/^unit\\_/', $varName ) > 0 ) {
										$varName	= preg_replace('/^unit\\_/','',$varName);
										if( is_array($shoppingProductObject->$varName) ) {
											$shoppingProductUnitObject->$varName	= explode(',',$value);
										} else {
											$shoppingProductUnitObject->$varName	= $value;
										}
									}
								}
								$shoppingProductUnitObject->product_id	= $shoppingProductObject->product_id;
								// 閲覧権限
								if ( strlen($shoppingProductUnitObject->member_viewable)>0 ) {
									$shoppingProductUnitObject->memberViewableArray		= explode('/',$shoppingProductUnitObject->member_viewable);
								}
								// 購入権限
								if ( strlen($shoppingProductUnitObject->member_purchasable)>0 ) {
									$shoppingProductUnitObject->memberPurchasableArray	= explode('/',$shoppingProductUnitObject->member_purchasable);
								}
								$shoppingProductUnitObject->updated_date	= date('Y-m-d H:i:s');
								if( strlen($shoppingProductUnitObject->registered_date) == 0 ) {
									$shoppingProductUnitObject->registered_date	= date('Y-m-d H:i:s');
								}
							} else {
								$request->addLocaledError('shopping.error.csv.line.requireunitid',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
							}
						}
						if( !$request->isError() ) {
							// 実行処理
							if( $registInformationHash['validated'] ) {
								// 妥当性検査が完了してるなら登録処理
								$shoppingProductObject->validate( $tmpHttpRequest );
								if( !is_null($shoppingProductUnitObject) ) {
									$shoppingProductUnitObject->validate( $tmpHttpRequest );
								}
								if( count($tmpHttpRequest->errors) > 0 ) {
									foreach( $tmpHttpRequest->errors as $errorMsg ) {
										$request->addLocaledError('shopping.error.csv.line.free',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
									}
								} else {
									if( preg_match('/^[0-9]+$/',$shoppingProductObject->product_number) > 0 ) {
										// 更新の場合
										// 画像ファイル登録
										$lastProductId	= $request->getSession($sessionLastProductId);
										if( $lastProductId != trim( $shoppingProductObject->product_id) ){
											if( $shoppingProductObject->importImageFiles( $request, $loginUserObject, $registInformationHash['importImagesUri'], $registInformationHash['importImages'] ) ) {
												$shoppingProductObject->updated_date	= date('Y-m-d H:i:s');
											}
										}
										if( strlen($shoppingProductObject->owner_id)==0 ) {
											// 登録者IDが指定されていない場合、登録済みの登録者IDを設定
											$shoppingProductObject->owner_id	= $shoppingProductObject->owner_id_org;
										}
										// 商品更新
										if( $dbo->update($shoppingProductObject,false) ) {
											// 最終実行商品IDをセッション保存
											$request->setSession($sessionLastProductId,$shoppingProductObject->product_id);
											// 販売単位の保存
											if( !is_null($shoppingProductUnitObject) && $shoppingProductObject->status_flag < 200 ) {
												$this->saveProductUnit( $request, $recordNumber, $shoppingProductUnitObject, $registInformationHash );
											}
										} else {
											$request->addLocaledError('shopping.error.csv.line.update',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
										}
									} else {
										if( strlen($shoppingProductObject->owner_id)==0 && $this->isLogin( $request ) ) {
											// 登録者IDが未設定、且つログインしているなら編集ユーザーのユニークIDを設定
											$shoppingProductObject->owner_id	= $loginUserObject->getUniqueId();
										}
										// 商品新規
										if( $dbo->insert($shoppingProductObject) ){
											// 画像ファイル登録
											if( $dbo->loadById( $shoppingProductObject, $shoppingProductObject->product_id, true ) ) {
												if( $shoppingProductObject->importImageFiles( $request, $loginUserObject, $registInformationHash['importImagesUri'], $registInformationHash['importImages'] ) ) {
													// 最終実行商品IDをセッション保存
													$request->setSession($sessionLastProductId,$shoppingProductObject->product_id);
												}
											}
											if( !is_null($shoppingProductUnitObject) ) {
												$this->saveProductUnit( $request, $recordNumber, $shoppingProductUnitObject, $registInformationHash );
											}
										} else {
											$request->addLocaledError('shopping.error.csv.line.insert',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
										}
									}
								}
							} else {
								// 妥当性検査が完了していないなら妥当性検査のみ
								$shoppingProductObject->validate( $tmpHttpRequest );
								if( !is_null($shoppingProductUnitObject) ) {
									$shoppingProductUnitObject->validate( $tmpHttpRequest );
								}
								if( count($tmpHttpRequest->errors) > 0 ) {
									foreach( $tmpHttpRequest->errors as $errorMsg ) {
											$request->addLocaledError('shopping.error.csv.line.free',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
									}
								}
							}
						}
					} else {
						$request->addLocaledError('shopping.error.csv.line.requireproduct',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);
					$request->removeSession($sessionLastProductId);
				}
			} 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 getNextRecordArray( & $request, $registInformationHash ) {
		$absolutePath	= system_DataFileWriter::getRealAbsolutePath( $request, $registInformationHash['temporaryUri'], DIR_NAME_TMP );
		$recordArray	= array();
		$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++;
						// 行データが完結してオフセット処理範囲内なら処理
						if( $dataRowNumber > $registInformationHash['offset']
							&& $dataRowNumber < $registInformationHash['offset'] + $registInformationHash['writeAtOnce'] ) {
							array_push( $recordArray, trim($dataLine) );
							$dataLine	= '';
						} else if ( $dataRowNumber >= $registInformationHash['offset'] + $registInformationHash['writeAtOnce'] ) {
							break;
						} else {
							$dataLine	= '';
						}
					}
				}
				// 最後の行があるなら処理する
				if( strlen(trim($dataLine)) > 0 ) {
					array_push( $recordArray, trim($dataLine) );
					$dataLine	= '';
				}
				@flock( $fp, LOCK_UN );
			}
			@fclose( $fp );
		}
		return $recordArray;
	}
	/**
	 * カラム名=>値のハッシュに整理
	 */
	function getColumnValueHash( & $request, $recordLine, $columnSelectedArray ) {
		// カラム名=>値のハッシュに整理
		$columnValues		= util_CharUtility::csv2Array( $recordLine );
		$columnValueHash	= array();
		foreach( $columnSelectedArray as $number => $varName ) {
			$columnValueHash[$varName]	= $columnValues[$number];
		}
		return $columnValueHash;
	}
	/**
	 * 
	 */
	function saveProductUnit( & $request, $recordNumber, $shoppingProductUnitObject, $registInformationHash ) {
		$dbo				= $request->getAttribute( 'dbo' );
		$loginUserObject	= $this->getLoginUserObject( $request );
		if( !is_null($shoppingProductUnitObject) ) {
			if( preg_match('/^[0-9]+$/',$shoppingProductUnitObject->unit_number) > 0 ) {
				// 画像ファイル登録
				if( $registInformationHash['importImages'] ) {
					if( $shoppingProductUnitObject->importImageFiles( $request, $loginUserObject, $registInformationHash['importImagesUri'] ) ) {
						$shoppingProductUnitObject->updated_date	= date('Y-m-d H:i:s');
					}
				}
				// ダウンロードファイル登録
				if( $shoppingProductUnitObject->delivery_type == '11' && $registInformationHash['importDownloadFiles'] ) {
					if( $shoppingProductUnitObject->importDownloadFiles( $request, $loginUserObject, $registInformationHash['importDownloadFilesUri'] ) ) {
						$shoppingProductUnitObject->updated_date	= date('Y-m-d H:i:s');
					}
				}
				if( strlen($shoppingProductUnitObject->owner_id)==0 ) {
					// 登録者IDが指定されていない場合、登録済みの登録者IDを設定
					$shoppingProductUnitObject->owner_id	= $shoppingProductUnitObject->owner_id_org;
				}
				if( $dbo->update($shoppingProductUnitObject,false) ) {
				} else {
					$request->addLocaledError('shopping.error.csv.line.updateunit',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
				}
			} else {
				// 画像ファイル登録
				if( $registInformationHash['importImages'] ) {
					if( $dbo->loadById( $shoppingProductUnitObject, $shoppingProductUnitObject->unit_id, true ) ) {
						if( $shoppingProductUnitObject->importImageFiles( $request, $loginUserObject, $registInformationHash['importImagesUri'] ) ) {
							$shoppingProductUnitObject->updated_date	= date('Y-m-d H:i:s');
						}
					}
				}
				// ダウンロードファイル登録
				if( $registInformationHash['importDownloadFiles'] ) {
					if( $dbo->loadById( $shoppingProductUnitObject, $shoppingProductUnitObject->unit_id, true )
					&& $shoppingProductUnitObject->delivery_type == '11' ) {
						if( $shoppingProductUnitObject->importDownloadFiles( $request, $loginUserObject, $registInformationHash['importDownloadFilesUri'] ) ) {
							$shoppingProductUnitObject->updated_date	= date('Y-m-d H:i:s');
						}
					}
				}
				if( strlen($shoppingProductUnitObject->owner_id)==0 && $this->isLogin( $request ) ) {
					// 登録者IDが未設定、且つログインしているなら編集ユーザーのユニークIDを設定
					$shoppingProductUnitObject->owner_id	= $loginUserObject->getUniqueId();
				}
				if( $dbo->insert($shoppingProductUnitObject) ){
				} else {
					$request->addLocaledError('shopping.error.csv.line.insertunit',SPIDER_LOG_LEVEL_FATAL,array($recordNumber));
				}
			}
		}
		if( $request->isError() ) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 名前入力の場合のカテゴリからカテゴリIDを戻します。カテゴリが存在しなかった場合は作成します
	 */
	function getCategoryIdByName( & $request, $categoryNameString ) {
		$dbo	= $request->getAttribute('dbo');
		$loginUserObject	= $this->getLoginUserObject( $request );
		$categoryNameArray	= explode(' - ',$categoryNameString);
		$lastCategoryId		= null;
		foreach( $categoryNameArray as $categoryName ) {
			if( strlen( $categoryName ) > 0 ) {
				$sql	= 'SELECT category_id FROM '.TABLE_NAME_SHOPPING_CATEGORY
				.' WHERE category_name='.$dbo->quote($categoryName);
				if( !is_null($lastCategoryId) && strlen($lastCategoryId) > 0 ){
					$sql	.= ' AND parent_id='.$dbo->quote($lastCategoryId);
				} else {
					$sql	.= ' AND ( parent_id IS NULL OR parent_id='.$dbo->quote('').' )';
				}
				$categoryId = $dbo->queryOne( $sql );
				if( strlen($categoryId) > 0 ) {
					// カテゴリが見つかった
					$lastCategoryId	= $categoryId;
				} else {
					// カテゴリが見つからなかったら最後に見つかったカテゴリを親にして作成
					$categoryObject	= spider_Controller::createObject('shopping_DaoShoppingCategory');
					$categoryObject->category_id		= null;
					$categoryObject->parent_id			= $lastCategoryId;
					$categoryObject->category_name		= $categoryName;
					$categoryObject->updated_date		= date('Y-m-d H:i:s');
					$categoryObject->registered_date	= date('Y-m-d H:i:s');
					$categoryObject->wner_id			= $loginUserObject->getUniqueId();
					$categoryObject->modifier_id		= $loginUserObject->getUniqueId();
					if( $dbo->setNextId( $categoryObject, 'SCHCA{num:5}' ) ) {
						if( $dbo->insert($categoryObject) ){
							$lastCategoryId	= $categoryObject->category_id;
						} else {
							$request->addLocaledError('shopping.error.csv.failtomakecat',SPIDER_LOG_LEVEL_FATAL,array($categoryName));
							return false;
						}
					} else {
						$request->addLocaledError('shopping.error.csv.failtomakecatid',SPIDER_LOG_LEVEL_FATAL,array($categoryName));
						return false;
					}
				}
			}
		}
		return $lastCategoryId;
	}
}
?>