Class: Net::LDAP::Filter

### Home Classes Methods

### In Files

- lib/net/ldap/filter.rb

### Parent

Object

### Methods

- ::begins
- ::construct
- ::contains
- ::ends
- ::eq
- ::equals
- ::escape
- ::ex
- ::from_rfc2254
- ::from_rfc4515
- ::ge
- ::intersect
- ::join
- ::le
- ::ne
- ::negate
- ::parse_ber
- ::parse_ldap_filter
- ::pres
- ::present
- ::present?
- #&
- #==
- #execute
- #match
- #to_ber
- #to_raw_rfc2254
- #to_rfc2254
- #to_s
- #|
- #~

### Files

- History.rdoc
- Manifest.txt

### Class/Module Index

Quicksearch

- Net
- Net::BER
- Net::BER::BERParser
- Net::BER::BerError
- Net::BER::BerIdentifiedArray
- Net::BER::BerIdentifiedNull
- Net::BER::BerIdentifiedOid
- Net::BER::BerIdentifiedString
- Net::BER::Extensions
- Net::BER::Extensions::Array
- Net::BER::Extensions::Bignum
- Net::BER::Extensions::FalseClass
- Net::BER::Extensions::Fixnum
- Net::BER::Extensions::String
- Net::BER::Extensions::TrueClass
- Net::LDAP
- Net::LDAP::Connection
- Net::LDAP::Connection::GetbyteForSSLSocket
- Net::LDAP::DN
- Net::LDAP::Dataset
- Net::LDAP::Entry
- Net::LDAP::Filter
- Net::LDAP::LdapControls
- Net::LDAP::LdapError
- Net::LDAP::PDU
- Net::LDAP::PDU::Error
- Net::LDAP::Password
- OpenSSL
- OpenSSL::SSL
- OpenSSL::SSL::SSLSocket

No matching classes.

# Net::LDAP::Filter

Class Net::LDAP::Filter is used to constrain LDAP searches. An object of this class is passed to Net::LDAP#search in the parameter :filter.

Net::LDAP::Filter supports the complete set of search filters available in LDAP, including conjunction, disjunction and negation (AND, OR, and NOT). This class supplants the (infamous) RFC 2254 standard notation for specifying LDAP search filters.

Here's how to code the familiar "objectclass is present" filter:

    f = Net::LDAP::Filter.present("objectclass")

The object returned by this code can be passed directly to the `:filter` parameter of Net::LDAP#search.

See the individual class and instance methods below for more examples.

### Constants

ESCAPES

  tools.ietf.org/html/rfc4515 lists these exceptions from UTF1 charset for filters. All of the following must be escaped in any normal string using a single backslash ('') as escape.

ESCAPE_RE

  Compiled character class regexp using the keys from the above hash.

FilterTypes

  Known filter types.

### Public Class Methods

begins(attribute, value) click to toggle source

Creates a Filter object indicating that the value of a particular attribute must begin with a particular string. The attribute value is escaped, so the "*" character is interpreted literally.

    # File lib/net/ldap/filter.rb, line 138
    def begins(attribute, value)
      new(:eq, attribute, escape(value) + "*")
    end

construct(ldap_filter_string) click to toggle source

Converts an LDAP filter-string (in the prefix syntax specified in RFC-2254) to a Net::LDAP::Filter.

    # File lib/net/ldap/filter.rb, line 322
    def construct(ldap_filter_string)
      FilterParser.parse(ldap_filter_string)
    end

Also aliased as: from_rfc2254, from_rfc4515
contains(attribute, value) click to toggle source

Creates a Filter object indicating that the value of a particular attribute must contain a particular string. The attribute value is escaped, so the "*" character is interpreted literally.

    # File lib/net/ldap/filter.rb, line 154
    def contains(attribute, value)
      new(:eq, attribute, "*" + escape(value) + "*")
    end

ends(attribute, value) click to toggle source

Creates a Filter object indicating that the value of a particular attribute must end with a particular string. The attribute value is escaped, so the "*" character is interpreted literally.

    # File lib/net/ldap/filter.rb, line 146
    def ends(attribute, value)
      new(:eq, attribute, "*" + escape(value))
    end

