<?php
/**
 *  User/Read.php
 *
 *  @author     {$author}
 *  @package    Secioss
 *  @version    $Id: skel.action.php,v 1.10 2006/11/06 14:31:24 cocoitiban Exp $
 */

/**
 *  user_readフォームの実装
 *
 *  @author     {$author}
 *  @access     public
 *  @package    Secioss
 */
class Secioss_Form_UserRead extends Secioss_ActionForm
{
    /** @var    bool    バリデータにプラグインを使うフラグ */
    var $use_validator_plugin = true;

    /**
     *  @access private
     *  @var    array   フォーム値定義
     */
    var $form = array(
        'id' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_TEXT,
            'name'          => 'ユーザID',
            'min'           => null,
            'max'           => null,
            'regexp'        => null
        ),
        'name' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_TEXT,
            'name'          => '氏名',
            'min'           => null,
            'max'           => null,
            'regexp'        => null
        ),
        'status' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_SELECT,
            'name'          => 'ユーザ状態',
            'option'        => array('*' => '全て', 'active' => '有効', 'inactive' => '無効')
        ),
        'lockout' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_SELECT,
            'name'          => 'ロックアウト状態',
            'option'        => array(null => '全て', 'TRUE' => 'ロックアウトされている')
        ),
        'tenant' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_SELECT,
            'name'          => 'テナント',
            'option'        => 'tenant_select'
        ),
        'system' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_SELECT,
            'name'          => 'システム',
            'option'        => 'system_select'
        ),
        'department' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_SELECT,
            'name'          => '部署',
            'option'        => 'department_select'
        ),
        'title' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_SELECT,
            'name'          => '役職',
            'option'        => 'title_select'
        ),
        'dn' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_HIDDEN
        ),
        'page_size' => array(
            'type'          => VAR_TYPE_INT,
            'form_type'     => FORM_TYPE_TEXT,
            'min'           => 1,
            'max'           => MAX_PAGE_SIZE,
            'default'       => MAX_PAGE_SIZE
        ),
        'key' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_SELECT,
            'option'        => array('uid' => 'ユーザID', 'cn;lang-ja;phonetic' => '氏名'),
            'required'      => true
        ),
        'page_num' => array(
            'type'          => VAR_TYPE_INT,
            'form_type'     => FORM_TYPE_HIDDEN,
            'min'           => 1
        ),
        'file_output' => array(
            'type'          => VAR_TYPE_INT,
            'form_type'     => FORM_TYPE_HIDDEN,
            'default'       => 0
        ),
        'operation' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_HIDDEN,
            'required'       => true
        ),
        'search' => array(
            'type'          => VAR_TYPE_STRING,
            'form_type'     => FORM_TYPE_HIDDEN,
        )
    );
}

/**
 *  user_readアクションの実装
 *
 *  @author     {$author}
 *  @access     public
 *  @package    Secioss
 */
class Secioss_Action_UserRead extends Secioss_ActionClass
{
    /**
     *  user_readアクションの前処理
     *
     *  @access public
     *  @return string      遷移名(正常終了ならnull, 処理終了ならfalse)
     */
    function prepare()
    {
        if ($this->af->get('search') == "true") {
            return 'user_search';
        }

        $this->af->setApp('total_num', 0);

        if ($this->af->get('operation') != "search") {
            return 'user_read';
        }

        if ($this->af->validate() > 0) {
            $this->ae->add(null, $this->getInvalidValMsg($this->getErrorFormName()));

            return 'user_read';
        }

        return null;
    }

