source: branches/2.2/contactcenter/inc/class.bo_ldap_manager.inc.php @ 3262

Revision 3262, 19.6 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1319 - Possibilidade de erro na pesquisa do ContacCenter?

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