source: sandbox/2.2.0.2/contactcenter/inc/class.bo_ldap_manager.inc.php @ 4500

Revision 4500, 19.2 KB checked in by airton, 13 years ago (diff)

Ticket #1926 - Permitir configurar mais atributos cadastrados de um contato para exibição

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