source: trunk/contactcenter/inc/class.bo_ldap_manager.inc.php @ 1419

Revision 1419, 18.3 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #421 - Ajuste no tratamento do referral para catalogo externo

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2  /***************************************************************************\
3  * eGroupWare - Contacts Center                                              *
4  * http://www.egroupware.org                                                 *
5  * Written by:                                                               *
6  *  - Raphael Derosso Pereira <raphaelpereira@users.sourceforge.net>         *
7  * ------------------------------------------------------------------------- *
8  *  This program is free software; you can redistribute it and/or modify it  *
9  *  under the terms of the GNU General Public License as published by the    *
10  *  Free Software Foundation; either version 2 of the License, or (at your   *
11  *  option) any later version.                                               *
12  \***************************************************************************/
13
14       
15        /*
16                This class is responsible for the LDAP control/generic functions and for
17                configuration gathering
18        */
19        include_once('class.Thread.inc.php');
20
21        class bo_ldap_manager
22        {
23               
24                var $srcs;
25
26               
27                function bo_ldap_manager ()
28                {
29                        if (!($this->srcs = $GLOBALS['phpgw']->session->appsession('bo_ldap_manager.srcs','contactcenter')))
30                        {
31                                $c = CreateObject('phpgwapi.config','contactcenter');
32                                $data = $c->read_repository();
33                               
34                                if (!$data or $data['cc_global_source0'] !== 'ldap')
35                                {
36                                        $this->srcs = null;
37                                        return;
38                                }
39                               
40                                $this->srcs = array(
41                                        1 => array(
42                                                'name'   => $data['cc_catalog_name'],
43                                                'host'   => $data['cc_ldap_host0'],
44                                                'dn'     => $data['cc_ldap_context0'],
45                                                'acc'    => $data['cc_ldap_browse_dn0'],
46                                                'pw'     => $data['cc_ldap_pw0'],
47                                                'obj'    => 'phpgwAccount',
48                                                'branch' => strtolower('ou'),
49                                                'visible' => $data['cc_ldap_query_automatic']
50                                        )
51                                );
52                        }
53                }
54
55                function new_ldap_source ( $source_name, $charset, $host, $port, $dn_root, $dn_admin, $admin_pass, $contact_objectclass )
56                {
57                }
58       
59                /*
60               
61                        @function get_all_ldap_sources
62                        @abstract Returns an array containing all LDAP sources informations
63                        @author Raphael Derosso Pereira
64               
65                        @return array All LDAP information
66                                $return = array(
67                                        <id_source> => array(
68                                                'host' => (string),
69                                                'dn'   => (string),
70                                                'acc'  => (string),
71                                                'pw'   => (string)   
72                                        ),
73                                        ...
74                                )
75                               
76                        TODO: Return multiple sources...
77                */
78                function get_all_ldap_sources (  )
79                {
80                        return $this->srcs;
81                }
82               
83                /*
84                * @function get_external_ldap_sources
85                * @author Mário César Kolling <mario.kolling@serpro.gov.br>
86                * @abstract returns an array with the external sources
87                * @return (array) the external sources
88                */
89
90                function get_external_ldap_sources()
91                {
92                        include(PHPGW_INCLUDE_ROOT . '/contactcenter/setup/external_catalogs.inc.php' );
93                        //include('external_catalogs.inc.php' );
94                        return $external_srcs;
95                }
96
97                /*
98                 * @function get_ldap_fields_association
99                 * @abstract get the fields associantion for ldap source
100                 * @return an array with attribute mappings
101                 */
102                function get_ldap_fields_association ( $id_source )
103                {
104                       
105                        $op_iop = array(
106                                'contact.uidnumber'                                => array('uidNumber'),
107                                'contact.id_contact'               => array('dn'),
108                                'contact.photo'                    => array('jpegPhoto'),
109                                'contact.prefixes.prefix'          => false,
110                                'contact.alias'                    => array('alias'),
111                                'contact.given_names'              => array('givenName'),
112                                'contact.family_names'             => array('sn'),
113                                'contact.names_ordered'            => array('cn'),//,'displayName'),
114                                'contact.suffixes.suffix'          => false,
115                                'contact.birthdate'                => false,
116                                'contact.sex'                      => false,
117                                'contact.pgp_key'                  => false,
118                                'contact.notes'                    => false,
119                                'contact.mail_forwarding_address' => array('mailForwardingAddress'),
120                                'contact.account_type' => array('phpgwAccountType'),
121                'contact.account_status'           => array('phpgwAccountStatus'),
122                'contact.account_visible'          => array('phpgwAccountVisible'),
123                                'contact.object_class'             => array('objectClass'),
124                                'contact.business_info.title'      => array('title'),
125                                'contact.business_info.department' => array('ou'),
126                                'contact.company.company_name'     => array('o'),
127                                'contact.company.company_notes'    => array('businessCategory'),
128                               
129                                'contact.contact_related.names_ordered' => 'contact.contact_related.typeof_relation.contact_relation_name',
130                                'contact.contact_related.typeof_relation.contact_relation_name' =>  array(
131                                        'manager'   => array('manager'),
132                                        'secretary' => array('secretary')
133                                ),
134                               
135                                'contact.address.address1'         => 'contact.address.typeof_address.contact_address_type_name',
136                                'contact.address.typeof_address.contact_address_type_name' => array(
137                                        'home' => array('street', 'st', 'postalAddress', 'homePostalAddress'),
138                                ),
139                               
140                                'contact.address.postal_code'      => 'contact.address.typeof_address.contact_address_type_name',
141                                'contact.address.typeof_address.contact_address_type_name' => array(
142                                        'home' => array('PostalCode'),
143                                ),
144                               
145                                'contact.address.city.city_name'   => 'contact.address.typeof_address.contact_address_type_name',
146                                'contact.address.typeof_address.contact_address_type_name' => array(
147                                        'home' => array('l'),
148                                ),
149                               
150                                'contact.address.city.state.state_name'       => 'contact.address.typeof_address.contact_address_type_name',
151                                'contact.address.typeof_address.contact_address_type_name' => array(
152                                        'home' => false,
153                                ),
154                               
155                                'contact.address.city.country.id_country'     => 'contact.address.typeof_address.contact_address_type_name',
156                                'contact.address.typeof_address.contact_address_type_name' => array(
157                                        'home' => array('c')
158                                ),
159                               
160                                'contact.connection.connection_value'         => 'contact.connection.typeof_connection.contact_connection_type_name',
161                                'contact.connection.typeof_connection.contact_connection_type_name' => array (
162                                        'email'  => array('mail'),
163                                        'phone'  => array('telephoneNumber'),
164                                        'mobile' => array('mobile'),
165                                        'pager'  => array('pager'),
166                                        'fax'    => array('facsimileTelephoneNumber'),
167                                        'telex'  => array('telexNumber')
168                                ),
169                        );
170                       
171                        return $op_iop;
172                }
173
174                /*
175                 * @function get_external_ldap_fields_association
176                 * @author Mário César Kolling <mario.kolling@serpro.gov.br>
177                 * @abstract get the fields association for an external ldap_source
178                 * @return an array with attribute mappings
179                 */
180                function get_external_ldap_fields_association ( $id_source )
181                {
182                        include(PHPGW_INCLUDE_ROOT . '/contactcenter/setup/external_catalogs.inc.php' );
183                        //include('external_catalogs.inc.php' );
184                        return $external_mappings[$id_source];
185                }
186
187                /*
188                 * @function test_connection
189                 * @author Mário César Kolling <mario.kolling@serpro.gov.br>
190                 * @abstract Test if we can bind to a ldap server in a reasonable time
191                 * @param (string) $host ldap server's hostname
192                 * @param (string) $account ldap bind dn
193                 * @param (string) $password a bind dn's password
194                 * @return (array) an array with the answer from the subprocess, null otherwise
195                 */
196                function test_connection($host, $account, $password, $timeout = 5)
197                {
198                        //opens a subprocess for nonblocking bind
199                        $tsearch = Thread::Create('class.ldap_assync.inc.php', array('host'     => $host,
200                                                                                                                                'account'       => $account,
201                                                                                                                                'password'      => $password
202                                                                                                                                )
203                        );
204
205                        // It's problably more efficient to let method readResponse control the timeout through
206                        // stream_select native timeout.
207                        $response = NULL;
208                        for ($i = 0; $i < $timeout; $i++)
209                        {
210                                if ($tsearch->isActive())
211                                {
212                                        sleep(1);
213                                        if (($response = $tsearch->readResponse()) !== NULL)
214                                        {
215                                                $tsearch->close();
216                                                return $response;
217                                        }
218
219                                }
220                                else
221                                {
222                                        $response = $tsearch->readResponse();
223                                        break;
224                                }
225                        }
226
227                        $tsearch->close();
228                        return null;
229                }
230
231                /*!
232               
233                        @function get_ldap_tree
234                        @abstract Returns the LDAP tree corresponding to the specified level
235                        @author Raphael Derosso Pereira
236                       
237                        @param (integer) $id_source The ID of the LDAP source
238                       
239                        @param (string)  $context The context to be used as root branch
240                               
241                        @param (boolean) $recursive Make it a recursive construction.
242                                CAUTION! This is EXTREMELY SLOW on large LDAP databases,
243                                specially when they're not indexed
244                */             
245                function get_ldap_tree($id_source, $context = false, $recursive = false)
246                {
247                        if (!$this->srcs[$id_source])
248                        {
249                                return null;
250                        }
251                       
252                        $ldap = $GLOBALS['phpgw']->common->ldapConnect($this->srcs[$id_source]['host'], $this->srcs[$id_source]['acc'],$this->srcs[$id_source]['pw'], true);
253                        if (!$ldap)
254                        {
255                                return false;
256                        }
257                       
258                        if ($recursive)
259                        {
260                                $tree = $this->get_ldap_tree_recursive($ldap, $context, $this->srcs[$id_source]['obj'],$this->srcs[$id_source]['branch']);
261                                $tree['recursive'] = true;
262
263                                return $tree;
264                        }
265                       
266                        return $this->get_ldap_tree_level($id_source, $ldap, $context, $this->srcs[$id_source]['obj'],$this->srcs[$id_source]['branch']);
267                }
268                // SERPRO
269
270                /*!
271
272                        @function get_external_ldap_tree
273                        @abstract Returns the LDAP external tree corresponding to the specified level
274                        @author Mário César Kolling <mario.kolling@serpro.gov.br>
275                        @param (integer) $id_source The ID of the external LDAP source
276                        @param (string)  $context The context to be used as root branch
277                        @param (boolean) $recursive Make it a recursive construction.
278                                CAUTION! This is EXTREMELY SLOW on large LDAP databases,
279                                specially when they're not indexed
280                */
281                function get_external_ldap_tree($id_source, $context = false, $recursive = false)
282                {
283
284
285                        include(PHPGW_INCLUDE_ROOT . '/contactcenter/setup/external_catalogs.inc.php' );
286                        //include('external_catalogs.inc.php' );
287                       
288                        if (!$external_srcs[$id_source])
289                        {
290                                return null;
291                        }
292                       
293                        // calls test_connection first. If succeeded continue, return error message otherwise.
294                        if (!($response = $this->test_connection($external_srcs[$id_source]['host'], $external_srcs[$id_source]['acc'], $external_srcs[$id_source]['pw'], 10)))
295                        {
296                                return array(
297                                        'msg'           =>      lang("Catalog %1 temporarily unavailable. Please try again later!", $external_srcs[$id_source]['name']),
298                                        'timeout'       =>      'true'
299                                );
300                        }
301
302                        $ldap = $GLOBALS['phpgw']->common->ldapConnect($external_srcs[$id_source]['host'], $external_srcs[$id_source]['acc'],$external_srcs[$id_source]['pw'], false);
303                        if (!$ldap)
304                        {
305                                return false;
306                        }
307
308                        // Option recursive commented out
309                        /*
310                        if ($recursive)
311                        {
312                                $tree = $this->get_ldap_tree_recursive($ldap, $context, $this->srcs[$id_source]['obj'],$this->srcs[$id_source]['branch']);
313                                $tree['recursive'] = true;
314
315                                return $tree;
316                        }
317                        */
318
319                        return $this->get_ldap_tree_level($id_source, $ldap, $context, $external_srcs[$id_source]['obj'],$external_srcs[$id_source]['branch'], 1);
320                }
321
322                /*!
323
324                        THIS FUNCTION IS NOT TESTED AND IS PROBABLY BROKEN!
325                        I WILL CORRECT IT IN THE NEAR FUTURE
326
327                */
328                function get_ldap_tree_recursive($resource, $context, $objectClass)
329                {
330                        $filter = '(!(objectClass='.$objectClass.'))';
331                        $result_res = ldap_list($resource, $context, $filter);
332
333                        if ($result_res === false)
334                        {
335                                return null;
336                        }
337                       
338                        $count = ldap_count_entries($resource,$result_res);
339                        if ( $count == 0 )
340                        {
341                                $filter = 'objectClass='.$objectClass;
342                                $result_res2 = ldap_list($resource, $context, $filter);
343                                $entries_count = ldap_count_entries($resource, $result_res2);
344
345                                if ($result_res2 !== false && $entries_count > 0)
346                                {
347                                        return $entries_count;
348                                }
349                                else
350                                {
351                                        return null;
352                                }
353                        }
354                       
355                        $entries = ldap_get_entries($resource, $result_res);
356                       
357                        for ($i = 0; $i < $entries['count']; $i++)
358                        {
359                                $subtree = $this->get_ldap_tree_recursive($resource, $entries[$i]['dn'], $objectClass);
360                               
361                                $dn_parts=ldap_explode_dn($entries[$i]['dn'],1);
362                               
363                                if ($subtree !== null and is_array($subtree))
364                                {
365                                        $tree[$i]['name'] = $dn_parts[0];
366                                        $tree[$i]['type'] = 'catalog_group';
367                                        $tree[$i]['recursive'] = true;
368                                        $tree[$i]['sub_branch'] = $subtree;
369                                }
370                                else if (is_int($subtree) and $subtree !== null)
371                                {
372                                        $tree[$i] = array(
373                                                'name'       => $dn_parts[0],
374                                                'type'       => 'catalog',
375                                                'class'      => 'global_contact_manager',
376                                                'icon'       => 'share-mini.png',
377                                                'value'      => $entries[$i]['dn'],
378                                                'sub_branch' => false
379                                        );
380                                }
381                        }
382
383                        if (is_array($tree))
384                        {
385                                return $tree;
386                        }
387                        else
388                        {
389                                return null;
390                        }
391                }
392               
393                function get_ldap_referrals($ds, $dn, $filter) {
394                       
395                        ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
396                        ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
397                       
398                        if ($ds) {
399                            ldap_bind($ds);
400                                $sr=ldap_list($ds,$dn, $filter);                   
401                                $ref = ldap_first_reference($ds, $sr);
402                                $array_referral = array();
403                                $idx = 0;
404                               
405                                 while ($ref) {
406                                        $array_referral[$idx++] = ldap_get_dn($ds, $ref);
407                                        $ref = ldap_next_reference($ds, $ref);
408                                }
409                                return $array_referral;
410                        }
411                        else
412                                return false;
413                       
414                       
415                }
416
417                function get_ldap_sub_branches_referrals($ds, $dn, $filter) {
418                       
419                        $referral = $this -> get_ldap_referrals($ds, $dn, $filter);
420                        $sub_branches = array();
421                       
422                        for($i = 0; $i <count($referral); $i++) {
423                                $dn = str_replace("??base","",preg_replace('!^(ldap://[^/]+)/(.*$)!', '\\2', $referral[$i]));
424                                $dn = explode(",",$dn);                         
425                                $dn = strtoupper(str_replace("ou=", "",$dn[0]));
426                                $dn = str_replace("DC=", "",$dn);
427                                                                                                                                                                               
428                                $sub_branch = array(
429                                                                                        'name' => $dn,
430                                                                'type' => 'unknown',
431                                                                'value' => $referral[$i],
432                                                                'sub_branch' => false           
433                                                                                );                                                                                                                     
434                                $sub_branches[$i] = $sub_branch;                       
435                        }
436                        return $sub_branches;
437                }
438               
439
440                function translate_accentuation($text)
441                {
442                        /*
443                         * Esta operação resolve o problema causado pela conversão de caracteres acentuados realizada
444                         * pela função ldap_explode_dn().
445                         */
446
447                        return utf8_decode(preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $text));
448                }
449
450                function get_ldap_tree_level($id_source, $resource, $context, $objectClass, $branch_dn, $external = 0)
451                {
452                                               
453                        /*
454                         * TODO: Search timeouts
455                         */
456                       
457                        $dn_parts = ldap_explode_dn($context,1);
458                        //$filter = '(!(objectClass='.$objectClass.'))';
459                        // Don't show OU's whith phpgwAccountVisible equal to '-1'
460                        if ($external)
461                        {
462                                // external source: get all organizationalUnits
463                                $filter = '(objectClass=organizationalUnit)';
464                        }
465                        else
466                        {
467                                // get any objectClass except the objectClass used for the source
468                                // and whose attribute phpgwAccountVisible value is different from -1
469                                $filter = '(&(!(objectClass='.$objectClass.')) (!(phpgwAccountVisible=-1)))';
470                                $context = preg_replace("/dc=(.*)/i",$this->srcs[$id_source]['dn'],$context);   
471                        }
472                       
473                        $result_res = @ldap_list($resource,  $context, $filter, array(), 0, 0);
474                        if (!$result_res)
475                                return null;
476                       
477                        @ldap_sort($resource, $result_res, 'ou');
478                        $count = ldap_count_entries($resource,$result_res);
479                       
480                        if ( $count == 0 )
481                        {
482                                $filter = '(objectClass='.$objectClass.')';
483                                // Get only one attribute of the source's objectClass
484                                $result_res2 = @ldap_list($resource, $context, $filter, Array('cn'), 0, 1);
485                                if (!$result_res2)
486                                        return null;
487
488                                $entries_count = ldap_count_entries($resource, $result_res2);
489
490                                if ($result_res2 !== false && $entries_count > 0)
491                                {
492                                        return array(
493                                                'name'       => $this->translate_accentuation($dn_parts[0]),
494                                                'type'       => 'catalog',
495                                                'class'      => 'bo_global_ldap_catalog',
496                                                // Pass the variable $external as a parameter to the constructor
497                                                'class_args' => array($id_source, $context, $external),
498                                                'icon'       => 'globalcatalog-mini.png',
499                                                'value'      => $context,
500                                                'sub_branch' => false
501                                        );
502                                }
503                                else
504                                {
505                                        return array(
506                                                'name' => $this->translate_accentuation($dn_parts[0]),
507                                                'type' => 'empty'
508                                        );
509                                }
510                        }
511                       
512                        $sub_branch_found = false;
513                        $i = 0;
514                        for ($entry = ldap_first_entry($resource, $result_res);
515                             $entry != false;
516                             $entry = ldap_next_entry($resource, $entry))
517                        {
518                                $dn = ldap_get_dn($resource, $entry);
519                                $dn_parts_1 = ldap_explode_dn($dn,1);
520                                $dn_parts_full = ldap_explode_dn($dn,0);
521                                list($group) = explode('=',$dn_parts_full[0]);
522
523                                //Faz a comparação do branch como case insensitive
524                                if (strtolower($group) == strtolower($branch_dn) or $branch_dn === 'all')
525                                {
526                                        $tree['sub_branch'][$i] = array(
527                                                'name'  => $this->translate_accentuation($dn_parts_1[0]),
528                                                'type'  => 'unknown',
529                                                'value' =>  $dn,
530                                                'sub_branch' => false
531                                        );
532                                        $sub_branch_found = true;
533                                }
534                                $i++;
535                        }
536                                               
537                        $filter = 'objectClass='.$objectClass;
538                        $result_res2 = @ldap_list($resource, $context, $filter, Array('cn'), 0, 1);
539                        $entries_count = ldap_count_entries($resource, $result_res2);
540
541                        if ($result_res2 !== false && $entries_count > 0 && $sub_branch_found)
542                        {
543                                $tree['name']       = $this->translate_accentuation($dn_parts[0]);
544                                $tree['type']       = 'mixed_catalog_group';
545                                $tree['class']      = 'bo_global_ldap_catalog';
546                                // Pass the variable $external as a parameter to the constructor
547                                $tree['class_args'] = array($id_source,$context,$external);
548                                $tree['icon']       = 'globalcatalog-mini.png';
549                                $tree['value']      = $context;
550                        }
551                        elseif ($result_res2 !== false && $entries_count > 0 && !$sub_branch_found)
552                        {
553                                return array(
554                                        'name'       => $this->translate_accentuation($dn_parts[0]),
555                                        'type'       => 'catalog',
556                                        'class'      => 'bo_global_ldap_catalog',
557                                        // Pass the variable $external as a parameter to the constructor
558                                        'class_args' => array($id_source, $context,$external),
559                                        'icon'       => 'globalcatalog-mini.png',
560                                        'value'      => $context,
561                                        'sub_branch' => false
562                                );
563                        }
564                        else
565                        {
566                                $tree['name']       = $this->translate_accentuation($dn_parts[0]);
567                                $tree['type']       = 'catalog_group';
568                                $tree['class']      = 'bo_catalog_group_catalog';
569                                // Pass the variable $external as a parameter to the constructor
570                                $tree['class_args'] = array('$this', '$this->get_branch_by_level($this->catalog_level[0])', $external);
571                                $tree['value']      = $context;
572                                $tree['ldap']       = array('id_source' => $id_source, 'context' => $context);
573                        }
574                       
575                        usort($tree['sub_branch'], array($this, "compareTreeNodes"));
576                        return $tree;
577                }
578
579                function compareTreeNodes($a, $b)       {
580                                               
581                        return strnatcasecmp($a['name'], $b['name']);
582                }       
583
584        }
585?>
Note: See TracBrowser for help on using the repository browser.