<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * 検索実行(会員絞込み)
 *
 * @package     NetCommons
 * @author      Noriko Arai,Ryuji Masukawa
 * @copyright   2006-2007 NetCommons Project
 * @license     http://www.netcommons.org/license.txt  NetCommons License
 * @project     NetCommons Project, supported by National Institute of Informatics
 * @access      public
 */
class Room_Action_Admin_Search extends Action
{
	// リクエストパラメータを受け取るため
	var $items = null;
	var $sel_room_id_list = null;
	
	var $room_parent_id = null;	//ルーム管理-会員絞込み
	var $room_current_id = null;	//ルーム管理-会員絞込み
	
	// フィルタによりセット
	var $room_id_arr = null;
	var $room_arr_flat = null;
	
	// 使用コンポーネントを受け取るため
	var $db = null;
	var $session = null;
	var $usersView = null;
	var $pagesView = null;
	
	// 値をセットするため
	var $count = null;
	
	/**
	 * execute実行
	 *
	 * @access  public
	 */
	function execute()
	{
		$this->room_current_id = ($this->room_current_id == null) ? 0 : intval($this->room_current_id);
		// 検索は、常に管理者権限での検索結果を表示する
		$user_auth_id = _AUTH_ADMIN;
    	//$user_auth_id = $this->session->getParameter("_user_auth_id");
    	$where_params = array(
    						"user_authority_id" => $user_auth_id
    					);
    	$result =& $this->usersView->getItems($where_params, null, null, null, array($this, "_getItemsFetchcallback"));
    	if($result === false) return 'error';
    	list($items, $tags_items) = $result;
    	 	
		//
		// SQL文作成処理
		//
		//$select_str =& $this->session->getParameter(array("room", $this->room_current_id,"selected_select_str"));
    	//$from_str =& $this->session->getParameter(array("room", $this->room_current_id,"selected_from_str"));
	    //$where_str =& $this->session->getParameter(array("room", $this->room_current_id,"selected_where_str"));
    	//$params =& $this->session->getParameter(array("room", $this->room_current_id,"selected_params"));
    	
    	//初期化し設定
    	$add_from_str = "";
    	$add_where_str = "";
    	$where_params = array();
    	$from_params = array();
 	
		$this->session->removeParameter(array("room", $this->room_current_id, "search"));
		foreach($this->items as $item_id => $item_value) {
			if(isset($items[$item_id])) {
				if(is_array($item_value)) {
					//日付関連 何日以上前～何日以内 OR　チェックボックス
					foreach($item_value as $key => $value) {
						$this->_createWhereArray($add_from_str, $from_params, $add_where_str, $where_params, $items[$item_id], $value, "_".$key);
					}
				} else {
					$this->_createWhereArray($add_from_str, $from_params, $add_where_str, $where_params, $items[$item_id], $item_value);
				}
			}
		}
		//
		// 参加ルーム
		//	
		
		// グループスペースのみセット
		$room_id_arr = null;
		if($this->room_id_arr != null){
			$room_id_arr = array();
			foreach($this->room_id_arr as $room_id) {
				if ($this->room_arr_flat[$room_id]['space_type'] == _SPACE_TYPE_GROUP &&
					$this->room_arr_flat[$room_id]['private_flag'] == _OFF) {
					$room_id_arr[] = $room_id;
				}
			}
		}
		$not_enroll_flag = false;
		$this->session->removeParameter(array("room", "search", 0));
		if($this->sel_room_id_list == "USER_NOT_ENROLL" && $user_auth_id == _AUTH_ADMIN) {
			// ルームに参加していない会員
			// 管理者の場合のみ
			// ルームに参加していない会員を求める
			$not_enroll_flag = true;
			// 検索条件をセッションに保存 item_id=0を使用
			$this->session->setParameter(array("room", "search", 0), "USER_NOT_ENROLL");
		} else if($this->sel_room_id_list != null && in_array( intval($this->sel_room_id_list), $this->room_id_arr )) {
			//参加ルーム指定あり
			$room_id_arr = array();
			$room_id_arr[] = intval($this->sel_room_id_list);
			// 検索条件をセッションに保存 item_id=0を使用
			$this->session->setParameter(array("room", "search", 0), $this->sel_room_id_list);
		} else if($user_auth_id == _AUTH_ADMIN) {
			// 管理者　すべての会員
			$room_id_arr = null;
		}
		
		if($room_id_arr != null){
			// 自分のルームに参加している会員を取得
			// デフォルトで参加するルームが１つでもあればすべての会員から検索
			// 但し、pages_users_link-authority_idが_AUTH_OTHER(不参加)されたものは引く
			$default_entry_room_arr = array();
			$default_entry_flag = false;
			if($this->sel_room_id_list != null && $this->sel_room_id_list != "USER_NOT_ENROLL") {
				// 参加ルーム指定あり
				if(isset($this->room_arr_flat[$this->sel_room_id_list]) && 
					$this->room_arr_flat[$this->sel_room_id_list]['default_entry_flag'] == _ON &&
					$this->room_arr_flat[$this->sel_room_id_list]['space_type'] == _SPACE_TYPE_GROUP &&
					$this->room_arr_flat[$this->sel_room_id_list]['private_flag'] == _OFF) {
					// デフォルトで参加しているグループルームあり
					$default_entry_room_arr[$this->room_arr_flat[$this->sel_room_id_list]['page_id']] = $this->room_arr_flat[$this->sel_room_id_list]['page_id'];
					$default_entry_flag = true;
				}
			} else {
				foreach($this->room_arr_flat as $room) {
					if($room['default_entry_flag'] == _ON && $room['space_type'] == _SPACE_TYPE_GROUP &&
						 $room['private_flag'] == _OFF) {
						// デフォルトで参加しているグループルーム
						$default_entry_room_arr[$room['page_id']] = $room['page_id'];
						$default_entry_flag = true;
					}
				}
			}
			// ルームに参加していない会員
			//$sel_default_entry_flag = $default_entry_flag;
			//if($not_enroll_flag == true) {
			//	$sel_default_entry_flag = ($default_entry_flag == true) ? false : true;	
			//}
			$pages_users_id_arr =& $this->usersView->getPagesUsersLinkByRoom($room_id_arr, null,null,null, null, array($this, "_getPagesUsersLinkFetchcallback"), array($not_enroll_flag, $default_entry_flag, $default_entry_room_arr));
			if($pages_users_id_arr === false) {
				return 'error';
			}
			$sel_default_entry_flag = $default_entry_flag;
			if($not_enroll_flag == true) {
				$sel_default_entry_flag = ($default_entry_flag == true) ? false : true;	
			}
			if($sel_default_entry_flag) {
				// 禁止者を省く	
				if($pages_users_id_arr != null) {
					// 禁止者も「ルームに参加していない会員」ではなければ表示
					$add_where_str .= " AND {users}.user_id NOT IN ('". implode("','", $pages_users_id_arr). "') ";
				}
			} else {
				// 自分のルームに参加している会員を取得
				$add_where_str .= " AND {users}.user_id IN ('". implode("','", $pages_users_id_arr). "') ";
			}
			
		}
		$this->session->setParameter(array("room", $this->room_current_id,"selected_add_from_str"), $add_from_str);
		$this->session->setParameter(array("room", $this->room_current_id,"selected_add_where_str"), $add_where_str);
		$this->session->setParameter(array("room", $this->room_current_id,"selected_from_params"), $from_params);
		$this->session->setParameter(array("room", $this->room_current_id,"selected_where_params"), $where_params);
		
		return 'success';
	}
	/**
	 * Where配列作成処理
	 *
	 * @access  private
	 */
	function _createWhereArray(&$from_str, &$from_params, &$where_str, &$where_params, $item, $value, $rename_post_fix = "") {
		if($value != "") {
			if($item['tag_name'] != "" && $item['tag_name'] != "user_name" && $item['tag_name'] != "email") {
				$tag_name = "";
				switch ($item['tag_name']) {
					case "password":
					case "lang_dirname_lang":
						// 検索不可
						break;
					case "timezone_offset_lang":
						// タイムゾーン
						$from_str .= " INNER JOIN {users_items_link} users_items_link".$item['item_id'].$rename_post_fix." ON (users_items_link".$item['item_id'].".item_id=? && users_items_link".$item['item_id'].$rename_post_fix.".content = ? && {users}.user_id=users_items_link".$item['item_id'].$rename_post_fix.".user_id)";
						$from_params[] = $item['item_id'];
						$from_params[] = $value . "|";
						break;
					case "role_authority_name":
						$tag_name = "role_authority_id";
						$value_arr = explode("|", $value);
						$value = intval($value_arr[0]);
						
						$where_str .= " AND {users}.".$tag_name." = ?";
						$where_params[] = $value;
						break;
					case "active_flag_lang":
						$tag_name = "active_flag";
						$value_arr = explode("|", $value);
						$value = intval($value_arr[1]);
						
						$where_str .= " AND {users}.".$tag_name." = ?";
						$where_params[] = $value;
						break;
					case "insert_time":
					case "update_time":
					case "password_regist_time":
					case "last_login_time":
						$tag_name = $item['tag_name'];
						if($rename_post_fix == "_0") {
							// 日以上前 <=
							$operator = "<=";
						} else {
							// 日以内 >=
							$operator = ">=";
						}
						$value = intval($value);
						$time = timezone_date();
						$time = mktime(intval(substr($time, 8, 2)), intval(substr($time, 10, 2)), 
											intval(substr($time, 12, 2)), intval(substr($time, 4, 2)), 
											intval(substr($time, 6, 2)) - $value, intval(substr($time, 0, 4)));
						$time = date("YmdHis", $time);
						
						$where_str .= " AND {users}.".$tag_name." ".$operator." ?";
						$where_params[] = $time;
						
						break;
					default :
						$tag_name = $item['tag_name'];
						$where_str .= " AND {users}.".$tag_name." LIKE ?";
						$where_params[] = "%".$value."%";
				}
			} else {
				if($item['type'] == "select" || $item['type'] == "radio" || $item['type'] == "checkbox") {
					//デフォルト値取得
					$from_str .= " INNER JOIN {users_items_link} users_items_link".$item['item_id'].$rename_post_fix." ON (users_items_link".$item['item_id'].$rename_post_fix.".item_id=? && users_items_link".$item['item_id'].$rename_post_fix.".content LIKE ? && {users}.user_id=users_items_link".$item['item_id'].$rename_post_fix.".user_id)";
					$from_params[] = $item['item_id'];
					$from_params[] = "%".$value . "|" ."%";
				} else {
					$from_str .= " INNER JOIN {users_items_link} users_items_link".$item['item_id'].$rename_post_fix." ON (users_items_link".$item['item_id'].$rename_post_fix.".item_id=? && users_items_link".$item['item_id'].$rename_post_fix.".content LIKE ? && {users}.user_id=users_items_link".$item['item_id'].$rename_post_fix.".user_id)";
					$from_params[] = $item['item_id'];
					$from_params[] = "%".$value."%";
				}
			}
			// session登録処理
			// 検索条件をセッションに保存
			if($rename_post_fix == "") {
				$this->session->setParameter(array("room", $this->room_current_id, "search", $item['item_id']), $value);
			} else {
				$this->session->setParameter(array("room", $this->room_current_id, "search", $item['item_id'], substr($rename_post_fix, 1, strlen($rename_post_fix) - 1)), $value);
			}
		}
	}
	
