2006 LDAP Filter Building UDF
I am working on a project that needs to do LDAP lookups, and lots of them. Some of my searches are for a single name, others are for multiple, and some allow partial matches (begin with passed string) while others don't.
A simple LDAP test for equality filter might look like this: uid=jsmith. Searching for multiple users (an OR search, so that any of them match) requires a syntax like this: (|(uid=jsmith)(uid=jdoe)(uid=bjones)). And then to allow wildcard searching you'd need to add a * after the name (or each name in the OR example).
To make all of this simpler I wrote this little UDF. You pass it the attribute to search on, the text to search for (lists are allowed), and whether or not wildcard searches are allowed. The string that is returned can be passed to <CFLDAP> as is.
2<cffunction name="BuildLDAPFilter" returntype="string" output="false">
3 <cfargument name="ldapField" type="string" required="yes">
4 <cfargument name="searchText" type="string" required="yes">
5 <cfargument name="wildcard" type="boolean" required="no" default="no">
6
7 <cfset var result="">
8 <cfset var i="">
9 <cfset var suffix="">
10
11 <!--- If wildcard, set suffix --->
12 <cfif ARGUMENTS.wildcard>
13 <cfset suffix="*">
14 </cfif>
15
16 <!--- Is this single or list? --->
17 <cfif ListLen(ARGUMENTS.searchText) IS 1>
18 <!--- Single, use as is --->
19 <cfset result="#ARGUMENTS.ldapField#=#ARGUMENTS.searchText##suffix#">
20 <cfelse>
21 <!--- Multiple, start filter string --->
22 <cfset result="(|">
23 <!--- Loop through fields --->
24 <cfloop list="#ARGUMENTS.searchText#" index="i">
25 <!--- Append field --->
26 <cfset result=result&"(#ARGUMENTS.ldapField#=#i##suffix#)">
27 </cfloop>
28 <!--- Wrap up filter string --->
29 <cfset result=result&")">
30 </cfif>
31
32 <cfreturn result>
33</cffunction>