Adding ad php консультации. Подключение к AD

Some HTML and text ads can be aligned horizontally using the text-align CSS property. More complicated issues of alignment and position within the various template files can be solved using proper CSS styling.

Adding Style to Ads

You may want to use some simple CSS to wrap the post around your advertising. In this example, the ad will appear in the upper right of each post, with the post text wrapped around it.

<>

Of course, you can also create styles for ads in your stylesheet.

Plugins for Advertising

Cg-PowerPack Includes the CG-Inline plugin and CG-Amazon CG-Inline is a powerful macro system for embedding auto-generated items within your posts/articles. In combination with CG-Amazon, allows for quick insertion of Amazon links/images within a post. Flexible image inlines, for floating/embedded thumbnails or image links. Powerful permalink creation. CG-Amazon provides live Amazon data feeds, product links, wishlist links, keyword lookups, all product types/catalogs, article inlined and sidebars, keyword lookups, admin interface and caching system. MooseCandy Adds content before specified posts (ex: an advertising banner between 1st and 2nd post). WP-Amazon Search and include items from Amazon.com to your post entries. This plugin adds a link called "Insert item from Amazon.com"? on the post page. This link launches a search window which allows an author to search for items from Amazon.com to be included on the author"s post entry. Adsense Beautifier Adsense beautifier is a plugin available for Wordpress to make your Adsense look beautiful in order to increase you Adsense earnings. Images adjacent to ads can help increase click through rate (CTR).

Troubleshooting Ads

If you are having trouble with your ads, here are some possible solutions.

Why Aren"t My Ads Showing Up?

In many cases it has nothing to do with WordPress, but here are a few things to remember or questions to ask yourself:

  1. With the context sensitive ad services, often the reason is that the keywords for context sensitive ads come from a search engine. Try a search for the URL where the ads should appear in the associated search engine and if the URL is not indexed, you will not get ads.
  2. Many ads use Javascripts. Some of those scripts do not validate correctly and some of them may behave oddly with certain stylesheet features or even with other scripts on the same page.
  3. Doublecheck your placement. For example, if you included the ad code in the Post section of the Main template file and now you are looking at a Page instead of a Post.
  4. Are you running a firewall, ad blocker or other software that may block the ad code? Do you have Javascript enabled in your browser? If the ad uses Flash or another plugin, do you have the required plugin installed?
  5. Try a thorough reload of the page. Clear your browser cache and cookies. Shut down your browser. Restart the browser. Load the page.

All I Get are Ads for Blogs

Context sensitive ads spider your site and index the keywords. If your site is heavy on words and links related to blogging, you will get lots of ads related to blogging. There are two things you can do to improve this. First, eliminate unnecessary blogging references. Second, make longer, keyword rich posts. Posts over 250 words tend to produce better context sensitive ads.

If you are using Google"s Adsense and having this problem, you may be able to see some improvement by using section targeting .

I Get Different Ads on Different Pages

If you find you are getting different ads at example.com/index.php than from the URI example.com , this issue with context sensitive ads may be because the search engine reads these as two separate URLs and may index them on different days.

The URL with index.php may be read by the search engine more or less often than the same page without the index.php . Once both are properly indexed, the ads should match -- at least for a while. The only solution, other than time, is to do everything you can to eliminate the use of the index.php in links, etc. A similar situation can occur with www.example.com reading differently than example.com without the www .

16 years ago

Try this script if you don"t know how to add an user in the AD Win2K.
To have more informations about the attributes, open the adsiedit console in the Support Tools for Win2K.

$adduserAD["cn"] =
$adduserAD["instancetype"] =
$adduserAD["objectclass"] = "top";
$adduserAD["objectclass"] = "person";
$adduserAD["objectclass"] = "organizationalPerson";
$adduserAD["objectclass"] = "user";
$adduserAD["displayname"] =
$adduserAD["name"] =
$adduserAD["givenname"] =
$adduserAD["sn"] =
$adduserAD["company"] =
$adduserAD["department"] =
$adduserAD["title"] =
$adduserAD["description"] =
$adduserAD["mail"] =
$adduserAD["initials"] =
$adduserAD["samaccountname"] =
$adduserAD["userprincipalname"] =
$adduserAD["profilepath"] =
$adduserAD["manager"] = ***Use DistinguishedName***

