<?php
/*
 * shopping/DaoShoppingCategory.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(__FILE__)
.DIRECTORY_SEPARATOR.'PackageConfig.class.php');
require_once( dirname(dirname( __FILE__ ))
.DIRECTORY_SEPARATOR.'database2'
.DIRECTORY_SEPARATOR.'AbstractData.class.php');
/**
 * shopping_DaoShoppingCategory
 * shoppingパッケージ データアクセスオブジェクトクラス shopping_categoryテーブル用
 */
class shopping_DaoShoppingCategory extends database2_AbstractData {
	var $category_number;
	var $category_id;
	var $parent_id;
	var $category_name;
	var $category_kana;
	var $order_number	= 0;
	var $status_flag	= 0;
	var $description;
	var $updated_date;
	var $registered_date;
	/** 登録者ID	*/
	var $owner_id;
	/** 変更者ＩＤ	*/
	var $modifier_id;
	
	/** オブジェクト拡張：子カテゴリID配列	*/
	var $child_category_id_array	= array();
	/** オブジェクト拡張：子カテゴリ配列	*/
	var $child_category_object_array	= array();
	/** オブジェクト拡張：親カテゴリオブジェクト	*/
	var $parent_category_object			= null;
	/** 登録商品数	*/
	var $item_count		= 0;

