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

Revision 7673, 19.3 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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