eq(attribute, value) click to toggle source

Creates a Filter object indicating that the value of a particular attribute must either be present or match a particular string.

Specifying that an attribute is 'present' means only directory entries which contain a value for the particular attribute will be selected by the filter. This is useful in case of optional attributes such as `mail.` Presence is indicated by giving the value "*" in the second parameter to eq. This example selects only entries that have one or more values for `sAMAccountName:`

    f = Net::LDAP::Filter.eq("sAMAccountName", "*")

To match a particular range of values, pass a string as the second parameter to eq. The string may contain one or more "*" characters as wildcards: these match zero or more occurrences of any character. Full regular-expressions are not supported due to limitations in the underlying LDAP protocol. This example selects any entry with a `mail` value containing the substring "anderson":

    f = Net::LDAP::Filter.eq("mail", "*anderson*")

This filter does not perform any escaping

    # File lib/net/ldap/filter.rb, line 63
    def eq(attribute, value)
      new(:eq, attribute, value)
    end

equals(attribute, value) click to toggle source

Creates a Filter object indicating that the value of a particular attribute must match a particular string. The attribute value is escaped, so the "*" character is interpreted literally.

    # File lib/net/ldap/filter.rb, line 130
    def equals(attribute, value)
      new(:eq, attribute, escape(value))
    end

escape(string) click to toggle source

Escape a string for use in an LDAP filter

    # File lib/net/ldap/filter.rb, line 244
    def escape(string)
      string.gsub(ESCAPE_RE) { |char| "\\" + ESCAPES[char] }
    end

ex(attribute, value) click to toggle source

Creates a Filter object indicating extensible comparison. This Filter object is currently considered EXPERIMENTAL.

    sample_attributes = ['cn:fr', 'cn:fr.eq',
      'cn:1.3.6.1.4.1.42.2.27.9.4.49.1.3', 'cn:dn:fr', 'cn:dn:fr.eq']
    attr = sample_attributes.first # Pick an extensible attribute
    value = 'roberts'

    filter = "#{attr}:=#{value}" # Basic String Filter
    filter = Net::LDAP::Filter.ex(attr, value) # Net::LDAP::Filter

    # Perform a search with the Extensible Match Filter
    Net::LDAP.search(:filter => filter)

    # File lib/net/ldap/filter.rb, line 112
    def ex(attribute, value)
      new(:ex, attribute, value)
    end

from_rfc2254(ldap_filter_string) click to toggle source
Alias for: construct
from_rfc4515(ldap_filter_string) click to toggle source
Alias for: construct
ge(attribute, value) click to toggle source

Creates a Filter object indicating that a particular attribute value is greater than or equal to the specified value.

    # File lib/net/ldap/filter.rb, line 161
    def ge(attribute, value)
      new(:ge, attribute, value)
    end

intersect(left, right) click to toggle source

Creates a disjoint comparison between two or more filters. Selects entries where either the left or right side are true. Calling `Filter.intersect(left, right)` is the same as `left | right`.

    # Selects only entries that have an <tt>objectclass</tt> attribute.
    x = Net::LDAP::Filter.present("objectclass")
    # Selects only entries that have a <tt>mail</tt> attribute that begins
    # with "George".
    y = Net::LDAP::Filter.eq("mail", "George*")
    # Selects only entries that meet either condition above.
    z = x | y

    # File lib/net/ldap/filter.rb, line 201
    def intersect(left, right)
      new(:or, left, right)
    end

join(left, right) click to toggle source

Joins two or more filters so that all conditions must be true. Calling `Filter.join(left, right)` is the same as `left & right`.

    # Selects only entries that have an <tt>objectclass</tt> attribute.
    x = Net::LDAP::Filter.present("objectclass")
    # Selects only entries that have a <tt>mail</tt> attribute that begins
    # with "George".
    y = Net::LDAP::Filter.eq("mail", "George*")
    # Selects only entries that meet both conditions above.
    z = Net::LDAP::Filter.join(x, y)

    # File lib/net/ldap/filter.rb, line 184
    def join(left, right)
      new(:and, left, right)
    end

le(attribute, value) click to toggle source