    /**
     *  user_readアクションの実装
     *
     *  @access public
     *  @return string  遷移名
     */
    function perform()
    {
        $auth =& $this->backend->getManager('Auth');
        $logger =& $this->backend->getLogger();
        $login_user = $this->session->get('user');
        $conf = $this->config->get('secioss');

        $id = $this->af->get('id');
        $name = $this->af->get('name');
        $status = $this->af->get('status');
        $lockout = $this->af->get('lockout');
        $tenant = $this->af->get('tenant');
        $system = $this->af->get('system');
        $department = $this->af->get('department');
        $title = $this->af->get('title');
        $page_size = $this->af->get('page_size');
        $key = $this->af->get('key');
        $page_num = $this->af->get('page_num');
        $file_output = $this->af->get('file_output');

        $role = $this->session->get('role');

        if ($role == 'tenant_admin') {
            $tenant = $this->session->get('tenant');
        }

        //  make filter to search
        if (!$id) {
            $id = '*';
        }
        if ($tenant) {
            $filter['area'] = $tenant;
        }
        if ($system) {
            $filter['system'] = $system;
        }

        $groups = array();
        if ($department) {
            array_push($groups, $department);
        }
        if ($title) {
            array_push($groups, $title);
        }
        if (isset($conf['user']['statusattr']) && $status) {
       	    $filter[$conf['user']['statusattr']] = $status;
        }
        if (isset($conf['user']['pwlockoutattr']) && $lockout) {
            $filter[$conf['user']['pwlockoutattr']] = $lockout;
        }
       	if ($name) {
            if(preg_match('/\*/',$name)) $filter['cn'] = $name;
            else $filter['cn'] = "*".$name."*";
       	}

        if(!$file_output){
            $start = ($page_num - 1)*$page_size + 1;
            $num = $page_size;
        }else{
            $start = 1;
            $num = null;
        }

        if(count($groups)){ //ロールでフィルタリング added by okazaki 090216
            $user_list = array();

            foreach ($groups as $groupid) {
                $r = $auth->getObjectList('group',array('id' => $groupid));
                $group = $r[1][0];
                $member = $group->get('memberuid');
                if(!is_array($member) && $member) $member = array($member);

                foreach ($member as $user) {
                    if (array_search($user_list, $user) == false) {
                        array_push($user_list, $user);
                    }
                }
            }

            $id = preg_replace('/\*/', '.*', $id);
            $users = array();
            for($i = 0; $i < count($user_list);$i++){
                if ($i < $start - 1) {
                    continue;
                } else if ($num && $i > $start + $num - 1) {
                    break;
                }

                if (!preg_match('/^'.$id.'$/i', $user_list[$i])) {
                    continue;
                }

                $filter['uid'] = $user_list[$i];
                $r = $auth->getObjectPropList('user', null, $filter);
                if (Ethna::isError($r)) {
                    $logger->log(LOG_ERR, "$login_user failed to search the users: ".$r->getMessage());
                    $this->ae->add(null, S_INTERNAL_ERR_MSG);
                    return 'user_read';
                }
                if($r[1][0]) array_push($users, $r[1][0]);
            }
            $total_num = count($users);

            //$usersのソート
            foreach($users as $key => $row){
                $sort_key[$key] = $row[$key];
            }
            array_multisort($sort_key, SORT_ASC, $users);
        }else{
            $filter['uid'] = $id;

            $r = $auth->getObjectPropList('user', null, $filter, array($key => OBJECT_SORT_ASC), $start, $num);
            if (Ethna::isError($r)) {
                $logger->log(LOG_ERR, "$login_user failed to search the users: ".$r->getMessage());
            	$this->ae->add(null, S_INTERNAL_ERR_MSG);

                return 'user_read';
            }
            $total_num = $r[0];
            $users = $r[1];
        }

        if ($file_output) {
            $fp = new File();
            $file = BASEDIR.'/tmp/users'.date('YmdHis').'.csv';

            for ($i = 0; $i < $total_num && isset($users[$i]); $i++) {
                $data = array($users[$i]['uid'],
                              $users[$i]['employeenumber'],
                              $users[$i]['sn'],
                              $users[$i]['givenname'],
                              $users[$i]['sn;lang-ja;phonetic'],
                              $users[$i]['givenname;lang-ja;phonetic'],
                              $users[$i]['mail']
                             );
                if (isset($conf['user']['loginidattr'])) {
                    $data[] = $users[$i][$conf['user']['loginidattr']];
                }
                if (isset($conf['user']['statusattr'])) {
                    $data[] = $users[$i][$conf['user']['statusattr']];
                }
                if (isset($conf['area']) && $role == 'system_admin') {
                    $data[] = $users[$i]['area'];
                }

                mb_convert_variables('SJIS', 'UTF-8', $data);         

                $rc = $fp->writeLine($file, implode(',', $data));
                if (PEAR::isError($rc)) {
                    $logger->log(LOG_ERR, "$login_user failed to write CSV file: ".$rc->getMessage());
                    unlink($file);
                    return null;
                }
            }
            $fp->close($file, FILE_MODE_APPEND);

            if (!$auth->downloadFile($file)) {
                $logger->log(LOG_ERR, "$login_user failed to download CSV file");
                unlink($file);
                return null;
            }
            unlink($file);

            return null;
        }

        $list = array();
        for ($i = 0; $i < $total_num && isset($users[$i]); $i++) {
            $data = array('dn'      => $users[$i]['id'],
                          'id'      => $users[$i]['uid'],
                          'name'    => $users[$i]['cn'],
                          'kana'    => isset($users[$i]['cn;lang-ja;phonetic']) ? $users[$i]['cn;lang-ja;phonetic'] : ''
                          );
            if (isset($conf['user']['statusattr'])) {
                $data['status'] = $users[$i][$conf['user']['statusattr']] == 'active' ? '有効' : '無効';
            }
            if (isset($conf['area']) && $role == 'system_admin') {
                $data['tenant'] = $users[$i]['area'];
            }

            array_push($list, $data);
        }

        if (isset($conf['area']) && $role == 'system_admin') {
            $this->session->set('tenant', $tenant);
        }
        if (isset($conf['system'])) {
            $this->session->set('system', $system);
        }

        $this->af->setApp('beginning_num', ($page_num - 1)*$page_size + 1);
        $this->af->setApp('total_num', $total_num);
        $this->af->setApp('total_page_num', ceil($r[0] / $page_size));
        $this->af->setApp('list_num', count($list));
        $this->af->setApp('list', $list);

        $logger->log(LOG_INFO, "$login_user succeeded to search the users");

        return 'user_read';
    }
}
?>