if (!($ldap = ldap_connect("localhost"))) {
die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, "[email protected]", $password))) {
die ("Could not bind to the LDAP account");
}
if (!(ldap_add($ldap, "CN=New User,OU=OU Users,DC=pc,DC=com", $adduserAD))){
echo "There is a problem to create the account
echo "Please contact your administrator !";
exit;
}
ldap_unbind($ldap);

12 years ago

Here is how to add a user with a hashed MD5 password to OpenLDAP. I used this technique to migrate Drupal accounts into OpenLDAP for a single-sign-on solution.

The trick to it is to tell OpenLDAP the hash type (e.g. {MD5}) before the password, and also to base64 encode the BINARY hashed result. You cannot just base64 encode what is returned by PHP"s md5() or sha() hash functions, because they return a hexadecimal text string. First you must use pack("H*", $hash_result) to make that a binary string, THEN you can base64 encode it.

Here is complete code for connecting and adding a user with a hashed password. You don"t have to use {MD5}, you could pick a different hash if that is what you have. The output from one of these hashed passwords will look like this: {md5}bdwD04RS9xMDGVi1n/H36Q==

Finally some caveats: This technique will not work if you hashed the password using a salt value (but Drupal does not). This technique will also certainly not work with active directory, where passwords can definitely only be set over SSL connections and hashing probably works differently.

$ds = ldap_connect($serverAddress);
if ($ds) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // otherwise PHP defaults to ldap v2 and you will get a Syntax Error!
$r = ldap_bind($ds, $managerDN, $managerPassword);
$ldaprecord["cn"] = $newuser_username;
$ldaprecord["givenName"] = $newuser_firstname;
$ldaprecord["sn"] = $newuser_surname;
// put user in objectClass inetOrgPerson so we can set the mail and phone number attributes
$ldaprecord["objectclass"] = "person";
$ldaprecord["objectclass"] = "organizationalPerson";
$ldaprecord["objectclass"] = "inetOrgPerson";
$ldaprecord["mail"] = $newuser_email_address;
$ldaprecord["telephoneNumber"] = $newuser_phone_number;
// and now the tricky part, base64 encode the binary hash result:
$ldaprecord["userPassword"] = "{MD5}" . base64_encode(pack("H*",$newuser_md5hashed_password));
// If you have the plain text password instead, you could use:
// $ldaprecord["userPassword"] = "{MD5}" . base64_encode(pack("H*",md5($newuser_plaintext_password)));
$r = ldap_add($ds, $base_user_dn, $ldaprecord);
} else { die "cannot connect to LDAP server at $serverAddress."; }

11 years ago

I created a simple function that can be called to create global distribution groups in Active Directory:

function ldap_createGroup ($object_name , $dn , $members , $ldap_conn )
{
$addgroup_ad [ "cn" ]= " $object_name " ;
$addgroup_ad [ "objectClass" ][ 0 ] = "top" ;
$addgroup_ad [ "objectClass" ][ 1 ] = "group" ;
$addgroup_ad [ "groupType" ]= "2" ;
$addgroup_ad [ "member" ]= $members ;
$addgroup_ad [ "sAMAccountName" ] = $object_name ;

Ldap_add ($ldap_conn , $dn , $addgroup_ad );

If(ldap_error ($ldap_conn ) == "Success" )
return true ;
else
return false ;
}
?>

You can call this function using the follow code:

$ldap_conn = ldap_bind ();
$object_name = "Test Group" ;
$dn = "CN=" . $object_name . ",OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM" ;
$members = "CN=User1,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM" ;
$members = "CN=User2,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM" ;

Ldap_createGroup ($object_name , $dn , $members , $ldap_conn );
?>

The other function I created is ldap_bind(), and this can be used to bind to an LDAP server:

function ldap_bind ()
{
$ldap_addr = "192.168.1.1" ; // Change this to the IP address of the LDAP server
$ldap_conn = ldap_connect ($ldap_addr ) or die("Couldn"t connect!" );
ldap_set_option ($ldap_conn , LDAP_OPT_PROTOCOL_VERSION , 3 );
$ldap_rdn = "domain_name\\user_account" ;
$ldap_pass = "user_password" ;

// Authenticate the user against the domain controller
$flag_ldap = ldap_bind ($ldap_conn , $ldap_rdn , $ldap_pass );
return $ldap_conn ;
}
?>

13 years ago

When adding/editing attributes for a user, keep in mind that the "memberof" attribute is a special case. The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute "member":

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com" ;
$group_info [ "member" ] = $dn ; // User"s DN is added to group"s "member" array
ldap_mod_add ($connect , $group_name , $group_info );

?>

11 years ago

This solution works for us.
In the form the CN and pwdtxt are randomly generated from strict rules.
This script creates 50-60 users i AD pr.day! and never even had a glitch!

## From form
$CN = $_POST [ "CN" ];
$givenName = $_POST [ "givenName" ];
$SN = $_POST [ "SN" ];
$mail = $_POST [ "mail" ];
$Phone = $_POST [ "Phone" ];
$pwdtxt = $_POST [ "pwdtxt" ];

$AD_server = "localhost:390" ; // Local Stunnel --> http://www.stunnel.org/
$AD_Auth_User = "[email protected]" ; //Administrative user
$AD_Auth_PWD = "duppiduppdupp" ; //The password

$dn = "CN=" . $CN . ",OU=Brukere,DC=student,DC=somwhere,DC=com" ;

## Create Unicode password
$newPassword = "\"" . $pwdtxt . "\"" ;
$len = strlen ($newPassword );
$newPassw = "" ;

for($i = 0 ; $i < $len ; $i ++) {
$newPassw .= " { $newPassword { $i }} \000" ;
}

## CONNNECT TO AD
$ds = ldap_connect ($AD_server );
if ($ds ) {
ldap_set_option ($ds , LDAP_OPT_PROTOCOL_VERSION , 3 ); // IMPORTANT
$r = ldap_bind ($ds , $AD_Auth_User , $AD_Auth_PWD ); //BIND

$ldaprecord [ "cn" ] = $CN ;
$ldaprecord [ "givenName" ] = $givenName ;
$ldaprecord [ "sn" ] = $SN ;
$ldaprecord [ "objectclass" ][ 0 ] = "top" ;
$ldaprecord [ "objectclass" ][ 1 ] = "person" ;
$ldaprecord [ "objectclass" ][ 1 ] = "organizationalPerson" ;
$ldaprecord [ "objectclass" ][ 2 ] = "user" ;
$ldaprecord [ "mail" ] = $mail ;
$ldaprecord [ "telephoneNumber" ] = $Phone ;
$ldaprecord [ "unicodepwd" ] = $newPassw ;
$ldaprecord [ "sAMAccountName" ] = $CN ;
$ldaprecord [ "UserAccountControl" ] = "512" ;
//This is to prevent the user from beeing disabled. -->
http : //support.microsoft.com/default.aspx?scid=kb;en-us;305144

$r = ldap_add ($ds , $dn , $ldaprecord );

} else {
echo "cannot connect to LDAP server at $AD_server ." ;
}

?>

This is code example creates a user i AD.
We use this on an internal web page to create
temporary users that kan access the wireless network.
We have a .pl script that deletes the users after 24H.

11 years ago

Once i"am having problmes to add attributes with boolean syntax (1.3.6.1.4.1.1466.115.121.1.7)

$["boolean_attr"]=true; //give me one warning, ldap_add(): Add: Invalid syntax

solved this by setting the value on this:

$["boolean_attr"]="TRUE";

hope this can helps.

16 years ago

In response to jharnett"s question about accounts disabled by default from ldap_add, we have found a solution.

The attribute userAccountControl contains a value that includes whether the account is disabled or enabled. The default for us is 546; when we changed that to 544 the account became enabled. Changing whatever value is in userAccountControl by 2 seems to enable or disable the account.

The following code worked for us to create a new user with an enabled account:

$adduserAD["userAccountControl"] = "544";

We just added this element to the above example"s array.

7 months ago

Create Group in Active Directory

$ds = ldap_connect ("IP-server/localhost" );
$base_dn = "CN=Group name,OU=Organization Unit,DC=Domain-name,DC=com" ; //distinguishedName of group

If ($ds ) {
// bind with appropriate dn to give update access
ldap_bind ($ds , , "some-password" );

//Add members in group
$member_array = array();
$member_array [ 0 ] = "CN=Administrator,OU=Organization Unit,DC=Domain-name,DC=com" ;
$member_array [ 1 ] = "CN=User,OU=Organization Unit,DC=Domain-name,DC=com" ;

$entry [ "cn" ] = "GroupTest" ;
$entry [ "samaccountname" ] = "GroupTest" ;
$entry [ "objectClass" ] = "Group" ;
$entry [ "description" ] = "Group Test!!" ;
$entry [ "member" ] = $member_array ;
$entry [ "groupType" ] = "2" ; //GroupType="2" is Distribution / GroupType="1" is Security

Ldap_add ($ds , $base_dn , $entry );

Ldap_close ($ds );
} else {
echo "Unable to connect to LDAP server" ;
}
?>

14 years ago

Another fun thing: ldap_add() doesn"t like arrays with empty members: so
array (
= "name"
= ""
= "value"
will yield a syntax error!

solve this with a simple peice of code:

foreach ($originalobject as $key => $value){
if ($value != ""){
$object[$key] = $value;
}
}

where $originalobject is the uncecked array and $object is the one without empty members.

19 years ago

Ldap_add() will only honour the $entry["attribute"][x]="value" *if there are multiple values for the attribute*. If there is only one attribute value, it *MUST* be entered as $entry["attribute"]="value" or ldap_add() sets the value for the attribute to be "Array" instead of what you put into $entry["attribute"].

Here is a little routine I wrote up to do this automatically. when you"re parsing the input, just use multi_add():
function multi_add ($attribute , $value )
{
global $entry ; // the LDAP entry you"re gonna add

If(isset($entry [ $attribute ]))
if(is_array ($entry [ $attribute ]))
$entry [ $attribute ][ count ($entry [ $attribute ])] = $value ;
else
{
$tmp = $entry [ $attribute ];
unset($entry [ $attribute ]);
$entry [ $attribute ][ 0 ] = $tmp ;
$entry [ $attribute ][ 1 ] = $value ;
}
else
$entry [ $attribute ] = $value ;
}
?>
multi_add() checks to see if there is already a value for the attribute. if not, it adds it as $entry[$attribute]=$value. If there is already a value for the attribute, it converts the attribute to an array and adds the multiple values correctly.

How to use it:
switch($form_data_name )
{
case "phone" : multi_add ("telephoneNumber" , $form_data_value ); break;
case "fax" : multi_add ("facsimileTelephoneNumber" , $form_data_value ); break;
case "email" : multi_add ("mail" , $form_data_value ); break;
...
}
?>
In the system I designed the form has pulldowns with names ctype1, ctype2, ctype3, etc. and the values are "fax, mail, phone...". The actual contact data (phone number, fax, email, etc) is contact1, contact2, contact3, etc. The user pulls down what the contact type is (phone, email) and then enters the data (number, address, etc.)

I use variable variables to fill the entry and skip blanks. Makes for a very clean form entry system. email me if you"re interested in it, as I think I"m outgrowing the size of note allowed here. :-)

6 years ago

I kept getting "Object Class Violation" when I tried adding posixAccount and shadowAccount as an objectclass. It turned out that these object classes had a lot of required fields that I was not adding. You may need to export a working user (if you have phpLDAPadmin) and see exactly what fields they have, then try to copy it exactly in the script. It also doesn"t hurt if you make everything an Array the first time around, you can fix those fields later.

In this section, you"ll learn how to search and retrieve data from the directory server, as well as add, modify, and delete entries.

ldap_search()

resource ldap_search (resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
The ldap_search() function offers a powerful means for searching the directory server pointed to by link_identifier. It will search to a depth of LDAP_SCOPE_SUBTREE, a value that can be set via the previously introduced function ldap_set_option(). By default, this value is set to search to an infinite depth, or through the entire scope of the tree as defined by the base_dn. The search filter, equivalent to a relational database query, is passed in via the filter parameter. Finally, you can specify exactly which attributes should be returned within the search results via the attributes parameter. The remaining four parameters are optional, and therefore in the interests of space, I"ll leave it as an exercise to you to learn more about them. Let"s consider an example:

"; } ldap_unbind($ad); ?> A sampling of the results follow: Gilmore, Jason (Columbus) Shoberg, Jon (Columbus) Streicher, Martin (San Francisco) Wade, Matt (Orlando)

Most of this is likely straightforward, save for the potentially odd way in which attribute values are referenced. All attribute rows are ultimately multi-dimensional arrays, with each attribute value referenced by a combination of row number, attribute name, and attribute array index. So, for example, even attributes such as "sn", the attribute name for the user"s last name, is an indexed array.

ldap_mod_add()

boolean ldap_mod_add(resource link_id, string dn, array entry)
Adding entries to the directory server is accomplished via the ldap_mod_add() function. A new entry is added simply by creating an array consisting of the attribute/value mappings intended to comprise the new row. This process is perhaps best explained with an example:

As is the case with all directory server tasks, be sure that the binding user has proper permissions to add the target data; otherwise, errors will occur.

ldap_mod_replace()

boolean ldap_mod_replace(resource link_id, string dn, array entry)
Modifying entry attributes is accomplished via the ldap_mod_replace() function. It operates exactly like ldap_add(), save for the added step of identifying the entry you"d like to modify. This is done by pointing to a very specific dn. Like ldap_add(), both a valid link identifier and an array consisting of the entries you"d like to update must be provided. An example follows, demonstrating how a user"s telephone number would be modified. In particular, take note of the very specific DN (pointing to my particular entry).

As is the case with all directory server tasks, be sure that the binding user has proper permissions to modify the target data; otherwise, unexpected errors will occur.

ldap_delete()

boolean ldap_delete(resource link_id, string dn)
Rounding out our survey of key PHP LDAP functions is ldap_delete(). This function is used to delete an existing entry. Like ldap_mod_replace(), a very specific DN must be provided to effect the deletion. The following example demonstrates how to remove the "Jason Gilmore" user entry from Active Directory:

As is the case with all directory server tasks, be sure that the binding user has proper permissions to delete the target data; otherwise, unexpected errors will occur.

Searching Active Directory via the Web

I always like to round out a tutorial with an applicable example that readers can immediately adapt to their own needs. In this tutorial, I"ll show you how to create a search interface capable of searching by name, location, or phone number. All you"ll need to do is modify the connection variables and base DN. To begin, let"s create the search interface, which will be saved as "search.html":

Search criteria:

Filter:

Figure 1 offers an example of what this search form would look like in the browser.

Figure 1. The Active Directory Search Form

Next, we"ll need to create the logic that effects the search. This short bit of code is shown here:

0) { for ($i=0; $i<$entries["count"]; $i++) { echo "

Name: ".$entries[$i]["displayname"]."
"; echo "Phone: ".$entries[$i]["telephonenumber"]."
"; echo "Email: ".$entries[$i]["mail"]."

"; } } else { echo "

No results found!

"; } ldap_unbind($ad); ?>

You can either change the action destination specified in the search interface, pointing it to a file consisting of the above script, or you can bundle it into the same file as the search interface, and use isset() and an if conditional to trigger execution in the case that the search submit button is depressed. Of course, you"ll want to add some additional data validation criteria prior to deploying such a script. Figure 2 offers a sampling of the search results.

Figure 2. Search Results

Conclusion

Although PHP has long been my primary language for developing Web applications, I"ve found Perl to be an integral part of my programmer"s toolkit. When working with directory servers, this sentiment is no different. Therefore, the next article is devoted to Perl/LDAP basics. As was the case with this article, all examples are specific to Microsoft"s Active Directory, although you should be able to easily apply them to any directory server implementation. We"ll round out that article with an example demonstrating how to create statically cached Web-based user directories using a Perl script and CRON (or Windows Task Scheduler).

I welcome questions and comments! E-mail me at [email protected] . I"d also like to hear more about your experiences integrating Microsoft and Open Source technologies!

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) is an Internet application developer for the Fisher College of Business. He"s the author of the upcoming book, PHP 5 and MySQL: Novice to Pro, due out by Apress in 2004. His work has been featured within many of the computing industry"s leading publications, including Linux Magazine, O"Reillynet, Devshed, Zend.com, and Webreview. Jason is also the author of A Programmer"s Introduction to PHP 4.0 (453pp., Apress). Along with colleague Jon Shoberg, he"s co-author of "Out in the Open," a monthly column published within Linux magazine.

IT Solutions Builder TOP IT RESOURCES TO MOVE YOUR BUSINESS FORWARD

Работаем с AD на PHP

Чтение данных. Часть 1. Подключение к AD, запрос и обработка данных

Серия контента:

Для выполнения основных операций по работе с AD, таких как добавление или удаление пользователя, изменение данных или членства в группах, и в особенности для массовых операций (например, сформировать список всех пользователей по отделам) вовсе не обязательно изучать Visual Basic или PowerShell - для этого достаточно знания PHP (а также наличия пользователя с необходимыми правами).

Часто используемые сокращения:

  • AD - Active Directory (служба каталогов);
  • LDAP - облегченный протокол доступа к каталогу (lightweight directory access protocol);
  • DN - отличительное имя (distinguished name).

В первых частях цикла, опубликованных в июне месяце (, , ) рассказывалось о том, как прочитать данные сервера AD, обращаясь к нему как к обычному LDAP-серверу с помощью стандартной программы ldapsearch и скрипта, написанного на языке Bourne Shell. Надо сказать, Bourne Shell не слишком приспособлен для такой работы: даже для достаточно простой операции формирования текстового файла из двух колонок приходится идти на весьма нетривиальные ходы. Поэтому совершенно естественно попробовать переписать его на языке высокого уровня, например, на PHP.

Конфигурационный файл

Для работы скрипта используется практически тот же самый конфигурационный файл. Его содержание приведено в Листинге 1.

Листинг 1. Конфигурационный файл скрипта phpldapread.php
#LDAP сервер для подключения ldap_server=10.54.200.1 #Base DN для подключения ldap_basedn="dc=shelton,dc=int" #Bind DN для подключения [email protected] #Пароль для пользователя, от имени которого будет выполняться подключение ldap_password="cXdlcnR5YXNkZgo 1" #Фильтр отбора записей. Он означает: отобрать объекты типа Пользователь, # у которых не установлено свойство "Заблокировать учетную запись" ldap_common_filter="(&(!(userAccountControl:1.2.840.113556.1.4.803:=2)) (sAMAccountType=805306368))" #Игнорировать перечисленных пользователей - это системные объекты ignore_list="SQLAgentCmdExec,SMSService,SMSServer_001, wsus" #Каталог, куда будет сохранен файл etcdir=/tmp #Имя файла со списком sarglist=sargusers

Зависимости, вспомогательные функции

Для работы скрипта потребуются дополнительные компоненты pear-Config и pear-Console_Getopt, а также расширение языка php-ldap. Pear-Config потребуется для чтения конфигурационного файла, pear-Console_Getopt - для разбора параметров командной строки. Надо сказать, рассматривается не весь скрипт: такие вопросы, как чтение конфигурационного файла, отображение справки или разбор командной строки являются вопросами уже достаточно хорошо описанными, поэтому соответствующие функции будут опущены, полную версию скрипта можно скачать с . Рассмотрено будет только то, что непосредственно относится к чтению данных из AD, как сервера LDAP, и некоторые нестандартные вспомогательные функции.

Функция обратного преобразования пароля приведена в Листинге 2. Вся роль так называемой "защиты" - предотвратить случайную утечку (ту, что называется eyedropper) и не более того.

Листинг 2. Функция обратного преобразования пароля.
/* * Обратное преобразование пароля * @param string $converted преобразованный пароль * @return string $passwd пароль в текстовой форме */ function demux_passwd($converted) { $_conved = explode(" ", $converted); $_passwd = ""; if ($_conved != 0) for (;$_conved != 0; $_conved--) { $_conved = $_conved . "="; } $_passwd = base64_decode($_conved); return rtrim($_passwd); }

Ничего особо интересного, конечно же, здесь нет: как уже было сказано в предыдущих частях, в конфигурационном файле хранится пароль, преобразованный в base64, заполнители отброшены и заменены числом. Эта функция выполняет обратное преобразование.

Функция перекодировки из UTF-8 в KOI8-R приведена в Листинге 3. Необходимость в этой функции возникает вследствие того, что консоль во FreeBSD не использует UTF-8.

Листинг 3. Функция перекодировки строки из UTF-8 в KOI8-R
/* * Перекодировать строку из UTF-8 в KOI8-R * @param string $source строка в кодировке UTF-8 * @return string $dest строка в кодировке KOI8-R */ function _from_utf8($source) { $converted = iconv("UTF-8", "KOI8-R", $source); return($converted); }

Кроме того, используется совершенно неинтересная функция safe_logger, в задачу которой входит вывод сообщений в лог или на консоль с завершением или без завершения работы скрипта. Все эти функции сохранены в файле utils.php.

Подключение к AD

Для подключения к AD используется функция ldap_server_connect, приведенная в Листинге 4. Функция выполняет все операции по подключению и возвращает идентификатор соединения для работы с сервером. Функция сохранена в отдельный файл ldapquery.php

Листинг 4. Функция подключения к серверу AD
require_once $PATH_LIB."/utils.php"; /* * Подключение к серверу LDAP * @param array $_config массив параметров конфигурации * @return resource $ldapconn идентификатор соединения с LDAP-сервером */ function ldap_server_connect($_config) { // Получить пароль в текстовом виде $_ldap_pwd = demux_passwd($_config["root"]["ldap_password"]); // Установить соединение с сервером if (!$ldapconn = ldap_connect($_config["root"]["ldap_server"])) safe_logger(sprintf("Невозможно подключиться к LDAP-серверу %s", $_config["root"]["ldap_server"]), "DIE"); // Для подключения к AD Windows 2003 и выше нужно установить эти опции ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0); // Авторизоваться на сервере ldap_bind($ldapconn, $_config["root"]["ldap_binddn"], $_ldap_pwd); return $ldapconn; }

На что хотелось бы обратить внимание здесь.

Во-первых, опции LDAP_OPT_PROTOCOL_VERSION ("версия протокола") и LDAP_OPT_REFERRALS ("отключить реферальные ссылки") должны быть обязательно установлены соответственно в 3 и 0 - без них можно увидеть странное: авторизация на сервере пройдет, но любой поиск будет возвращать ровно нуль записей.

Во-вторых, Bind DN должен быть задан в точности как в конфигурационном файле и никаким другим образом. Неверным будет в том числе и указание полного DN.

Запрос данных из AD

Для запроса данных из AD разработана отдельная функция ldap_data_query. Сделано это в основном потому, что данные, содержащие не-ASCII символы (а таких в нормальном AD большинство), хранятся в кодировке UTF-8. Поскольку консоль FreeBSD ограниченно поддерживает UTF-8, пришлось пойти на некоторые преобразования.

Отбор данных из AD проводится функцией ldap_search, которая принимает в числе других параметров одномерный массив с атрибутами, которые необходимо получить. Но для того, чтобы указать, следует ли перекодировать значение этого атрибута, функция получает двумерный массив, в котором каждый элемент сам есть массив, состоящий из элементов с индексами name и recode.

Вид массива атрибутов, который получает на входе функция, показан в Листинге 5 (частично).

Листинг 5. Массив параметров, передаваемый функции запроса данных.
array(2) { => array(2) { ["name"]=> string(2) "cn" ["recode"]=> string(4) "true" } ... }

Собственно функция запроса данных приведена в Листинге 6.

Листинг 6. Функция запроса данных из AD.
require_once $PATH_LIB."/utils.php"; require_once $PATH_LIB."/ldapconnect.php"; /* * Запросить данные с сервера LDAP * @param array $_config Массив с конфигурационными данными * @param resource $ldapconn Идентификатор подключения к серверу LDAP * @param array $attribute Массив атрибутов для запроса из LDAP * @return array $ldapdata Данные с сервера LDAP */ function ldap_data_query($_config, $ldapconn, $attribute) { $oneadd = array(); $myrecode = array(); $myattrs = array(); // Для запроса данных мы создаем одномерный массив foreach ($attribute as $oneattr) $myattrs = $oneattr["name"]; // Запросим данные, используя общий фильтр отбора из конфигурационного файла $result = ldap_search($ldapconn, $_config["root"]["ldap_basedn"], $_config["root"]["ldap_common_filter"], $myattrs); // Прочитаем все отобранные записи $info = ldap_get_entries($ldapconn, $result); // Выведем их количество в лог safe_logger(sprintf("Read %d records from server %s", $info["count"], $_config["root"]["ldap_server"]), ""); // Создадим двумерный массив с выходными данными // Каждый элемент массива есть массив, в элементах которого ключ - имя атрибута, // а данные - значение атрибута; перекодированные, если надо for ($i = 0; $i < $info["count"]; $i++) { for ($j = 0, $k = count($attribute); $j < $k; $j++) { $myattr = $attribute[$j]["name"]; if (isset($info[$i][$myattr])) { if ($attribute[$j]["recode"] == "true") $myrecode[$myattr] = _from_utf8($info[$i][$myattr]); else $myrecode[$myattr] = $info[$i][$myattr]; } else $myrecode[$myattr] = ""; $oneadd[$i] = $myrecode; } } return $oneadd; }

Из двумерного массива параметров формируется одномерный для функции ldap_search потом запрашиваются данные. Данные возвращаются в виде массива, каждый элемент которого имеет вид, приведенный в Листинге 7.

Листинг 7. Один элемент массива данных, возвращаемого функцией ldap_get_entries.
=> array(6) { ["cn"]=> array(2) { ["count"]=> int(1) => string(13) "Administrator" } => string(2) "cn" ["samaccountname"]=> array(2) { ["count"]=> int(1) => string(13) "Administrator" } => string(14) "samaccountname" ["count"]=> int(2) ["dn"]=> string(43) "CN=Administrator,CN=Users,DC=shelton,DC=net" }

Как видно, это даже не двумерный, а трехмерный массив. На первом уровне - запрошенные данные, на втором - атрибуты одного объекта, на третьем - строки многострочного атрибута, которым на всякий случай считаются все строковые атрибуты. Также в каждом элементе первого уровня присутствует элемент второго уровня dn, который содержит полный DN данного объекта - это нам очень пригодится в дальнейшем. Выходной же массив куда проще, вид одного элемента приведен на Листинге 8. Здесь нарочно использован объект с не-ASCII данными, чтобы показать тот факт, что данные были перекодированы.

Листинг 8. Элемент выходного массива.
=> array(2) { ["cn"]=> string(11) "Просто Юзер" ["samaccountname"]=> string(10) "prostouser" }

Для чего так подробно рассматриваются входные и выходные данные этой функции? Потому что фактически вся работа основного скрипта (который будет рассмотрен в следующей части статьи) будет сведена к подготовке ее вызова и последующей обработке сформированного ею массива.

Заключение

Как видно из данной статьи, PHP значительно упрощает работу с LDAP-сервером, позволяя отказаться от зубодробительных конструкций, связанных с хранением данных во временных файлах, заменяя их куда более удобным представлением массивов в памяти, позволяя "на ходу" перекодировать в другую кодовую страницу, и значительно облегчая отладку скрипта.



Понравилась статья? Поделитесь с друзьями!