Creates a Filter object indicating that a particular attribute value is less than or equal to the specified value.

    # File lib/net/ldap/filter.rb, line 168
    def le(attribute, value)
      new(:le, attribute, value)
    end

ne(attribute, value) click to toggle source

Creates a Filter object indicating that a particular attribute value is either not present or does not match a particular string; see Filter::eq for more information.

This filter does not perform any escaping

    # File lib/net/ldap/filter.rb, line 122
    def ne(attribute, value)
      new(:ne, attribute, value)
    end

negate(filter) click to toggle source

Negates a filter. Calling `Fitler.negate(filter)` i s the same as `~filter`.

    # Selects only entries that do not have an <tt>objectclass</tt>
    # attribute.
    x = ~Net::LDAP::Filter.present("objectclass")

    # File lib/net/ldap/filter.rb, line 212
    def negate(filter)
      new(:not, filter, nil)
    end

parse_ber(ber) click to toggle source

Converts an LDAP search filter in BER format to an Net::LDAP::Filter object. The incoming BER object most likely came to us by parsing an LDAP searchRequest PDU. See also the comments under to_ber, including the grammar snippet from the RFC.

    # File lib/net/ldap/filter.rb, line 256
    def parse_ber(ber)
      case ber.ber_identifier
      when 0xa0 # context-specific constructed 0, "and"
        ber.map { |b| parse_ber(b) }.inject { |memo, obj| memo & obj }
      when 0xa1 # context-specific constructed 1, "or"
        ber.map { |b| parse_ber(b) }.inject { |memo, obj| memo | obj }
      when 0xa2 # context-specific constructed 2, "not"
        ~parse_ber(ber.first)
      when 0xa3 # context-specific constructed 3, "equalityMatch"
        if ber.last == "*"
        else
          eq(ber.first, ber.last)
        end
      when 0xa4 # context-specific constructed 4, "substring"
        str = ""
        final = false
        ber.last.each { |b|
          case b.ber_identifier
          when 0x80 # context-specific primitive 0, SubstringFilter "initial"
            raise Net::LDAP::LdapError, "Unrecognized substring filter; bad initial value." if str.length > 0
            str += b
          when 0x81 # context-specific primitive 0, SubstringFilter "any"
            str += "*#{b}"
          when 0x82 # context-specific primitive 0, SubstringFilter "final"
            str += "*#{b}"
            final = true
          end
        }
        str += "*" unless final
        eq(ber.first.to_s, str)
      when 0xa5 # context-specific constructed 5, "greaterOrEqual"
        ge(ber.first.to_s, ber.last.to_s)
      when 0xa6 # context-specific constructed 6, "lessOrEqual"
        le(ber.first.to_s, ber.last.to_s)
      when 0x87 # context-specific primitive 7, "present"
        # call to_s to get rid of the BER-identifiedness of the incoming string.
        present?(ber.to_s)
      when 0xa9 # context-specific constructed 9, "extensible comparison"
        raise Net::LDAP::LdapError, "Invalid extensible search filter, should be at least two elements" if ber.size<2

        # Reassembles the extensible filter parts
        # (["sn", "2.4.6.8.10", "Barbara Jones", '1'])
        type = value = dn = rule = nil
        ber.each do |element|
          case element.ber_identifier
            when 0x81 then rule=element
            when 0x82 then type=element
            when 0x83 then value=element
            when 0x84 then dn='dn'
          end
        end

        attribute = ''
        attribute << type if type
        attribute << ":#{dn}" if dn
        attribute << ":#{rule}" if rule

        ex(attribute, value)
      else
        raise Net::LDAP::LdapError, "Invalid BER tag-value (#{ber.ber_identifier}) in search filter."
      end
    end

parse_ldap_filter(obj) click to toggle source

Convert an RFC-1777 LDAP/BER "Filter" object to a Net::LDAP::Filter object.

    # File lib/net/ldap/filter.rb, line 335
    def parse_ldap_filter(obj)
      case obj.ber_identifier
      when 0x87 # present. context-specific primitive 7.
        eq(obj.to_s, "*")
      when 0xa3 # equalityMatch. context-specific constructed 3.
        eq(obj[0], obj[1])
      else
        raise Net::LDAP::LdapError, "Unknown LDAP search-filter type: #{obj.ber_identifier}"
      end
    end

