<?php
/*
 * shopping/product/unit/Download.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-07-07
 */
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'PackageConfig.class.php' );
class shopping_product_unit_Download extends system_login_ModuleBase {
	function shopping_product_unit_Download(){
	}
	function execute( & $request ) {
		
		$dbo				= $request->getAttribute( 'dbo' );
		$orderId			= stripslashes( $_GET['shpoid'] );
		$memberId			= stripslashes( $_GET['shppid'] );
		$orderKey			= stripslashes( $_GET['shppokey'] );
		$unitId				= stripslashes( $_GET['shpui'] );
		$execCmd			= stripslashes( $_GET['shpcmd'] );
		$loginUserObject	= $this->getLoginUserObject( $request );
		
		// 妥当性検査
		if( !isset($orderId) || strlen(trim($orderId))==0 ) {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else if( !isset($memberId) || strlen(trim($memberId))==0 ) {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else if( !isset($orderKey) || strlen(trim($orderKey))==0 ) {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else if( !isset($unitId) || strlen(trim($unitId))==0 ) {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
		}
		if( $request->isError() ) {
			return false;
		}
		
		// 申し込み情報の存在確認
		$shoppingOrderObject	= spider_Controller::createObject('shopping_DaoShoppingOrder');
		// 対象販売単位
		$targetUnitObject		= null;
		// 対象申し込みの販売単位ID配列
		$targetOrderUnitIdArray	= array();
		if( $dbo->loadById( $shoppingOrderObject, $orderId, true ) ){
			// 申し込み読み込みに成功したら
			if( $shoppingOrderObject->member_id != $memberId ) {
				$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if( $shoppingOrderObject->order_key != $orderKey ) {
				$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_FATAL,array(''));
			} else if( $shoppingOrderObject->status_flag >= 200 ) {
				$request->addLocaledError('shopping.error.order.download.cancel',SPIDER_LOG_LEVEL_ERROR,array());
			} else if( $shoppingOrderObject->status_settle != 101 ) {
				$request->addLocaledError('shopping.error.order.download.nosettled',SPIDER_LOG_LEVEL_ERROR,array());
			} else if( $shoppingOrderObject->status_flag == 101
				&& defined('SHOPPING_DOWNLOAD_ENABLE_FROM_ORDER') && preg_match('/^[0-9]{1,3}$/',SHOPPING_DOWNLOAD_ENABLE_FROM_ORDER) > 0 
				&& time() - strtotime($shoppingOrderObject->registered_date) > 60*60*24*SHOPPING_DOWNLOAD_ENABLE_FROM_ORDER ) {
				$request->addLocaledError('shopping.error.order.download.downloaded',SPIDER_LOG_LEVEL_ERROR,array());
			} else {
				// 問題ないなら完了商品を確認
				$isExists	= false;
				foreach( $shoppingOrderObject->shoppingOrderAddressObjectArray as $addressObject ) {
					foreach( $addressObject->shoppingOrderItemObjectArray as $orderItemObject ) {
						if( $unitId == $orderItemObject->unit_id ) {
							$isExists			= true;
							$targetUnitObject	= $orderItemObject->getUnitObject( $request );
							if( $targetUnitObject->delivery_type != 11 ) {
								$request->addLocaledError('shopping.error.order.download.invalidproduct',SPIDER_LOG_LEVEL_ERROR,array());
							} else if( !in_array($unitObject->unit_id,$targetOrderUnitIdArray) ) {
								array_push($targetOrderUnitIdArray,$unitObject->unit_id);
							}
						}
					}
				}
				if( !$isExists ) {
					$request->addLocaledError('shopping.error.order.download.noorderitem',SPIDER_LOG_LEVEL_ERROR,array());
				}
			}
		} else {
			$request->addLocaledError('system.error.common.invalidaccess',SPIDER_LOG_LEVEL_ERROR,array());
		}
		// ダウンロードファイルを確認
		$targetFileBinObject	= null;
		if( !$request->isError() ) {
			foreach( $targetUnitObject->fileIdArray as $key => $fileId ) {
				if( $key >= 100 ) {
					$fileBinObject	= spider_Controller::createObject('file_DaoFileBin');
					if( $dbo->loadById( $fileBinObject, $fileId ) ) {
						// ターゲットエージェントを確認
						if( strlen(trim($fileBinObject->target_agent)) > 0 ) {
							// ターゲットエージェント設定があるなら確認
							$agentRegxArray	= explode("\n",trim($fileBinObject->target_agent));
							foreach( $agentRegxArray as $agentRegx ) {
								$agentRegx	= trim($agentRegx);
								if( preg_match('/'.util_CharUtility::escapeRegxStr($agentRegx).'/',$_SERVER['HTTP_USER_AGENT']) > 0 ) {
									// ユーザーエージェント指定がマッチするならダウンロード
									$targetFileBinObject	= $fileBinObject;
									break;
								}
							}
						} else {
							// ターゲットユーザーエージェント設定がないなら最初に見つかったファイルでダウンロード
							$targetFileBinObject	= $fileBinObject;
							break;
						}
					}
				}
			}
			if( is_null($targetFileBinObject) ) {
				$request->addLocaledError('shopping.error.order.download.noproperfile',SPIDER_LOG_LEVEL_ERROR,array());
			}
		}
		// ダウンロード履歴を確認する
		if( !$request->isError() ) {
			$sql	= 'SELECT * FROM '.TABLE_NAME_SHOPPING_DOWNLOAD_LOG
				.' WHERE order_id='.$dbo->quote($shoppingOrderObject->order_id)
				.' AND unit_id='.$dbo->quote($targetUnitObject->unit_id)
				.' ORDER BY download_date DESC'
			;
			$downloadRows	= $dbo->queryAll( $sql, 'hash', false );
			if ( $downloadRows === false ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
			} else {
				if( defined('SHOPPING_DOWNLOAD_MAX_COUNT') && preg_match('/^[0-9]{1,2}$/',SHOPPING_DOWNLOAD_MAX_COUNT) > 0 ) {
					// ダウンロード上限回数が設定されているなら確認
					if( count($downloadRows) >= SHOPPING_DOWNLOAD_MAX_COUNT ) {
						$request->addLocaledError('shopping.error.order.download.downloaded',SPIDER_LOG_LEVEL_ERROR,array());
					}
				}
				
				if( defined('SHOPPING_DOWNLOAD_ENABLE_FROM_LAST') && preg_match('/^[0-9]{1,7}$/',SHOPPING_DOWNLOAD_ENABLE_FROM_LAST) > 0 ) {
					if( count($downloadRows)>0 ) {
						$lastDownloadDate	= $downloadRows[0]['download_date'];
						if( time()-strtotime($lastDownloadDate) > 60 * SHOPPING_DOWNLOAD_ENABLE_FROM_LAST ) {
							$request->addLocaledError('shopping.error.order.download.downloaded',SPIDER_LOG_LEVEL_ERROR,array());
						}
					}
				}
			}
		}
		if( !$request->isError() ) {
			// エラーがないならダウンロードログの記録
			$writeLog			= true;
			$rengeAccessInfo	= $request->getRequestRangeInfo();
			if( $rengeAccessInfo ) {
				// Rangeアクセスの場合最終がファイルサイズに達していないならログを記録しない
				if( $rengeAccessInfo['end'] < filesize($targetFileBinObject->getOriginalFilePath( $request )) ) {
					$writeLog			= false;
				}
			}
			if( $this->isLogin( $request )
				&& SYSTEM_LOGIN_USER_ADMINISTRATORS == $loginUserObject->getLoginGroupLevel() ) {
			} else if( $writeLog ) {
				// 管理者でなければダウンロードログを記録
				$sql	= 'INSERT INTO '.TABLE_NAME_SHOPPING_DOWNLOAD_LOG
					.'(order_id,unit_id,download_date,remote_host,remote_address,http_referrer,user_agent) VALUES ('
					.$dbo->quote($shoppingOrderObject->order_id)
					.','.$dbo->quote($targetUnitObject->unit_id)
					.',NOW()'
					.','.$dbo->quote($_SERVER['REMOTE_HOST'])
					.','.$dbo->quote($_SERVER['REMOTE_ADDR'])
					.','.$dbo->quote($_SERVER['HTTP_REFERER'])
					.','.$dbo->quote($_SERVER['HTTP_USER_AGENT'])
					.')'
				;
				$resut = $dbo->query($sql);
				// 全てのアイテムをダウンロード済みか確認する
				if ( $resut === false ) {
					$request->addLocaledError('database2.error.insert',SPIDER_LOG_LEVEL_ERROR,array($sql));
				} else {
					if( count($targetOrderUnitIdArray) > 0 ) {
						$sql	= 'SELECT '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.unit_id'
							.', COUNT('.TABLE_NAME_SHOPPING_DOWNLOAD_LOG.'.download_number) AS download_count '
							.' FROM '.TABLE_NAME_SHOPPING_PRODUCT_UNIT
							.' LEFT OUTER JOIN '.TABLE_NAME_SHOPPING_DOWNLOAD_LOG
							.' ON '.TABLE_NAME_SHOPPING_DOWNLOAD_LOG.'.unit_id='.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.unit_id'
							.' AND '.TABLE_NAME_SHOPPING_DOWNLOAD_LOG.'.order_id='.$dbo->quote($shoppingOrderObject->order_id)
							.' WHERE '
							.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.unit_id IN (\''.implode('\',\'',$targetOrderUnitIdArray).'\')'
							.' GROUP BY '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.unit_id'
						;
						$countHash	= $dbo->queryAll( $sql, 'hash', false );
						if ( $countHash === false ) {
							$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
						} else {
							$isAllDownloaded	= true;
							foreach( $countHash as $countRow ) {
								if( strlen($countRow['download_count']) == 0
									|| $countRow['download_count'] == 0 ) {
									$isAllDownloaded	= false;
									break;
								}
							}
							if( $isAllDownloaded ) {
								$sql	= 'UPDATE '.TABLE_NAME_SHOPPING_ORDER
									.' SET status_flag=101, ';
								if( strlen($shoppingOrderObject->promotion_code)>0
								&& $shoppingOrderObject->status_promotion == 0 ) {
									// プロモーション状態が未確定なら自動で承認済みに変更
									$sql	.= 'status_promotion=10, ';
								}
								$sql	.= 'updated_date=NOW() WHERE order_id='.$dbo->quote($shoppingOrderObject->order_id);
								$resut = $dbo->query($sql);
								if ( $resut === false ) {
									$request->addLocaledError('shopping.error.common.failtochangestatus',SPIDER_LOG_LEVEL_ERROR,array(''));
								}
							}
						}
					}
				}
			}
			
			if( !$request->isError() && !is_null($targetFileBinObject) ) {
				if( preg_match( '/^[eE][xX][eE][cC]$/', $execCmd ) > 0 ) {
					// ダウンロードファイルがあるならダウンロード処理
					$downloadFilePath	= $targetFileBinObject->getOriginalFilePath( $request );
					$request->setResponseHeader( 'Content-Disposition', 'attachment; filename="'.$targetFileBinObject->file_name.'"' );
					$request->setResponseHeader( 'Content-Type', $fileBinObject->mime_type );
					// 2010-08-09 IE7,8 SSLでのダウンロードエラー回避（IEではPragmaがブランクでないとダウンロードエラーになる）
//					$request->setResponseHeader( 'Expires', 'Mon, 26 Jul 1997 05:00:00 GMT' );
//					$request->setResponseHeader( 'Cache-Control', 'no-store, no-cache, must-revalidate' );
//					$request->setResponseHeader( 'Cache-Control', 'pre-check=0, post-check=0, max-age=0' );
//					$request->setResponseHeader( 'Pragma', 'no-cache' );
//					$request->setResponseHeader( 'Expires', '0' );
					$request->setResponseHeader( 'Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0' );
					$request->setResponseHeader( 'Pragma', 'public' );
					$limitDate	= date('D, d M Y H:i:s +0900',strtotime($shoppingOrderObject->registered_date) + (SHOPPING_DOWNLOAD_ENABLE_FROM_ORDER*60*60*24));
					$request->setResponseHeader( 'Expires', $limitDate );
					if( strlen(trim($fileBinObject->response_headers)) > 0 ) {
						$headerArray	= explode("\n",trim($fileBinObject->response_headers));
						foreach( $headerArray as $headerStr ) {
							$headerStr	= trim($headerStr);
							if( strlen($headerStr) > 0 && strpos($headerStr,':') !== false ) {
								$elmArray	= explode(':',$headerStr);
								if( count($elmArray) > 1 ) {
									$request->setResponseHeader(array_shift($elmArray), implode(':',$elmArray));
								}
							}
						}
					}
					$request->setResponseFile( $downloadFilePath );
				} else {
					$request->setAttribute('shopping.download.targetOrderObject', $shoppingOrderObject);
					$request->setAttribute('shopping.download.targetUnitObject', $targetUnitObject);
					$request->setAttribute('shopping.download.targetFileObject', $targetFileBinObject);
				}
			}
		}
	}
}
?>