<?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 Pm_Action_Main_Searchuser extends Action
{
	// リクエストパラメータを受け取るため
	var $handle = null;
	var $now_page = null;
	
	// フィルタによりセット
	var $room_id_arr = null;
	var $room_arr_flat = null;
	
	// 使用コンポーネントを受け取るため
	var $session = null;
	var $usersView = null;
	var $db = null;
	var $pmView = null;
	
	// 値をセットするため
	var $users = null;
	
	//ページ
    var $pager = array();
	
    /**
     * メール転送登録アクション
     *
     * @access  public
     */
    function execute()
    {
    	// 会員管理の権限を用いるように修正
		if($this->session->getParameter("_user_auth_id") == _AUTH_ADMIN) {
    		$user_auth_id = _AUTH_ADMIN;
    	} else {
    		$user_auth_id = $this->session->getParameter("_auth_id");
    	}
    	
    	$select_str = "SELECT {users}.user_id, {users}.handle AS name, {authorities}.role_authority_name, {authorities}.user_authority_id, ".
						"{authorities}.system_flag AS  auth_system_flag,".
						"avatar.content AS icon_path";
		$from_str = " FROM {authorities},{users} ".
					" INNER JOIN {items} avatar_items ON avatar_items.item_name = 'USER_ITEM_AVATAR'".
					" LEFT JOIN {users_items_link} avatar ON avatar.user_id = {users}.user_id AND avatar.item_id=avatar_items.item_id". " ";
		$where_str = " WHERE {users}.role_authority_id={authorities}.role_authority_id AND {users}.active_flag ="._USER_ACTIVE_FLAG_ON;
		
    	$items = array(
    		"handle" => $this->handle
    	);
		$where_params = array();
		$from_params = array();
		//初期化し設定
		foreach($items as $item_name => $item_value) {
			if(isset($item_value)) {
				$this->_createWhereArray($from_str, $from_params, $where_str, $where_params, $item_name, $item_value);
			}
		}

    	$room_id_arr = null;
    	$not_enroll_flag = false;
    	if($user_auth_id == _AUTH_ADMIN) {
			// 管理者　すべての会員
			$this->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;
				}
			}
		}

    	if($room_id_arr != null){
			// 自分のルームに参加している会員を取得
			// デフォルトで参加するルームが１つでもあればすべての会員から検索
			// 但し、pages_users_link-authority_idが_AUTH_OTHER(不参加)されたものは引く
			$default_entry_room_arr = array();
			$default_entry_flag = false;
			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;
				}
			}
			
			$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) {
					$where_str .= " AND {users}.user_id NOT IN ('". implode("','", $pages_users_id_arr). "') ";
				}
			} else {
				// 自分のルームに参加している会員を取得
				$where_str .= " AND {users}.user_id IN ('". implode("','", $pages_users_id_arr). "') ";
			}
		}
		$params = array_merge($from_params, $where_params);
		// レコード数取得
		$count_sql = "SELECT COUNT(*) ";
		$count_sql .= $from_str.$where_str;
		$count_result =& $this->db->execute($count_sql, $params, null, null, false);
		if($count_result === false) {
			$this->db->addError();
			return 'error';
		}
		$count = intval($count_result[0][0]);
		
		$order_params = array(
			"{users}.system_flag" => "DESC",
			"{users}.handle" => "ASC"
		);
		$order_str = " ".$this->db->getOrderSQL($order_params);
		
    	$sql = $select_str.$from_str.$where_str;
		$sql = $select_str.$from_str.$where_str.$order_str;
		$this->pmView->setPageInfo($this->pager, $count, PM_SEARCH_VISIBLE_ITEM_CNT, $this->now_page);
		$this->users =& $this->db->execute($sql, $params, PM_SEARCH_VISIBLE_ITEM_CNT, $this->pager['disp_begin'], true, array($this, "_SearchFetchcallback"));
		if($this->users === false) {
			$this->db->addError();
			return 'error';
		}

		return "success";
    }
    
	/**
	 * Where配列作成処理
	 *
	 * @access  private
	 */
	function _createWhereArray(&$from_str, &$from_params, &$where_str, &$where_params, $item, $value) {
		switch ($item) {
			default :
				$where_str .= " AND {users}.".$item." LIKE ?";
				$where_params[] = "%".$value."%";
		}
	}
	
	/**
	 * fetch時コールバックメソッド
	 * @param result adodb object
	 * @return array items
	 * @access	private
	 */
	function &_getItemsFetchcallback($result) {
		$ret = array();
		while ($row = $result->fetchRow()) {
			$ret[$row['item_id']] = $row;
		}
		return $ret;
	}
	
	/**
	 * 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];
		//if(count($default_entry_room_arr) == 0) {
		//	$default_entry_flag = false;
		//} else {
		//	$default_entry_flag = true;
		//}
		
		$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時コールバックメソッド
	 * @param result adodb object
	 * @return array users
	 * @access	private
	 */
	function &_SearchFetchcallback($result) {
		$ret = array();
		while ($row = $result->fetchRow()) {
			if(isset($row['auth_system_flag']) && $row['auth_system_flag'] == _ON &&
				defined($row['role_authority_name'])) {
					$row['role_authority_name'] = constant($row['role_authority_name']);
			}
			$ret[] = $row;
		}
		return $ret;
	}
}
?>