pres(attribute) click to toggle source
Alias for: present?
present(attribute) click to toggle source
Alias for: present?
present?(attribute) click to toggle source

This is a synonym for eq(attribute, "*"). Also known as present and pres.

    # File lib/net/ldap/filter.rb, line 219
    def present?(attribute)
      eq(attribute, "*")
    end

Also aliased as: present, pres

### Public Instance Methods

&(filter) click to toggle source

Joins two or more filters so that all conditions must be true.

    # Selects only entries that have an <tt>objectclass</tt> attribute.
    x = Net::LDAP::Filter.present("objectclass")
    # Selects only entries that have a <tt>mail</tt> attribute that begins
    # with "George".
    y = Net::LDAP::Filter.eq("mail", "George*")
    # Selects only entries that meet both conditions above.
    z = x & y

    # File lib/net/ldap/filter.rb, line 357
    def &(filter)
      self.class.join(self, filter)
    end

==(filter) click to toggle source

Equality operator for filters, useful primarily for constructing unit tests.

    # File lib/net/ldap/filter.rb, line 388
    def ==(filter)
      # 20100320 AZ: We need to come up with a better way of doing this. This
      # is just nasty.
      str = "[@op,@left,@right]"
      self.instance_eval(str) == filter.instance_eval(str)
    end

execute(&block) click to toggle source

Perform filter operations against a user-supplied block. This is useful when implementing an LDAP directory server. The caller's block will be called with two arguments: first, a symbol denoting the "operation" of the filter; and second, an array consisting of arguments to the operation. The user-supplied block (which is MANDATORY) should perform some desired application-defined processing, and may return a locally-meaningful object that will appear as a parameter in the :and, :or and :not operations detailed below.

A typical object to return from the user-supplied block is an array of Net::LDAP::Filter objects.

