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

Revision 284, 18.9 KB checked in by rafaelraymundo, 16 years ago (diff)

Vide Trac - #197, #166, #198, #199

  1. Correção de problema na leitura do arquivo configuração.
  2. Permissão do click2dial também no contactcenter.
  3. Visualização de matricula, e nro celular no resultado da pesquisa(se estiverem populados)
  4. Adicionada a leitura a Catálogos Externos
  • 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                function bo_ldap_manager ()
27                {
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'    => 'inetOrgPerson',
48                                                'branch' => strtolower('ou')
49                                        )
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.id_contact'               => array('dn'),
107                                'contact.photo'                    => array('jpegPhoto'),
108                                'contact.prefixes.prefix'          => false,
109                                'contact.alias'                    => array('alias'),
110                                'contact.given_names'              => array('givenName'),
111                                'contact.family_names'             => array('sn'),
112                                'contact.names_ordered'            => array('cn'),//,'displayName'),
113
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'), // Setor do empregado...
126                                'contact.business_info.empNumber'  => array('employeeNumber'), // Matricula do empregado
127                                'contact.company.company_name'     => array('o'),
128                                'contact.company.company_notes'    => array('businessCategory'),
129
130                                'contact.contact_related.names_ordered' => 'contact.contact_related.typeof_relation.contact_relation_name',
131                                'contact.contact_related.typeof_relation.contact_relation_name' =>  array(
132                                        'manager'   => array('manager'),
133                                        'secretary' => array('secretary')
134                                ),
135
136                                'contact.address.address1'         => 'contact.address.typeof_address.contact_address_type_name',
137                                'contact.address.typeof_address.contact_address_type_name' => array(
138                                        'home' => array('street', 'st', 'postalAddress', 'homePostalAddress'),
139                                ),
140
141                                'contact.address.postal_code'      => 'contact.address.typeof_address.contact_address_type_name',
142                                'contact.address.typeof_address.contact_address_type_name' => array(
143                                        'home' => array('PostalCode'),
144                                ),
145
146                                'contact.address.city.city_name'   => 'contact.address.typeof_address.contact_address_type_name',
147                                'contact.address.typeof_address.contact_address_type_name' => array(
148                                        'home' => array('l'),
149                                ),
150
151                                'contact.address.city.state.state_name'       => 'contact.address.typeof_address.contact_address_type_name',
152                                'contact.address.typeof_address.contact_address_type_name' => array(
153                                        'home' => false,
154                                ),
155
156                                'contact.address.city.country.id_country'     => 'contact.address.typeof_address.contact_address_type_name',
157                                'contact.address.typeof_address.contact_address_type_name' => array(
158                                        'home' => array('c')
159                                ),
160
161                                'contact.connection.connection_value'         => 'contact.connection.typeof_connection.contact_connection_type_name',
162                                'contact.connection.typeof_connection.contact_connection_type_name' => array (
163                                        'email'  => array('mail'),
164                                        'phone'  => array('telephoneNumber'),
165                                        'mobile' => array('mobile'),
166                                        'pager'  => array('pager'),
167                                        'fax'    => array('facsimileTelephoneNumber'),
168                                        'telex'  => array('telexNumber')
169                                ),
170                        );
171
172                        return $op_iop;
173
174                }
175
176                /*
177                 * @function get_external_ldap_fields_association
178                 * @author Mário César Kolling <mario.kolling@serpro.gov.br>
179                 * @abstract get the fields association for an external ldap_source
180                 * @return an array with attribute mappings
181                 */
182                function get_external_ldap_fields_association ( $id_source )
183                {
184                        include(PHPGW_INCLUDE_ROOT . '/contactcenter/setup/external_catalogs.inc.php' );
185                        //include('external_catalogs.inc.php' );
186                        return $external_mappings[$id_source];
187                }
188
189                /*
190                 * @function test_connection
191                 * @author Mário César Kolling <mario.kolling@serpro.gov.br>
192                 * @abstract Test if we can bind to a ldap server in a reasonable time
193                 * @param (string) $host ldap server's hostname
194                 * @param (string) $account ldap bind dn
195                 * @param (string) $password a bind dn's password
196                 * @return (array) an array with the answer from the subprocess, null otherwise
197                 */
198                function test_connection($host, $account, $password, $timeout = 5)
199                {
200                        //opens a subprocess for nonblocking bind
201                        $tsearch = Thread::Create('class.ldap_assync.inc.php', array('host'     => $host,
202                                                                                                                                'account'       => $account,
203                                                                                                                                'password'      => $password
204                                                                                                                                )
205                        );
206
207                        // It's problably more efficient to let method readResponse control the timeout through
208                        // stream_select native timeout.
209                        $response = NULL;
210                        for ($i = 0; $i < $timeout; $i++)
211                        {
212                                if ($tsearch->isActive())
213                                {
214                                        sleep(1);
215                                        if (($response = $tsearch->readResponse()) !== NULL)
216                                        {
217                                                $tsearch->close();
218                                                return $response;
219                                        }
220
221                                }
222                                else
223                                {
224                                        $response = $tsearch->readResponse();
225                                        break;
226                                }
227                        }
228
229                        $tsearch->close();
230                        return null;
231                }
232
233                /*!
234
235                        @function get_ldap_tree
236                        @abstract Returns the LDAP tree corresponding to the specified level
237                        @author Raphael Derosso Pereira
238
239                        @param (integer) $id_source The ID of the LDAP source
240
241                        @param (string)  $context The context to be used as root branch
242
243                        @param (boolean) $recursive Make it a recursive construction.
244                                CAUTION! This is EXTREMELY SLOW on large LDAP databases,
245                                specially when they're not indexed
246                */
247                function get_ldap_tree($id_source, $context = false, $recursive = false)
248                {
249                        if (!$this->srcs[$id_source])
250                        {
251                                return null;
252                        }
253
254                        $ldap = $GLOBALS['phpgw']->common->ldapConnect($this->srcs[$id_source]['host'], $this->srcs[$id_source]['acc'],$this->srcs[$id_source]['pw'], false);
255                        if (!$ldap)
256                        {
257                                return false;
258                        }
259
260                        if ($recursive)
261                        {
262                                $tree = $this->get_ldap_tree_recursive($ldap, $context, $this->srcs[$id_source]['obj'],$this->srcs[$id_source]['branch']);
263                                $tree['recursive'] = true;
264
265                                return $tree;
266                        }
267
268                        return $this->get_ldap_tree_level($id_source, $ldap, $context, $this->srcs[$id_source]['obj'],$this->srcs[$id_source]['branch'], 0);
269                }
270
271                /*!
272
273                        @function get_external_ldap_tree
274                        @abstract Returns the LDAP external tree corresponding to the specified level
275                        @author Mário César Kolling <mario.kolling@serpro.gov.br>
276                        @param (integer) $id_source The ID of the external LDAP source
277                        @param (string)  $context The context to be used as root branch
278                        @param (boolean) $recursive Make it a recursive construction.
279                                CAUTION! This is EXTREMELY SLOW on large LDAP databases,
280                                specially when they're not indexed
281                */
282                function get_external_ldap_tree($id_source, $context = false, $recursive = false)
283                {
284
285
286                        include(PHPGW_INCLUDE_ROOT . '/contactcenter/setup/external_catalogs.inc.php' );
287                        //include('external_catalogs.inc.php' );
288
289                        if (!$external_srcs[$id_source])
290                        {
291                                return null;
292                        }
293
294                        // calls test_connection first. If succeeded continue, return error message otherwise.
295                        if (!($response = $this->test_connection($external_srcs[$id_source]['host'], $external_srcs[$id_source]['acc'], $external_srcs[$id_source]['pw'], 10)))
296                        {
297                                return array(
298                                        'msg'           =>      lang("Catalog %1 temporarily unavailable. Please try again later!", $external_srcs[$id_source]['name']),
299                                        'timeout'       =>      'true'
300                                );
301                        }
302
303                        $ldap = $GLOBALS['phpgw']->common->ldapConnect($external_srcs[$id_source]['host'], $external_srcs[$id_source]['acc'],$external_srcs[$id_source]['pw'], false);
304                        if (!$ldap)
305                        {
306                                return false;
307                        }
308
309                        // Option recursive commented out
310                        /*
311                        if ($recursive)
312                        {
313                                $tree = $this->get_ldap_tree_recursive($ldap, $context, $this->srcs[$id_source]['obj'],$this->srcs[$id_source]['branch']);
314                                $tree['recursive'] = true;
315
316                                return $tree;
317                        }
318                        */
319
320                        return $this->get_ldap_tree_level($id_source, $ldap, $context, $external_srcs[$id_source]['obj'],$external_srcs[$id_source]['branch'], 1);
321                }
322
323                /*!
324
325                        THIS FUNCTION IS NOT TESTED AND IS PROBABLY BROKEN!
326                        I WILL CORRECT IT IN THE NEAR FUTURE
327
328                */
329                function get_ldap_tree_recursive($resource, $context, $objectClass)
330                {
331                        $filter = '(!(objectClass='.$objectClass.'))';
332                        $result_res = ldap_list($resource, $context, $filter);
333
334                        if ($result_res === false)
335                        {
336                                return null;
337                        }
338
339                        $count = ldap_count_entries($resource,$result_res);
340                        if ( $count == 0 )
341                        {
342                                $filter = 'objectClass='.$objectClass;
343                                $result_res2 = ldap_list($resource, $context, $filter);
344                                $entries_count = ldap_count_entries($resource, $result_res2);
345
346                                if ($result_res2 !== false && $entries_count > 0)
347                                {
348                                        return $entries_count;
349                                }
350                                else
351                                {
352                                        return null;
353                                }
354                        }
355
356                        $entries = ldap_get_entries($resource, $result_res);
357
358                        for ($i = 0; $i < $entries['count']; $i++)
359                        {
360                                $subtree = $this->get_ldap_tree_recursive($resource, $entries[$i]['dn'], $objectClass);
361
362                                $dn_parts=ldap_explode_dn($entries[$i]['dn'],1);
363
364
365
366                                if ($subtree !== null and is_array($subtree))
367                                {
368                                        $tree[$i]['name'] = $dn_parts[0];
369                                        $tree[$i]['type'] = 'catalog_group';
370                                        $tree[$i]['recursive'] = true;
371                                        $tree[$i]['sub_branch'] = $subtree;
372                                }
373                                else if (is_int($subtree) and $subtree !== null)
374                                {
375                                        $tree[$i] = array(
376                                                'name'       => $dn_parts[0],
377                                                'type'       => 'catalog',
378                                                'class'      => 'global_contact_manager',
379                                                'icon'       => 'share-mini.png',
380                                                'value'      => $entries[$i]['dn'],
381                                                'sub_branch' => false
382                                        );
383                                }
384                        }
385
386                        if (is_array($tree))
387                        {
388                                return $tree;
389                        }
390                        else
391                        {
392                                return null;
393                        }
394                }
395
396                function get_ldap_referrals($ds, $dn, $filter) {
397
398                        ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
399                        ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
400
401                        if ($ds) {
402                            ldap_bind($ds);
403                                $sr=ldap_list($ds,$dn, $filter);
404                                $ref = ldap_first_reference($ds, $sr);
405                                $array_referral = array();
406                                $idx = 0;
407
408                                 while ($ref) {
409                                        $array_referral[$idx++] = ldap_get_dn($ds, $ref);
410                                        $ref = ldap_next_reference($ds, $ref);
411                                }
412                                return $array_referral;
413                        }
414                        else
415                                return false;
416                }
417
418                function get_ldap_sub_branches_referrals($ds, $dn, $filter) {
419
420                        $referral = $this -> get_ldap_referrals($ds, $dn, $filter);
421                        $sub_branches = array();
422
423                        for($i = 0; $i <count($referral); $i++) {
424                                $dn = str_replace("??base","",preg_replace('!^(ldap://[^/]+)/(.*$)!', '\\2', $referral[$i]));
425                                $dn = explode(",",$dn);
426                                $dn = strtoupper(str_replace("ou=", "",$dn[0]));
427                                $dn = str_replace("DC=", "",$dn);
428
429                                $sub_branch = array(
430                                                                                        'name' => $dn,
431                                                                'type' => 'unknown',
432                                                                'value' => $referral[$i],
433                                                                'sub_branch' => false
434                                                                                );
435                                $sub_branches[$i] = $sub_branch;
436                        }
437                        return $sub_branches;
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                        if(strstr($context, "ldap://")){
453                                $refer_context = str_replace("??base","",preg_replace('!^(ldap://[^/]+)/(.*$)!', '\\2', $context));
454                                $host   = preg_replace('!^(ldap://[^/]+)/.*$!', '\\1', $context);
455                                $resource = ldap_connect($host);
456                                ldap_bind($resource);
457                        }
458
459                        /*
460                         * TODO: Search timeouts
461                         */
462
463                        $dn_parts = ldap_explode_dn(($refer_context ? $refer_context : $context),1);
464                        //$filter = '(!(objectClass='.$objectClass.'))';
465                        // Don't show OU's whith phpgwAccountVisible equal to '-1'
466
467                        if ($external)
468                        {
469                                // external source: get all organizationalUnits
470                                $filter = '(objectClass=organizationalUnit)';
471                        }
472                        else
473                        {
474                                // get any objectClass except the objectClass used for the source
475                                // and whose attribute phpgwAccountVisible value is different from -1
476                                $filter = '(&(!(objectClass='.$objectClass.')) (!(phpgwAccountVisible=-1)))';
477                        }
478                        $result_res = @ldap_list($resource,  ($refer_context ? $refer_context : $context), $filter, array(), 0, 0);
479                        @ldap_sort($resource, $result_res, 'ou');
480
481                        // Timeouts commented out
482                        /*
483                        if ($result_res === false)
484                        {
485                                if (ldap_errno($resource) === 3)
486                                {
487                                        return array('error_msg' => ldap_error($resource));
488                                }
489                                return null;
490                        }
491                        */
492
493                        $count = ldap_count_entries($resource,$result_res);
494
495                        if ( $count == 0 )
496                        {
497                                $filter = '(objectClass='.$objectClass.')';
498                                // Get only one attribute of the source's objectClass
499                                $result_res2 = @ldap_list($resource, ($refer_context ? $refer_context : $context), $filter, Array('cn'), 0, 1);
500                                $entries_count = ldap_count_entries($resource, $result_res2);
501
502                                if ($result_res2 !== false && $entries_count > 0)
503                                {
504                                        return array(
505                                                'name'       => $this->translate_accentuation($dn_parts[0]),
506                                                'type'       => 'catalog',
507                                                'class'      => 'bo_global_ldap_catalog',
508                                                // Pass the variable $external as a parameter to the constructor
509                                                'class_args' => array($id_source, $context, $external),
510                                                'icon'       => 'globalcatalog-mini.png',
511                                                'value'      => $context,
512                                                'sub_branch' => false
513                                        );
514                                }
515                                else
516                                {
517                                        return array(
518                                                'name' => $this->translate_accentuation($dn_parts[0]),
519                                                'type' => 'empty'
520                                        );
521                                }
522                        }
523
524                        $sub_branch_found = false;
525                        $i = 0;
526                        for ($entry = ldap_first_entry($resource, $result_res);
527                             $entry != false;
528                             $entry = ldap_next_entry($resource, $entry))
529                        {
530                                $dn = ldap_get_dn($resource, $entry);
531                                $dn_parts_1 = ldap_explode_dn($dn,1);
532                                $dn_parts_full = ldap_explode_dn($dn,0);
533                                list($group) = explode('=',$dn_parts_full[0]);
534
535                                //Faz a comparação do branch como case insensitive
536                                if (strtolower($group) == strtolower($branch_dn) or $branch_dn === 'all')
537                                {
538                                        $tree['sub_branch'][$i] = array(
539                                                'name'  => $this->translate_accentuation($dn_parts_1[0]),
540                                                'type'  => 'unknown',
541                                                'value' =>  ($refer_context ? $host."/" : "").$dn,
542                                                'sub_branch' => false
543                                        );
544                                        $sub_branch_found = true;
545                                }
546                                $i++;
547                        }
548
549                        if(! $refer_context) {
550                                $array_referral = $this -> get_ldap_sub_branches_referrals($resource, $context,'(objectClass=organizationalUnit)');
551                                for($z = 0; $z < count($array_referral); $z++) {
552                                        $tree['sub_branch'][$i++] = $array_referral[$z];
553                                }
554                        }
555
556                        $filter = 'objectClass='.$objectClass;
557                        $result_res2 = @ldap_list($resource, ($refer_context ? $refer_context : $context), $filter, Array('cn'), 0, 1);
558                        $entries_count = ldap_count_entries($resource, $result_res2);
559
560                        if ($result_res2 !== false && $entries_count > 0 && $sub_branch_found)
561                        {
562                                $tree['name']       = $this->translate_accentuation($dn_parts[0]);
563                                $tree['type']       = 'mixed_catalog_group';
564                                $tree['class']      = 'bo_global_ldap_catalog';
565                                // Pass the variable $external as a parameter to the constructor
566                                $tree['class_args'] = array($id_source,$context,$external);
567                                $tree['icon']       = 'globalcatalog-mini.png';
568                                $tree['value']      = $context;
569                        }
570                        elseif ($result_res2 !== false && $entries_count > 0 && !$sub_branch_found)
571                        {
572                                return array(
573                                        'name'       => $this->translate_accentuation($dn_parts[0]),
574                                        'type'       => 'catalog',
575                                        'class'      => 'bo_global_ldap_catalog',
576                                        // Pass the variable $external as a parameter to the constructor
577                                        'class_args' => array($id_source, $context,$external),
578                                        'icon'       => 'globalcatalog-mini.png',
579                                        'value'      => $context,
580                                        'sub_branch' => false
581                                );
582                        }
583                        else
584                        {
585                                $tree['name']       = $this->translate_accentuation($dn_parts[0]);
586                                $tree['type']       = 'catalog_group';
587                                $tree['class']      = 'bo_catalog_group_catalog';
588                                // Pass the variable $external as a parameter to the constructor
589                                $tree['class_args'] = array('$this', '$this->get_branch_by_level($this->catalog_level[0])', $external);
590                                $tree['value']      = $context;
591                                $tree['ldap']       = array('id_source' => $id_source, 'context' => $context);
592                        }
593                        usort($tree['sub_branch'], array($this, "compareTreeNodes"));
594                        return $tree;
595                }
596
597                function compareTreeNodes($a, $b)       {
598
599                        return strnatcasecmp($a['name'], $b['name']);
600                }
601
602        }
603?>
Note: See TracBrowser for help on using the repository browser.