protected function searchByFlag( $flag )
    {
        $uid = ( $this->options->uidReferencing ) ? self::UID : self::NO_UID;

        if ( $this->state != self::STATE_SELECTED &&
             $this->state != self::STATE_SELECTED_READONLY )
        {
            throw new ezcMailTransportException( "Can't call searchByFlag() on the IMAP transport when a mailbox is not selected." );
        }

        $matchingMessages = array();
        $flag = $this->normalizeFlag( $flag );
        if ( in_array( $flag, self::$extendedFlags ) )
        {
            $tag = $this->getNextTag();
            $this->connection->sendData( "{$tag} {$uid}SEARCH ({$flag})" );
            $response = $this->getResponse( '* SEARCH' );

            if ( strpos( $response, '* SEARCH' ) !== false )
            {
                $ids = substr( trim( $response ), 9 );
                if ( trim( $ids ) !== "" )
                {
                    $matchingMessages = explode( ' ', $ids );
                }
            }
            $response = trim( $this->getResponse( $tag, $response ) );
            if ( $this->responseType( $response ) != self::RESPONSE_OK )
            {
                throw new ezcMailTransportException( "The IMAP server could not search the messages by flags: {$response}." );
            }
        }
        else
        {
            throw new ezcMailTransportException( "Flag '{$flag}' is not allowed for searching." );
        }
        return $matchingMessages;
    }