	/**
	 * fetch時コールバックメソッド
	 * @param result adodb object
	 * @return array items
	 * @access	private
	 */
	function _getItemsFetchcallback($result) {
		$ret = array();
		$ret_tags = array();
		while ($row = $result->fetchRow()) {
			$ret[$row['item_id']] = $row;
			if(isset($row['tag_name']) && $row['tag_name'] !="") {
				switch ($row['tag_name']) {
					case "active_flag_lang":
						$tag_name = "active_flag";
						break;
					case "timezone_offset_lang":
						$tag_name = "timezone_offset";
						break;
					default :
						$tag_name = $row['tag_name'];
				}
				$ret_tags[$tag_name] = $row;
			}
		}
		return array($ret, $ret_tags);
	}
	
	/**
	 * fetch時コールバックメソッド-getPagesUsersLinkByRoom
	 * @param result adodb object
	 * @return array items
	 * @access	private
	 */
	function &_getPagesUsersLinkFetchcallback($result, $func_params) {
		$not_enroll_flag = $func_params[0];
		$default_entry_flag = $func_params[1];
		$default_entry_room_arr =& $func_params[2];
		
		$absence_user_arr = array();	//不参加会員
		$ret = array();
		while ($row = $result->fetchRow()) {
			if($row['role_authority_id'] == _ROLE_AUTH_OTHER) {
				//不参加会員
				$absence_user_arr[$row['room_id']][] = $row['user_id'];
			} else {
				$ret[$row['user_id']] = $row['user_id'];
			}
		}
		$user_intersect_arr = null;
		if($default_entry_flag) {
			foreach($default_entry_room_arr as $room_id) {
				if(isset($absence_user_arr[$room_id])) {
					if($user_intersect_arr == null) {
						$user_intersect_arr = $absence_user_arr[$room_id];
					} else {
						// 共通項を求める
						$user_intersect_arr = array_intersect($user_intersect_arr, $absence_user_arr[$room_id]);
					}
				} else {
					// 禁止者が誰もいないデフォルトで参加するルームあり
					// すべての会員から検索する
					$user_intersect_arr = null;
					break;
				}
			}
		}
		if($default_entry_flag == false) {
			// 参加者を求める
			return $ret;
		} else if($not_enroll_flag) {
			$ret_user_intersect_arr = array();
			if(is_array($user_intersect_arr)) {
				foreach($user_intersect_arr as $user_intersect) {
					if(!isset($ret[$user_intersect])) {
						$ret_user_intersect_arr[] = $user_intersect;
					}
				}
			}
			return $ret_user_intersect_arr;
		} else {
			// 禁止者を求める
			return $user_intersect_arr;
		}
	}
	
	
	/**
	 * fetch時コールバックメソッド-getPagesUsersLinkByRoom
	 * @param result adodb object
	 * @return array items
	 * @access	private
	 */
	function &_getSubGroupPagesUsersLinkFetchcallback($result, $func_params) {
		$ret = array();
		while ($row = $result->fetchRow()) {
			$ret[$row['user_id']] = $row['user_id'];
		}
		
		// 参加者を求める
		return $ret;
	}
}
?>