	/**
	 * コンストラクタ
	 */
	function shopping_DaoShoppingCategory(){
		$this->child_category_id_array		= array();
		$this->child_category_object_array	= array();
		$this->parent_category_object		= null;
	}
	function _load_optional_data( $dbo, $load_child=true, $load_parent=true ) {
		// 子カテゴリの読み込み
		if( $load_child ) {
			$sql	= 'SELECT * '
			.' FROM ' . TABLE_NAME_SHOPPING_CATEGORY
			.' WHERE status_flag<200 '
			.' AND parent_id=' . $dbo->quote( $this->category_id )
			.' ORDER BY order_number ASC, category_kana ASC';
			$searchCategoryObject = spider_Controller::createObject('shopping_DaoShoppingCategory');
			$dataArray	= $dbo->queryAll( $sql, $searchCategoryObject, false, false );
			if ( $dataArray === false ){
				if( is_object($dbo->request) ){
					$dbo->request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
				}
			} else {
				foreach( $dataArray as $key => $object ) {
					$dataArray[$key]->_load_optional_data( $dbo, true, false );
					$dataArray[$key]->parent_category_object	= & $this;
					array_push( $this->child_category_id_array, trim($object->category_id) );
				}
				$this->child_category_object_array	= $dataArray;
			}
		}
		// 親カテゴリの読み込み
		if( $load_parent && strlen(trim($this->parent_id)) > 0 ) {
			$this->parent_category_object	= spider_Controller::createObject('shopping_DaoShoppingCategory');
			$dbo->loadById($this->parent_category_object,trim($this->parent_id),false);
			$this->parent_category_object->_load_optional_data( $dbo, false, true );
		}
		// 直接紐づいているプロダクト数を取得
		$sql	= 'SELECT COUNT( DISTINCT '.TABLE_NAME_SHOPPING_CATEGORY_PRODUCT.'.product_id ) '
			.' FROM '.TABLE_NAME_SHOPPING_CATEGORY_PRODUCT
			.' INNER JOIN '.TABLE_NAME_SHOPPING_PRODUCT
			.' ON '.TABLE_NAME_SHOPPING_PRODUCT.'.product_id='.TABLE_NAME_SHOPPING_CATEGORY_PRODUCT.'.product_id'
			.' WHERE '
			.TABLE_NAME_SHOPPING_CATEGORY_PRODUCT.'.category_id='.$dbo->quote($this->category_id)
			.' AND '
			.TABLE_NAME_SHOPPING_PRODUCT.'.status_flag>=100'
			.' AND '
			.TABLE_NAME_SHOPPING_PRODUCT.'.status_flag<200'
		;
		$this->item_count	= $dbo->queryOne($sql);
	}
	/**
	 * インサート前に行いたい処理
	 * @param MDBObject $dbo MDB2オブジェクトかその互換オブジェクト
	 * @return boolean 成功したらtrue
	 */
	function pre_insert( $dbo ) {
		return true;
	}
	/**
	 * アップデート前に行いたい処理
	 * @param MDBObject $dbo MDB2オブジェクトかその互換オブジェクト
	 * @return boolean 成功したらtrue
	 */
	function pre_update( $dbo ) {
		return true;
	}
	/**
	 * 階層構造をカテゴリ名文字列にして取得します。
	 */
	function getCategoryFullName( $separator=' ' ) {
		if( strlen($this->parent_id) > 0 && !is_null($this->parent_category_object) ) {
			$categoryNameArray	= array();
			array_push($categoryNameArray,$this->category_name);
			$categoryObject	= $this->parent_category_object;
			while( !is_null($categoryObject) ) {
				array_unshift($categoryNameArray,$categoryObject->category_name);
				$categoryObject	= & $categoryObject->parent_category_object;
			}
			return implode($separator, $categoryNameArray);
		} else {
			return $this->category_name;
		}
	}
	/**
	 * 階層構造のカテゴリ名文字列からカテゴリオブジェクトを取得します。
	 */
	function loadByCategoryFullName( $dbo, $categoryFullName, $separator=' ' ) {
		if( strlen($categoryFullName) > 0 ) {
			$condition_array	= array();
			$categoryNameArray	= array();
			// カテゴリ名を階層別に分ける
			$categoryNameArray	= explode($separator, $categoryFullName);
			
			// 階層別にカテゴリ名を条件にし、カテゴリIDを特定する
			$categoryName = array_pop( $categoryNameArray );
			$strTableName = TABLE_NAME_SHOPPING_CATEGORY;
			array_push( $condition_array, $strTableName.'.category_name='.$dbo->quote($categoryName) );
			$from_string = ' FROM '.TABLE_NAME_SHOPPING_CATEGORY;
			while ( count($categoryNameArray) > 0 ) {
				$categoryName = array_pop( $categoryNameArray );
				$from_string .= ' LEFT OUTER JOIN '.TABLE_NAME_SHOPPING_CATEGORY.' AS '.'g'.$strTableName
					.' ON '.'g'.$strTableName.'.category_id='.$strTableName.'.parent_id'
				;
				$strTableName = 'g'.$strTableName;
				array_push( $condition_array, $strTableName.'.category_name='.$dbo->quote($categoryName) );
			}
			$condition_string	= '';
			if ( count( $condition_array ) > 0 ) {
				$condition_string	= ' WHERE ' . implode( ' AND ', $condition_array );
			}
			$sql = 'SELECT '.TABLE_NAME_SHOPPING_CATEGORY.'.*'
				.$from_string
				.$condition_string
			;
			$dataArray	= $dbo->queryAll( $sql, 'hash' );
			if ( $dataArray === false ) {
				if( is_object($dbo->request) ){
					$dbo->request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
				}
			} else if ( count($dataArray) == 0 ) {
				// 該当行が見つからない場合、falseを返す
				return false;
			} else if ( count($dataArray) > 1 ) {
				// 複数行取得した場合、falseを返す
				return false;
			} else {
				return $dbo->setRowToFields( $dataArray[0], $this );
			}
		} else {
				return false;
		}
	}
// TODO:メソッド、変数名、要検討し修正
	function getByFullNameFromChild( $categoryFullName, $separator=' ' ) {
		$categoryNameArray	= explode( $separator, $categoryFullName );
		$categoryName		= array_shift($categoryNameArray);
		if( $this->category_name == $categoryName ) {
			$childCategoryFullName	= implode( $separator, $categoryNameArray );
			if( strlen( $childCategoryFullName ) > 0 ) {
				foreach( $this->child_category_object_array as $childObject ) {
					$result = $childObject->getByFullNameFromChild( $childCategoryFullName, $separator );
					if( false !== $result ) {
						return $result;
					}
				}
				return false;
			} else {
				return $this;
			}
		} else {
			return false;
		}
	}
	/**
	 * 階層下に所属する全てのカテゴリ数を取得します。
	 */
	function getAllChildCount() {
		$allCount	= 0;
		foreach( $this->child_category_object_array as $childObject ) {
			$allCount++;
			$allCount	+= $childObject->getAllChildCount();
		}
		return $allCount;
	}
	/**
	 * 階層化に所属する全てのカテゴリIDの配列を取得します
	 */
	function getAllChildCategoryIdArray() {
		$childCategoryIdArray	= array();
		foreach( $this->child_category_object_array as $childObject ) {
			array_push( $childCategoryIdArray, $childObject->category_id );
			$idArray	= $childObject->getAllChildCategoryIdArray();
			foreach( $idArray as $id ) {
				array_push( $childCategoryIdArray, $id );
			}
		}
		return $childCategoryIdArray;
	}
	/**
	 * 本オブジェクトの階層位置を取得します
	 */
	function getHierarchy() {
		if( get_class($this->parent_category_object) == get_class($this) ) {
			$hierarchy		= 0;
			$parentObject	= $this->parent_category_object;
			while( !is_null($parentObject) ) {
				$hierarchy++;
				$parentObject	= $parentObject->parent_category_object;
			}
			return $hierarchy;
		} else {
			return 0;
		}
	}
	/**
	 * 本オブジェクトの最下層位置を取得します
	 */
	function getMaxChildHierarchy(){
		if( count($this->child_category_object_array) == 0 ) {
			return $this->getHierarchy();
		} else {
			$maxHierarchy	= $this->getHierarchy() + 1;
			foreach( $this->child_category_object_array as $childObject ) {
				$hierarchy	= $childObject->getMaxChildHierarchy();
				if( $hierarchy > $maxHierarchy ) {
					$maxHierarchy	= $hierarchy;
				}
			}
			return $maxHierarchy;
		}
	}
	function getChildDipth() {
		return $this->getMaxChildHierarchy() - $this->getHierarchy();
	}
	/**
	 * 下層カテゴリを含めて紐づいているプロダクト総数を取得します
	 */
	function getTotalItemCount() {
		$totalCount	= $this->item_count;
		if( is_array($this->child_category_object_array) ) {
			foreach( $this->child_category_object_array as $childObject ) {
				$totalCount	+= $childObject->getTotalItemCount();
			}
		}
		return $totalCount;
	}
	/**
	 * 妥当性検査
	 */
	function validate( & $request ){
		$dbo	= $request->getAttribute('dbo');
		if( strlen(trim($this->category_id)) == 0 ) {
		} else if( strlen(trim($this->category_id)) > 16 ) {
			$request->addLocaledError('shopping.error.dao.category.invalidid',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else if( !preg_match('/^[0-9a-zA-Z]+$/', $this->category_id) ) {
			$request->addLocaledError('shopping.error.dao.category.invalidid',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else {
			$compareShoppingCategoryObject		= spider_Controller::createObject('shopping_DaoShoppingCategory');
			if( $dbo->loadById( $compareShoppingCategoryObject, $this->category_id ) ) {
				if( $this->category_number != $compareShoppingCategoryObject->category_number ) {
				$request->addLocaledError('shopping.error.dao.category.duplicatedid',SPIDER_LOG_LEVEL_ERROR,array(''));
				}
			}
		}
		
		if( strlen(trim($this->category_name)) == 0 ) {
			$request->addLocaledError('shopping.error.dao.category.requirename',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else if( strlen(trim($this->category_name)) > 90 ) {
			$request->addLocaledError('shopping.error.dao.category.invalidname',SPIDER_LOG_LEVEL_ERROR,array(''));
		}
		
		if( strlen(trim($this->category_kana)) == 0 ) {
		} else if( strlen(trim($this->category_kana)) > 90 ) {
			$request->addLocaledError('shopping.error.dao.category.invalidkana',SPIDER_LOG_LEVEL_ERROR,array(''));
		}
		if( $this->navigation_view != 1 ) {
			$this->navigation_view	= 0;
		}
		if( strlen(trim($this->order_number)) == 0 ) {
			$this->order_number	= 50;
		} else if ( !is_numeric( $this->order_number )
			|| !preg_match('/^[0-9]+$/',$this->order_number) ) {
			$request->addLocaledError('shopping.error.dao.category.invalidvieworder',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else if ( $this->order_number < 0 ) {
			$request->addLocaledError('shopping.error.dao.category.invalidvieworder',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else if ( $this->order_number > 100 ) {
			$request->addLocaledError('shopping.error.dao.category.invalidvieworder',SPIDER_LOG_LEVEL_ERROR,array(''));
		}
		
		if( strlen(trim($this->parent_id)) == 0 ) {
		} else if( strlen(trim($this->parent_id)) > 16 ) {
			$request->addLocaledError('shopping.error.dao.category.invalidparent',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else if( !preg_match('/^[0-9a-zA-Z]+$/', $this->parent_id) ) {
			$request->addLocaledError('shopping.error.dao.category.invalidparent',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else if( trim($this->parent_id) == trim($this->category_id) ) {
			$request->addLocaledError('shopping.error.dao.category.invalidparent',SPIDER_LOG_LEVEL_ERROR,array(''));
		} else {
			$compareShoppingCategoryObject	= spider_Controller::createObject('shopping_DaoShoppingCategory');
			if( !$dbo->loadById( $compareShoppingCategoryObject, $this->parent_id ) ) {
				$request->addLocaledError('shopping.error.dao.category.invalidparent',SPIDER_LOG_LEVEL_ERROR,array(''));
			}
		}
		if( strlen(trim($this->description)) == 0 ) {
		} else if( strlen(trim($this->description)) > 900 ) {
				$request->addLocaledError('shopping.error.dao.category.overdescription',SPIDER_LOG_LEVEL_ERROR,array(''));
		}
		if( $request->isError() ){
			return false;
		}
		return true;
	}
	/**
	 * サムネイル画像のURIを取得します
	 */
	function getImageURI( & $request, $num=0, $confirm=true ){
		$fileURI	= '/upload/shopping/category/'.$this->category_id.'_'.sprintf('%02d',$num);
		if( $confirm ){
			spider_Controller::loadClassDefinition('system_DataFileWriter');
			if( system_DataFileWriter::isExists( $request, $fileURI.'.jpg', 'public' ) ){
				return $fileURI.'.jpg';
			} else if( system_DataFileWriter::isExists( $request, $fileURI.'.JPG', 'public' ) ){
				return $fileURI.'.JPG';
			} else if( system_DataFileWriter::isExists( $request, $fileURI.'.png', 'public' ) ){
				return $fileURI.'.png';
			} else if( system_DataFileWriter::isExists( $request, $fileURI.'.PNG', 'public' ) ){
				return $fileURI.'.PNG';
			} else if( system_DataFileWriter::isExists( $request, $fileURI.'.gif', 'public' ) ){
				return $fileURI.'.gif';
			} else if( system_DataFileWriter::isExists( $request, $fileURI.'.GIF', 'public' ) ){
				return $fileURI.'.GIF';
			} else {
				return false;
			}
		}
		return $fileURI;
	}
}
?>