These are the possible values that may be passed to the user-supplied block:

    * :equalityMatch (the arguments will be an attribute name and a value
      to be matched);
    * :substrings (two arguments: an attribute name and a value containing
      one or more "*" characters);
    * :present (one argument: an attribute name);
    * :greaterOrEqual (two arguments: an attribute name and a value to be
      compared against);
    * :lessOrEqual (two arguments: an attribute name and a value to be
      compared against);
    * :and (two or more arguments, each of which is an object returned
      from a recursive call to #execute, with the same block;
    * :or (two or more arguments, each of which is an object returned from
      a recursive call to #execute, with the same block; and
    * :not (one argument, which is an object returned from a recursive
      call to #execute with the the same block.

    # File lib/net/ldap/filter.rb, line 571
    def execute(&block)
      case @op
      when :eq
        if @right == "*"
          yield :present, @left
        elsif @right.index '*'
          yield :substrings, @left, @right
        else
          yield :equalityMatch, @left, @right
        end
      when :ge
        yield :greaterOrEqual, @left, @right
      when :le
        yield :lessOrEqual, @left, @right
      when :or, :and
        yield @op, (@left.execute(&block)), (@right.execute(&block))
      when :not
        yield @op, (@left.execute(&block))
      end || []
    end

match(entry) click to toggle source

    # File lib/net/ldap/filter.rb, line 612
    def match(entry)
      case @op
      when :eq
        if @right == "*"
          l = entry[@left] and l.length > 0
        else
          l = entry[@left] and l = Array(l) and l.index(@right)
        end
      else
        raise Net::LDAP::LdapError, "Unknown filter type in match: #{@op}"
      end
    end

to_ber() click to toggle source

Converts the filter to BER format.

    # File lib/net/ldap/filter.rb, line 470
    def to_ber
      case @op
      when :eq
        if @right == "*" # presence test
          @left.to_s.to_ber_contextspecific(7)
        elsif @right =~ /[*]/ # substring
          # Parsing substrings is a little tricky. We use String#split to
          # break a string into substrings delimited by the * (star)
          # character. But we also need to know whether there is a star at the
          # head and tail of the string, so we use a limit parameter value of
          # -1: "If negative, there is no limit to the number of fields
          # returned, and trailing null fields are not suppressed."
          #
          # 20100320 AZ: This is much simpler than the previous verison. Also,
          # unnecessary regex escaping has been removed.

          ary = @right.split(/[*]+/, -1)

          if ary.first.empty?
            first = nil
            ary.shift
          else
            first = ary.shift.to_ber_contextspecific(0)
          end

          if ary.last.empty?
            last = nil
            ary.pop
          else
            last = ary.pop.to_ber_contextspecific(2)
          end

          seq = ary.map { |e| e.to_ber_contextspecific(1) }
          seq.unshift first if first
          seq.push last if last

          [@left.to_s.to_ber, seq.to_ber].to_ber_contextspecific(4)
        else # equality
          [@left.to_s.to_ber, unescape(@right).to_ber].to_ber_contextspecific(3)
        end
      when :ex
        seq = []

        unless @left =~ /^([-;\w]*)(:dn)?(:(\w+|[.\w]+))?$/
          raise Net::LDAP::LdapError, "Bad attribute #{@left}"
        end
        type, dn, rule = $1, $2, $4

        seq << rule.to_ber_contextspecific(1) unless rule.to_s.empty? # matchingRule
        seq << type.to_ber_contextspecific(2) unless type.to_s.empty? # type
        seq << unescape(@right).to_ber_contextspecific(3) # matchingValue
        seq << "1".to_ber_contextspecific(4) unless dn.to_s.empty? # dnAttributes

        seq.to_ber_contextspecific(9)
      when :ge
        [@left.to_s.to_ber, unescape(@right).to_ber].to_ber_contextspecific(5)
      when :le
        [@left.to_s.to_ber, unescape(@right).to_ber].to_ber_contextspecific(6)
      when :ne
        [self.class.eq(@left, @right).to_ber].to_ber_contextspecific(2)
      when :and
        ary = [@left.coalesce(:and), @right.coalesce(:and)].flatten
        ary.map {|a| a.to_ber}.to_ber_contextspecific(0)
      when :or
        ary = [@left.coalesce(:or), @right.coalesce(:or)].flatten
        ary.map {|a| a.to_ber}.to_ber_contextspecific(1)
      when :not
        [@left.to_ber].to_ber_contextspecific(2)
      end
    end

to_raw_rfc2254() click to toggle source

    # File lib/net/ldap/filter.rb, line 395
    def to_raw_rfc2254
      case @op
      when :ne
        "!(#{@left}=#{@right})"
      when :eq
        "#{@left}=#{@right}"
      when :ex
        "#{@left}:=#{@right}"
      when :ge
        "#{@left}>=#{@right}"
      when :le
        "#{@left}<=#{@right}"
      when :and
        "&(#{@left.to_raw_rfc2254})(#{@right.to_raw_rfc2254})"
      when :or
        "|(#{@left.to_raw_rfc2254})(#{@right.to_raw_rfc2254})"
      when :not
        "!(#{@left.to_raw_rfc2254})"
      end
    end

to_rfc2254() click to toggle source

Converts the Filter object to an RFC 2254-compatible text format.

    # File lib/net/ldap/filter.rb, line 418
    def to_rfc2254
      "(#{to_raw_rfc2254})"
    end

to_s() click to toggle source

    # File lib/net/ldap/filter.rb, line 422
    def to_s
      to_rfc2254
    end

|(filter) click to toggle source

Creates a disjoint comparison between two or more filters. Selects entries where either the left or right side are true.

    # Selects only entries that have an <tt>objectclass</tt> attribute.
    x = Net::LDAP::Filter.present("objectclass")
    # Selects only entries that have a <tt>mail</tt> attribute that begins
    # with "George".
    y = Net::LDAP::Filter.eq("mail", "George*")
    # Selects only entries that meet either condition above.
    z = x | y

    # File lib/net/ldap/filter.rb, line 372
    def |(filter)
      self.class.intersect(self, filter)
    end

~() click to toggle source

Negates a filter.

    # Selects only entries that do not have an <tt>objectclass</tt>
    # attribute.
    x = ~Net::LDAP::Filter.present("objectclass")

    # File lib/net/ldap/filter.rb, line 382
    def ~
      self.class.negate(self)
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.