source: trunk/expressoAdmin1_2/inc/class.ldap_functions.inc.php @ 355

Revision 355, 72.4 KB checked in by niltonneto, 16 years ago (diff)

Alterações do Desenvolvedor.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2define('PHPGW_INCLUDE_ROOT','../');
3define('PHPGW_API_INC','../phpgwapi/inc');     
4include_once(PHPGW_API_INC.'/class.common.inc.php');
5include_once('class.functions.inc.php');
6
7function ldapRebind($ldap_connection, $ldap_url)
8{
9        // Enquanto estivermos utilizando referral na arvore ldap, teremos que continuar a utilizar o usuário sistemas:expresso.
10        // Depois, quando não existir mais referral, não existirá a necessidade de ldapRebind.
11        //ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
12        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
13        {
14                @ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
15        }
16}
17
18class ldap_functions
19{
20        var $ldap;
21        var $current_config;
22        var $functions;
23        var $manager_contexts;
24       
25        function ldap_functions(){             
26                $GLOBALS['phpgw_info']['server'] = $_SESSION['phpgw_info']['expresso']['server'];
27                $this->current_config = $_SESSION['phpgw_info']['expresso']['expressoAdmin'];
28                $common = new common();
29               
30                if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) &&
31                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) &&
32                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) )
33                {
34                        $this->ldap = $common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_master_host'],
35                                                                                           $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'],
36                                                                                           $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
37                }
38                else
39                {
40                        $this->ldap = $common->ldapConnect();
41                }
42               
43                $this->functions = new functions;
44                $manager_acl = $this->functions->read_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid']);
45                $this->manager_contexts = $manager_acl['contexts'];
46        }
47       
48        /* expressoAdmin: email lists : deve utilizar o ldap Host Master com o usuario e senha do CC*/
49        /* ldap connection following referrals and using Master config, from setup */
50        function ldapMasterConnect()
51        {
52                /*
53                $common = new common();
54                if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) &&
55                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) &&
56                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) )
57                {
58                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_master_host']);
59                        ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
60                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
61                        ldap_set_rebind_proc($ldap_connection, ldapRebind);
62                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
63                }
64                else
65                {
66                        $ldap_connection = $common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_host'],
67                                                                                           $GLOBALS['phpgw_info']['server']['ldap_root_dn'],
68                                                                                           $GLOBALS['phpgw_info']['server']['ldap_root_pw'], true);
69                }
70               
71                // If success, return follow_referral connection. Else, return normal connection.
72                if ($ldap_connection)
73                        return $ldap_connection;
74                else
75                        return $this->ldap;
76                */
77               
78                if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) && ($ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_master_host'])) )
79                {
80                        ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
81                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
82                        ldap_set_rebind_proc($ldap_connection, ldapRebind);
83                        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
84                        {
85                                if ( ! ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']) )
86                                {
87                                        return false;
88                                }
89                        }
90                        return $ldap_connection;
91                }
92                else
93                {
94                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
95                        if ($ldap_connection)
96                        {
97                                ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
98                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
99                                if ( ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']) )
100                                        return $ldap_connection;
101                        }
102                }
103               
104                return false;
105        }
106               
107        function validate_fields($params)
108        {
109                /* ldap connection following referals and using Contac Center config*/
110                if (is_array($_SESSION['phpgw_info']['expresso']['cc_ldap_server']))
111                {
112                        $ldap_connection = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
113                        if ($ldap_connection)
114                        {
115                                ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
116                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
117                               
118                                if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
119                                        ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
120                                $context = $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['dn'];
121                        }
122                        else
123                        {
124                                $result['status'] = false;
125                                $result['msg'] = 'Falha na conexao com o ldap.';
126                                return $result;
127                        }
128                }
129                else
130                {
131                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
132                        ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
133                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
134                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
135                        $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
136                }
137               
138                $result['status'] = true;
139               
140                $params = unserialize($params['attributes']);
141                $type = $params['type'];
142                $uid = $params['uid'];
143                $mail = $params['mail'];
144                $mailalternateaddress = $params['mailalternateaddress'];
145                $cpf = $params['cpf'];
146                               
147                if ($_SESSION['phpgw_info']['expresso']['global_denied_users'][$uid])
148                {
149                        $result['status'] = false;
150                        $result['msg'] = 'Este LOGIN não pode ser usado pois é uma conta de sistema.';
151                        return $result;
152                }
153               
154                if (($type == 'create_user') || ($type == 'rename_user'))
155                {
156                        if ($this->current_config['expressoAdmin_prefix_org'] == 'true')
157                        {
158                                //Obtenho UID sem a organização. Na criação o uid já vem sem a organização
159                                $tmp_uid_without_org = split("-", $params['uid']);
160                                $tmp_reverse_uid_without_org = array_reverse($tmp_uid_without_org);
161                                array_pop($tmp_reverse_uid_without_org);
162                                $uid_without_org = implode("-", $tmp_reverse_uid_without_org);
163                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(uid=$uid)(uid=$uid_without_org)))";
164                        }
165                        else
166                        {
167                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$uid))";
168                        }
169                        /*
170                        //UID
171                        if (($type == 'rename_user') && ($this->current_config['expressoAdmin_prefix_org'] == 'true'))
172                        {
173                                //Obtenho UID sem a organização. Na criação o uid já vem sem a organização
174                                $tmp_uid_without_org = split("-", $params['uid']);
175                                $tmp_reverse_uid_without_org = array_reverse($tmp_uid_without_org);
176                                array_pop($tmp_reverse_uid_without_org);
177                                $uid_without_org = implode("-", $tmp_reverse_uid_without_org);
178                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(uid=$uid)(uid=$uid_without_org)))";
179                        }
180                        else
181                        {
182                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$uid))";
183                        }
184                        */
185                       
186                        $justthese = array("uid", "mail", "cn");
187                        $search = ldap_search($ldap_connection, $context, $filter, $justthese);
188                        $count_entries = ldap_count_entries($ldap_connection,$search);
189                        if ($count_entries > 0)
190                        {
191                                $entries = ldap_get_entries($ldap_connection, $search);
192                               
193                                for ($i=0; $i<$entries['count']; $i++)
194                                {
195                                        $users .= $entries[$i]['cn'][0] . ' - ' . $entries[$i]['mail'][0] . "\n";
196                                }
197                               
198                                $result['status'] = false;
199                                $result['msg'] = "LOGIN já está sendo utilizado por:\n" . $users;
200                                return $result;
201                        }
202
203                        // GRUPOS
204                        $filter = "(&(phpgwAccountType=g)(cn=$uid))";
205                        $justthese = array("cn");
206                        $search = ldap_search($ldap_connection, $context, $filter, $justthese);
207                        $count_entries = ldap_count_entries($ldap_connection,$search);
208                        if ($count_entries > 0)
209                        {
210                                $result['status'] = false;
211                                $result['msg'] = 'LOGIN do usuário já esta sendo usado por um grupo.';
212                                return $result;
213                        }
214                       
215                       
216                        // UID em outras organizações, pesquiso apenas na maquina local e se utilizar prefix_org
217                        if ($this->current_config['expressoAdmin_prefix_org'] == 'true')
218                        {
219                                $ldap_connection2 = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
220                                ldap_set_option($ldap_connection2,LDAP_OPT_PROTOCOL_VERSION,3);
221                                ldap_set_option($ldap_connection2, LDAP_OPT_REFERRALS, false);
222                                ldap_bind($ldap_connection2, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
223                                $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
224                               
225                                //Obtenho UID sem a organização
226                                /*
227                                $tmp_uid_without_org = split("-", $params['uid']);
228                                if (count($tmp_uid_without_org) < 2)
229                                {
230                                        $result['status'] = false;
231                                        $result['msg'] = 'Novo login sem organização.';
232                                        return $result;
233                                }
234                                $tmp_reverse_uid_without_org = array_reverse($tmp_uid_without_org);
235                                array_pop($tmp_reverse_uid_without_org);
236                                $uid_without_org = implode("-", $tmp_reverse_uid_without_org);
237                                */
238                               
239                                $filter = "(ou=*)";
240                                $justthese = array("ou");
241                                $search = ldap_list($ldap_connection2, $context, $filter, $justthese);
242                                $entries = ldap_get_entries($ldap_connection2   ,$search);
243                               
244                                foreach ($entries as $index=>$org)
245                                {
246                                        $organization = $org['ou'][0];
247                                        $organization = strtolower($organization);
248                               
249                                        $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$organization-$uid))";
250                                       
251                                        $justthese = array("uid");
252                                        $search = ldap_search($ldap_connection2, $context, $filter, $justthese);
253                                        $count_entries = ldap_count_entries($ldap_connection2,$search);
254                                        if ($count_entries > 0)
255                                        {
256                                                $result['status'] = false;
257                                                $result['msg'] = 'LOGIN já esta sendo usado por outro usuário em outra organização.';
258                                                ldap_close($ldap_connection2);
259                                                return $result;
260                                        }
261                                }
262                                ldap_close($ldap_connection2);
263                        }
264                }
265               
266                if ($type == 'rename_user')
267                {
268                        return $result;
269                }
270               
271                // MAIL
272                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mail)(mailalternateaddress=$mail)))";
273                $justthese = array("mail", "uid");
274                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
275                $entries = ldap_get_entries($ldap_connection,$search);
276                if ($entries['count'] == 1){
277                        if ($entries[0]['uid'][0] != $uid){
278                                $result['status'] = false;
279                                $result['msg'] = 'E-MAIL está sendo usado por 1 usuário: ' . $entries[0]['uid'][0];
280                                //ldap_close($ldap_connection);
281                                return $result;
282                        }
283                }
284                else if ($entries['count'] > 1){
285                        $result['status'] = false;
286                        $result['msg'] = 'E-MAIL está sendo usado por 2 ou mais usuários.';
287                        //ldap_close($ldap_connection);
288                        return $result;
289                }
290               
291                // MAILAlternateAddress
292                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mailalternateaddress)(mailalternateaddress=$mailalternateaddress)))";
293                $justthese = array("mail", "uid");
294                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
295                $entries = ldap_get_entries($ldap_connection,$search);
296                if ($entries['count'] == 1){
297                        if ($entries[0]['uid'][0] != $uid){
298                                $result['status'] = false;
299                                $result['msg'] = "E-MAIL alternativo está sendo usado por 1 usuário: " . $entries[0]['uid'][0];
300                                //ldap_close($ldap_connection);
301                                return $result;
302                        }
303                }
304                else if ($entries['count'] > 1){
305                        $result['status'] = false;
306                        $result['msg'] = 'E-MAIL alternativo está sendo usado por 2 ou mais usuários.';
307                        return $result;
308                }
309
310                //Begin: Check CPF
311                if (!empty($cpf))
312                {
313                        if (!$this->functions->checkCPF($cpf))
314                        {
315                                $result['status'] = false;
316                                $result['msg'] = $this->functions->lang('Field CPF is invalid') . '.';
317                                return $result;
318                        }
319                        else
320                        {
321                                $local_ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
322                                if ($ldap_connection)
323                                {
324                                        ldap_set_option($local_ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
325                                        ldap_set_option($local_ldap_connection, LDAP_OPT_REFERRALS, false);
326                                        ldap_bind($local_ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
327                                }
328                                else
329                                {
330                                        $result['status'] = false;
331                                        $result['msg'] = 'Falha na conexao com o ldap.';
332                                        return $result;
333                                }
334                               
335                                $filter = "(&(phpgwAccountType=u)(cpf=$cpf))";
336                                $justthese = array("cn","uid");
337                                $search = ldap_search($local_ldap_connection, $context, $filter, $justthese);
338                                $entries = ldap_get_entries($local_ldap_connection,$search);
339                               
340                                if ( ($entries['count'] == 1) && (strcasecmp($uid, $entries[0]['uid'][0]) == 0) )
341                                {}
342                                else
343                                {
344                                        if ($entries['count'] > 0)
345                                        {
346                                                $result['question'] = $this->functions->lang('Field CPF used by') . ":\n";
347                                                for ($i=0; $i<$entries['count']; $i++)
348                                                {
349                                                        if (strcasecmp($uid, $entries[$i]['uid'][0]) != 0)
350                                                                $result['question'] .= "- " . $entries[$i]['cn'][0] . "\n";
351                                                }
352                                                $result['question'] .= $this->functions->lang("Do you want to continue anyway") . "?";
353                                                return $result;
354                                        }
355                                }
356                                ldap_close($local_ldap_connection);
357                        }
358                }
359                else if ($this->current_config['expressoAdmin_cpf_obligation'])
360                {
361                        $result['status'] = false;
362                        $result['msg'] = $this->functions->lang('Field CPF must be completed') . '.';
363                        return $result;
364                }
365                //End: Check CPF
366
367                return $result;
368        }
369       
370        function validate_fields_group($params)
371        {
372                /* ldap connection following referals and using Contac Center config*/
373                if (is_array($_SESSION['phpgw_info']['expresso']['cc_ldap_server']))
374                {
375                        $ldap_connection = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
376                        if ($ldap_connection)
377                        {
378                                ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
379                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
380                                if ( ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
381                                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'], $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw']);
382                                $context = $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['dn'];
383                        }
384                        else
385                        {
386                                $result['status'] = false;
387                                $result['msg'] = 'Falha na conexao com o ldap.';
388                                return $result;
389                        }
390                }
391                else
392                {
393                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
394                        ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
395                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
396                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
397                        $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
398                }
399
400                $cn = $params['cn'];
401                $result['status'] = true;
402               
403                if ($_SESSION['phpgw_info']['expresso']['global_denied_groups'][$cn])
404                {
405                        $result['status'] = false;
406                        $result['msg'] = 'Este nome de grupo não pode ser usado pois é um grupo de sistema.';
407                        return $result;
408                }
409               
410                // CN
411                $filter = "(&(phpgwAccountType=g)(cn=$cn))";
412                $justthese = array("cn");
413                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
414                $count_entries = ldap_count_entries($ldap_connection,$search);
415                if ($count_entries > 0)
416                {
417                        $result['status'] = false;
418                        $result['msg'] = 'NOME do grupo já está sendo usado.';
419                        return $result;
420                }
421               
422                // UID
423                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$cn))";
424                $justthese = array("uid");
425                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
426                $count_entries = ldap_count_entries($ldap_connection,$search);
427                if ($count_entries > 0)
428                {
429                        $result['status'] = false;
430                        $result['msg'] = 'NOME do grupo já esta sendo usado por um usuário.';
431                        return $result;
432                }
433               
434                return $result;
435        }
436       
437        function validate_fields_maillist($params)
438        {
439                /* ldap connection following referals and using Contac Center config*/
440                if (is_array($_SESSION['phpgw_info']['expresso']['cc_ldap_server']))
441                {
442                        $ldap_connection = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
443                        if ($ldap_connection)
444                        {
445                                ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
446                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
447                                if ( ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
448                                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'], $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw']);
449                                $context = $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['dn'];
450                        }
451                        else
452                        {
453                                $result['status'] = false;
454                                $result['msg'] = 'Falha na conexao com o ldap.';
455                                return $result;
456                        }
457                }
458                else
459                {
460                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
461                        ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
462                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
463                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
464                        $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
465                }
466               
467                $uid = $params['uid'];
468                $mail = $params['mail'];
469                $result['status'] = true;
470               
471                if ($_SESSION['phpgw_info']['expresso']['global_denied_users'][$uid])
472                {
473                        $result['status'] = false;
474                        $result['msg'] = 'Este LOGIN não pode ser usado pois é uma conta de sistema.';
475                        return $result;
476                }
477               
478                // UID
479                $filter = "(&(phpgwAccountType=l)(uid=$uid))";
480                $justthese = array("uid");
481                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
482                $count_entries = ldap_count_entries($ldap_connection,$search);
483                if ($count_entries > 0)
484                {
485                        $result['status'] = false;
486                        $result['msg'] = 'LOGIN da lista já está sendo usado.';
487                        return $result;
488                }
489               
490                // MAIL
491                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mail)(mailalternateaddress=$mail)))";
492                $justthese = array("mail");
493                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
494                $count_entries = ldap_count_entries($ldap_connection,$search);
495                if ($count_entries > 0)
496                {
497                        $result['status'] = false;
498                        $result['msg'] = 'E-MAIL da lista já está sendo usado.';
499                        return $result;
500                }
501               
502                return $result;
503        }
504
505        //Busca usuários de um contexto e já retorna as options do select;
506        function get_available_users($params)
507        {
508                $context = $params['context'];
509                $recursive = $params['recursive'];
510                $justthese = array("cn", "uidNumber");
511                $filter="(phpgwAccountType=u)";
512               
513                if ($recursive == 'true')
514                        $groups_list=ldap_search($this->ldap, $context, $filter, $justthese);
515                else
516                $groups_list=ldap_list($this->ldap, $context, $filter, $justthese);
517       
518        $entries = ldap_get_entries($this->ldap, $groups_list);
519       
520                for ($i=0; $i<$entries["count"]; $i++){
521                        $u_tmp[$entries[$i]["uidnumber"][0]] = $entries[$i]["cn"][0];
522                }
523                       
524                if (count($u_tmp))
525                        natcasesort($u_tmp);
526
527                $i = 0;
528                $users = array();
529                       
530                if (count($u_tmp))
531                {
532                        foreach ($u_tmp as $uidnumber => $cn)
533                        {
534                                $options .= "<option value=$uidnumber>$cn</option>";
535                        }
536                        unset($u_tmp);
537                }
538
539        return $options;
540        }
541
542        //Busca usuários de um contexto e já retorna as options do select;
543        /*
544        function get_available_users_and_maillist($params)
545        {
546                $context = $params['context'];
547                $recursive = $params['recursive'];
548                $justthese = array("cn", "uidNumber");
549                $filter="(|(phpgwAccountType=u)(phpgwAccountType=l))";
550               
551                if ($recursive == 'true')
552                        $groups_list=ldap_search($this->ldap, $context, $filter, $justthese);
553                else
554                $groups_list=ldap_list($this->ldap, $context, $filter, $justthese);
555       
556        $entries = ldap_get_entries($this->ldap, $groups_list);
557       
558                for ($i=0; $i<$entries["count"]; $i++){
559                        $u_tmp[$entries[$i]["uidnumber"][0]] = $entries[$i]["cn"][0];
560                }
561                       
562                if (count($u_tmp))
563                        natcasesort($u_tmp);
564
565                $i = 0;
566                $users = array();
567                       
568                if (count($u_tmp))
569                {
570                        foreach ($u_tmp as $uidnumber => $cn)
571                        {
572                                $options .= "<option value=$uidnumber>$cn</option>";
573                        }
574                        unset($u_tmp);
575                }
576
577        return $options;
578        }
579        */
580
581        //Busca usuários e listas de um contexto e já retorna as options do select;
582        function get_available_users_and_maillist($params)
583        {
584                $context = $params['context'];
585                $recursive = $params['recursive'];
586               
587                //Usado para retirar a própria lista das possibilidades de inclusão.
588                $denied_uidnumber = $params['denied_uidnumber'];
589               
590                $justthese = array("cn", "uidNumber", "mail");
591               
592                $users_filter="(phpgwAccountType=u)";
593                $lists_filter = $denied_uidnumber == '' ? "(phpgwAccountType=l)" : "(&(phpgwAccountType=l)(!(uidnumber=$denied_uidnumber)))";
594               
595                $users = Array();
596                $lists = Array();               
597
598                /* folling referral connection */
599                $ldap_conn_following_ref = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
600                if ($ldap_conn_following_ref)
601                {
602                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_PROTOCOL_VERSION, 3);
603                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_REFERRALS, 1);
604
605                        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
606                                ldap_bind($ldap_conn_following_ref, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
607                }
608                else
609                        return false;
610
611                if ($recursive == 'true')
612                {
613                        $lists_search = ldap_search($ldap_conn_following_ref, $context, $lists_filter, $justthese);
614                        $users_search = ldap_search($ldap_conn_following_ref, $context, $users_filter, $justthese);
615                }
616                else
617                {
618                        $lists_search = ldap_list($ldap_conn_following_ref, $context, $lists_filter, $justthese);
619                        $users_search = ldap_list($ldap_conn_following_ref, $context, $users_filter, $justthese);
620                }
621               
622                /* email lists */
623                $lists_entries = ldap_get_entries($ldap_conn_following_ref, $lists_search);
624               
625                for ($i=0; $i<$lists_entries["count"]; $i++)
626                {
627                        $l_tmp[$lists_entries[$i]["mail"][0]] = $lists_entries[$i]["cn"][0];
628                }
629                       
630                if (count($l_tmp))
631                        natcasesort($l_tmp);
632                       
633                $i = 0;
634                $lists = array();
635               
636                $options .= '<option  value="-1" disabled>------------------------------&nbsp;&nbsp;&nbsp;&nbsp;Listas&nbsp;&nbsp;&nbsp;&nbsp;------------------------------ </option>'."\n";   
637                if (count($l_tmp))
638                {
639                        foreach ($l_tmp as $mail => $cn)
640                        {
641                                $options .= "<option value=$mail>$cn</option>";
642                        }
643                        unset($l_tmp);
644                }
645               
646                /* users */
647                $users_entries = ldap_get_entries($ldap_conn_following_ref, $users_search);
648                for ($i=0; $i<$users_entries["count"]; $i++)
649                {
650                        $u_tmp[$users_entries[$i]["mail"][0]] = $users_entries[$i]["cn"][0];
651                }
652                       
653                if (count($u_tmp))
654                        natcasesort($u_tmp);
655                       
656                $i = 0;
657                $users = array();
658               
659                $options .= '<option  value="-1" disabled>-----------------------------&nbsp;&nbsp;&nbsp;&nbsp;Usuários&nbsp;&nbsp;&nbsp;&nbsp;---------------------------- </option>'."\n";   
660                if (count($u_tmp))
661                {
662                        foreach ($u_tmp as $mail => $cn)
663                        {
664                                $options .= "<option value=$mail class='line-above'>$cn</option>";
665                        }
666                        unset($u_tmp);
667                }
668               
669                ldap_close($ldap_conn_following_ref);
670                return $options;
671        }
672
673        function get_available_groups($params)
674        {
675                $context = $params['context'];
676                $justthese = array("cn", "gidNumber");
677        $groups_list=ldap_list($this->ldap, $context, ("(phpgwAccountType=g)"), $justthese);
678        ldap_sort($this->ldap, $groups_list, "cn");
679       
680        $entries = ldap_get_entries($this->ldap, $groups_list);
681               
682                $options = '';
683                for ($i=0; $i<$entries['count']; $i++)
684                {
685                        $options .= "<option value=" . $entries[$i]['gidnumber'][0] . ">" . $entries[$i]['cn'][0] . "</option>";
686                }
687       
688        return $options;               
689        }
690       
691        function get_available_maillists($params)
692        {
693                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
694                        return false;
695               
696                $context = $params['context'];
697                $justthese = array("uid","mail","uidNumber");
698        $maillists=ldap_list($ldapMasterConnect, $context, ("(phpgwAccountType=l)"), $justthese);
699        ldap_sort($ldapMasterConnect, $maillists, "uid");
700       
701        $entries = ldap_get_entries($ldapMasterConnect, $maillists);
702       
703                $options = '';                 
704                for ($i=0; $i<$entries['count']; $i++)
705                {
706                        $options .= "<option value=" . $entries[$i]['uid'][0] . ">" . $entries[$i]['uid'][0] . " (" . $entries[$i]['mail'][0] . ")" . "</option>";
707                }
708       
709        ldap_close($ldapMasterConnect);
710        return $options;
711        }
712       
713        function ldap_add_entry($dn, $entry)
714        {
715                $result = array();
716                if (!@ldap_add ( $this->ldap, $dn, $entry ))
717                {
718                        $result['status']               = false;
719                        $result['error_number'] = ldap_errno($this->ldap);
720                        $result['msg']                  = "Erro na funcao ldap_functions->ldap_add_entry ($dn).\nRetorno do servidor:" . ldap_errno($this->ldap) . ldap_error($this->ldap);
721                }
722                else
723                        $result['status'] = true;
724               
725                return $result;
726        }
727       
728        function ldap_save_photo($dn, $pathphoto, $photo_exist=false)
729        {
730                $fd = fopen($pathphoto, "r");
731                $fsize = filesize($pathphoto);
732                $jpegStr = fread($fd, $fsize);
733                fclose ($fd);
734                $attrs['jpegPhoto'] = $jpegStr;
735                       
736                if ($photo_exist)
737                        $res = @ldap_mod_replace($this->ldap, $dn, $attrs);
738                else
739                        $res = @ldap_mod_add($this->ldap, $dn, $attrs);
740                       
741                if ($res)
742                {
743                        $result['status'] = true;
744                }
745                else
746                {
747                        $result['status'] = false;
748                        $result['msg'] = "Erro na funcao ldap_functions->ldap_save_photo ($dn).\nRetorno do servidor:" . ldap_error($this->ldap);
749                }
750               
751                return $result;
752        }
753       
754        function ldap_remove_photo($dn)
755        {
756                $attrs['jpegPhoto'] = array();
757                $res = ldap_mod_del($this->ldap, $dn, $attrs);
758               
759                if ($res)
760                {
761                        $result['status'] = true;
762                }
763                else
764                {
765                        $result['status'] = false;
766                        $result['msg'] = "Erro na funcao ldap_functions->ldap_remove_photo ($dn).\nRetorno do servidor:" . ldap_error($this->ldap);
767                }
768               
769                return $result;
770        }       
771       
772        // Pode receber tanto um único memberUid quanto um array de memberUid's
773        function add_user2group($gidNumber, $memberUid)
774        {
775                $filter = "(&(phpgwAccountType=g)(gidNumber=$gidNumber))";
776                $justthese = array("dn");
777                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
778                $entry = ldap_get_entries($this->ldap, $search);
779                $group_dn = $entry[0]['dn'];
780                $attrs['memberUid'] = $memberUid;
781               
782                $res = @ldap_mod_add($this->ldap, $group_dn, $attrs);
783               
784                if ($res)
785                {
786                        $result['status'] = true;
787                }
788                else
789                {
790                        $result['status'] = false;
791                        $result['msg'] = "Erro na funcao ldap_functions->add_user2group ($memberUid).\nRetorno do servidor:" . ldap_error($this->ldap);
792                }
793                return $result;
794        }
795       
796        function remove_user2group($gidNumber, $memberUid)
797        {
798                $filter = "(&(phpgwAccountType=g)(gidNumber=$gidNumber))";
799                $justthese = array("dn");
800                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
801                $entry = ldap_get_entries($this->ldap, $search);
802                $group_dn = $entry[0]['dn'];
803                $attrs['memberUid'] = $memberUid;
804                $res = @ldap_mod_del($this->ldap, $group_dn, $attrs);
805               
806                /*echo 'usuarios recebidos para remocao no ldap';
807                echo '<pre>';
808                print_r($memberUid);*/
809               
810                if ($res)
811                {
812                        $result['status'] = true;
813                }
814                else
815                {
816                        $result['status'] = false;
817                        $result['msg'] = "Erro na funcao ldap_functions->remove_user2group ($memberUid).\nRetorno do servidor:" . ldap_error($this->ldap);
818                }
819                return $result;
820        }
821       
822        function add_user2maillist($uid, $mail)
823        {
824                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
825                {
826                        $result['status'] = false;
827                        $result['msg'] = "Falha de conexão com o openLDAP.\n\nRetorno do servidor:" . ldap_error($ldapMasterConnect);
828                        return $result;
829                }
830                       
831                $filter = "(&(phpgwAccountType=l)(uid=$uid))";
832                $justthese = array("dn");
833                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
834                $entry = ldap_get_entries($ldapMasterConnect, $search);
835                $group_dn = $entry[0]['dn'];
836                $attrs['mailForwardingAddress'] = $mail;
837                $res = @ldap_mod_add($ldapMasterConnect, $group_dn, $attrs);
838               
839                if ($res)
840                {
841                        $result['status'] = true;
842                }
843                else
844                {
845                        $result['status'] = false;
846                        if (ldap_errno($ldapMasterConnect) == '50')
847                        {
848                                $result['msg'] = "Erro na funcao ldap_functions->add_user2maillist.\n" .
849                                                                 "O usuário utilizado para gravação no LDAP, DEVE ter direito de escrita.\n".
850                                                                 "O usuário " . $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] . " não tem este direito.\n".
851                                                                 "Edite \"Configuração Global do Catálogo\", no módulo Administrador, Catálogo de Endereços e adicione um usuário com direitos de escrita.";
852                        }                                       
853                        else
854                                $result['msg'] = "Erro na funcao ldap_functions->add_user2maillist.\nRetorno do servidor:" . ldap_error($ldapMasterConnect);
855                }
856               
857                ldap_close($ldapMasterConnect);
858                return $result;
859        }
860       
861        function add_user2maillist_scl($dn, $array_emails)
862        {
863                $attrs['mailSenderAddress'] = $array_emails;
864               
865                print_r($attrs);
866               
867                $res = @ldap_mod_add($this->ldap, $dn, $attrs);
868               
869                if ($res)
870                {
871                        $result['status'] = true;
872                }
873                else
874                {
875                        $result['status'] = false;
876                        $result['msg'] = "Erro na funcao ldap_functions->add_user2maillist_scp ($dn).\n\nRetorno do servidor:" . ldap_error($this->ldap);
877                }
878                return $result;
879        }
880
881        function remove_user2maillist($uid, $mail)
882        {
883                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
884                {
885                        $result['status'] = false;
886                        $result['msg'] = "Falha de conexão com o openLDAP.\n\nRetorno do servidor:" . ldap_error($ldapMasterConnect);
887                        return $result;
888                }
889               
890                $filter = "(&(phpgwAccountType=l)(uid=$uid))";
891                $justthese = array("dn");
892                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
893                $entry = ldap_get_entries($ldapMasterConnect, $search);
894                $group_dn = $entry[0]['dn'];
895                $attrs['mailForwardingAddress'] = $mail;
896                $res = @ldap_mod_del($ldapMasterConnect, $group_dn, $attrs);
897               
898                if ($res)
899                {
900                        $result['status'] = true;
901                }
902                else
903                {
904                        $result['status'] = false;
905                        if (ldap_errno($ldapMasterConnect) == '50')
906                        {
907                                $result['msg'] = "Erro na funcao ldap_functions->add_user2maillist.\n" .
908                                                                 "O usuário utilizado para gravação no LDAP, DEVE ter direito de escrita.\n".
909                                                                 "O usuário " . $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] . " não tem este direito.\n".
910                                                                 "Edite \"Configuração Global do Catálogo\", no módulo Administrador, Catálogo de Endereços e adicione um usuário com direitos de escrita.";
911                        }                                       
912                        else
913                                $result['msg'] = "Erro na funcao ldap_functions->add_user2maillist.\nRetorno do servidor:" . ldap_error($ldapMasterConnect);
914                }
915                ldap_close($ldapMasterConnect);
916                return $result;
917        }
918
919        function remove_user2maillist_scl($dn, $array_emails)
920        {
921                $attrs['mailSenderAddress'] = $array_emails;
922                $res = @ldap_mod_del($this->ldap, $dn, $attrs);
923               
924                if ($res)
925                {
926                        $result['status'] = true;
927                }
928                else
929                {
930                        $result['status'] = false;
931                        $result['msg'] = "Erro na funcao ldap_functions->remove_user2maillist_scp ($dn).\n\nRetorno do servidor:" . ldap_error($this->ldap);
932                }
933                return $result;
934        }
935
936        function replace_user2maillists($new_mail, $old_mail)
937        {
938                $filter = "(&(phpgwAccountType=l)(mailforwardingaddress=$old_mail))";
939                $justthese = array("dn");
940                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
941                $entries = ldap_get_entries($this->ldap, $search);
942                $result['status'] = true;
943                for ($i=0; $i<$entries['count']; $i++)
944                {
945                        $attrs['mailforwardingaddress'] = $old_mail;
946                        $res1 = @ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs);
947                        $attrs['mailforwardingaddress'] = $new_mail;
948                        $res2 = @ldap_mod_add($this->ldap, $entries[$i]['dn'], $attrs);
949               
950                        if ((!$res1) || (!$res2))
951                        {
952                                $result['status'] = false;
953                                $result['msg'] = "Erro na funcao ldap_functions->replace_user2maillists ($old_mail).\nRetorno do servidor:" . ldap_error($this->ldap);
954                        }
955                }
956               
957                return $result;
958        }
959       
960        function get_user_info($uidnumber)
961        {
962                foreach ($this->manager_contexts as $index=>$context)
963                {
964                        $filter="(&(phpgwAccountType=u)(uidNumber=".$uidnumber."))";
965                        $search = ldap_search($this->ldap, $context, $filter);
966                        $entry = ldap_get_entries($this->ldap, $search);
967                       
968                        if ($entry['count'])
969                        {
970                                //Pega o dn do setor do usuario.
971                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
972                                $sector_dn_array = explode(",", $entry[0]['dn']);
973                                for($i=1; $i<count($sector_dn_array); $i++)
974                                        $sector_dn .= $sector_dn_array[$i] . ',';
975                                //Retira ultimo pipe.
976                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
977               
978                                $result['context']                              = $sector_dn;
979                                $result['uid']                                  = $entry[0]['uid'][0];
980                                $result['uidnumber']                    = $entry[0]['uidnumber'][0];
981                                $result['gidnumber']                    = $entry[0]['gidnumber'][0];
982                                $result['departmentnumber']             = $entry[0]['departmentnumber'][0];
983                                $result['givenname']                    = $entry[0]['givenname'][0];
984                                $result['sn']                                   = $entry[0]['sn'][0];
985                                $result['telephonenumber']              = $entry[0]['telephonenumber'][0];
986                                $result['passwd_expired']               = $entry[0]['phpgwlastpasswdchange'][0];
987                                $result['phpgwaccountstatus']   = $entry[0]['phpgwaccountstatus'][0];
988                                $result['phpgwaccountvisible']  = $entry[0]['phpgwaccountvisible'][0];
989                                $result['accountstatus']                = $entry[0]['accountstatus'][0];
990                                $result['mail']                                 = $entry[0]['mail'][0];
991                                $result['mailalternateaddress'] = $entry[0]['mailalternateaddress'];
992                                $result['mailforwardingaddress']= $entry[0]['mailforwardingaddress'];
993                                $result['deliverymode']                 = $entry[0]['deliverymode'][0];
994                                $result['userPasswordRFC2617']  = $entry[0]['userpasswordrfc2617'][0];
995
996                                //Photo
997                                if ($entry[0]['jpegphoto']['count'] == 1)
998                                        $result['photo_exist'] = 'true';
999               
1000                                // Samba
1001                                for ($i=0; $i<$entry[0]['objectclass']['count']; $i++)
1002                                {
1003                                        if ($entry[0]['objectclass'][$i] == 'sambaSamAccount')
1004                                                $result['sambaUser'] = true;
1005                                }
1006                                if (($this->current_config['expressoAdmin_samba_support'] == 'true') && ($result['sambaUser']))
1007                                {
1008                                        $result['sambaaccflags'] = $entry[0]['sambaacctflags'][0];
1009                                        $result['sambalogonscript'] = $entry[0]['sambalogonscript'][0];
1010                                        $result['homedirectory'] = $entry[0]['homedirectory'][0];
1011                                        $a_tmp = explode("-", $entry[0]['sambasid'][0]);
1012                                        array_pop($a_tmp);
1013                                        $result['sambasid'] = implode("-", $a_tmp);
1014                                }
1015
1016                                // Verifica o acesso do gerente aos atributos corporativos
1017                                if ($this->functions->check_acl($_SESSION['phpgw_session']['session_lid'], 'manipulate_corporative_information'))
1018                                {
1019                                        $result['corporative_information_employeenumber']= $entry[0]['employeenumber'][0];
1020                                        $result['corporative_information_cpf']                  = $entry[0]['cpf'][0];
1021                                        $result['corporative_information_rg']                   = $entry[0]['rg'][0];
1022                                        $result['corporative_information_rguf']                 = $entry[0]['rguf'][0];
1023                                }
1024                               
1025                                // MailLists
1026                                $result['maillists_info'] = $this->get_user_maillists($result['mail']);
1027                                if($result['maillists_info'])
1028                                {
1029                                        foreach ($result['maillists_info'] as $maillist)
1030                                        {
1031                                                $result['maillists'][] = $maillist['uid'];
1032                                        }
1033                                }
1034                               
1035                                // Groups
1036                                $justthese = array("gidnumber","cn");
1037                                $filter="(&(phpgwAccountType=g)(memberuid=".$result['uid']."))";
1038                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1039                        ldap_sort($this->ldap, $search, "cn");
1040                        $entries = ldap_get_entries($this->ldap, $search);
1041                        for ($i=0; $i<$entries['count']; $i++)
1042                        {
1043                                $result['groups_ldap'][ $entries[$i]['gidnumber'][0] ] = $entries[$i]['cn'][0];
1044                        }
1045                        }
1046                }
1047                return $result;
1048        }
1049               
1050        function get_user_maillists($mail)
1051        {
1052                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1053                        return false;
1054               
1055                $result = array();
1056               
1057                //Mostra somente os mailists dos contextos do gerente
1058                $justthese = array("uid","mail","uidnumber");
1059                $filter="(&(phpgwAccountType=l)(mailforwardingaddress=$mail))";
1060               
1061                foreach ($this->manager_contexts as $index=>$context)
1062                {
1063                        $search = ldap_search($ldapMasterConnect, $context, $filter, $justthese);
1064                $entries = ldap_get_entries($ldapMasterConnect, $search);
1065               
1066                for ($i=0; $i<$entries['count']; $i++)
1067                {
1068                                $result[ $entries[$i]['uid'][0] ]['uid']                = $entries[$i]['uid'][0];
1069                                $result[ $entries[$i]['uid'][0] ]['mail']               = $entries[$i]['mail'][0];
1070                               
1071                                $a_tmp[] = $entries[$i]['uid'][0];
1072                }
1073                }
1074       
1075        if($a_tmp) {
1076                natcasesort($a_tmp);
1077       
1078                foreach ($a_tmp as $uid)
1079                {
1080                                $return[$uid]['uid']            = $result[$uid]['uid'];
1081                                $return[$uid]['mail']           = $result[$uid]['mail'];
1082                }
1083        }
1084        ldap_close($ldapMasterConnect);
1085                return $return;
1086        }
1087       
1088        function get_group_info($gidnumber)
1089        {
1090                foreach ($this->manager_contexts as $index=>$context)
1091                {
1092                        $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
1093                        $search = ldap_search($this->ldap, $context, $filter);
1094                        $entry = ldap_get_entries($this->ldap, $search);
1095                       
1096                        if ($entry['count'])
1097                        {
1098                                //Pega o dn do setor do grupo.
1099                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1100                                $sector_dn_array = explode(",", $entry[0]['dn']);
1101                                for($i=1; $i<count($sector_dn_array); $i++)
1102                                        $sector_dn .= $sector_dn_array[$i] . ',';
1103                                //Retira ultimo pipe.
1104                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1105               
1106                                $result['context']                              = $sector_dn;
1107                                $result['cn']                                   = $entry[0]['cn'][0];
1108                                $result['description']                  = $entry[0]['description'][0];
1109                                $result['gidnumber']                    = $entry[0]['gidnumber'][0];
1110                                $result['phpgwaccountvisible']  = $entry[0]['phpgwaccountvisible'][0];
1111                                $result['email']                                = $entry[0]['mail'][0];
1112               
1113                                //MemberUid
1114                                for ($i=0; $i<$entry[0]['memberuid']['count']; $i++)
1115                                {
1116                                        $justthese = array("cn","uid","uidnumber");
1117                       
1118                                        // Montagem dinamica do filtro
1119                                        $filter="(&(phpgwAccountType=u)(|";
1120                                        for ($k=0; (($k<10) && ($i<$entry[0]['memberuid']['count'])); $k++)
1121                                        {
1122                                                $filter .= "(uid=".$entry[0]['memberuid'][$i].")";
1123                                                $i++;
1124                                        }
1125                                        $i--;
1126                                        $filter .= "))";
1127                       
1128                                        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1129                                        $user_entry = ldap_get_entries($this->ldap, $search);
1130
1131                                        for ($j=0; $j<$user_entry['count']; $j++)
1132                                        {
1133                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['cn'] = $user_entry[$j]['cn'][0];
1134                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['uidnumber'] = $user_entry[$j]['uidnumber'][0];
1135                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['type'] = 'u';
1136                                        }
1137                                }
1138               
1139                                // Checamos e-mails que não fazem parte do expresso.
1140                                // Criamos um array temporario
1141                                $tmp_array = array();
1142                                if($result['memberuid_info'])
1143                                        foreach ($result['memberuid_info'] as $uid => $user_data)
1144                                        {
1145                                                $tmp_array[] = $uid;
1146                                        }
1147               
1148                                if($entry[0]['memberuid']) {
1149                                        // Retira o count do array
1150                                        array_shift($entry[0]['memberuid']);
1151                                        // Vemos a diferença
1152                                        $array_diff = array_diff($entry[0]['memberuid'], $tmp_array);
1153                                        // Incluimos no resultado                       
1154                                        foreach ($array_diff as $index=>$uid)
1155                                        {
1156                                                $result['memberuid_info'][$uid]['cn'] = $uid;
1157                                        }
1158                                }
1159               
1160                                // Samba
1161                                for ($i=0; $i<$entry[0]['objectclass']['count']; $i++)
1162                                {
1163                                        if ($entry[0]['objectclass'][$i] == 'sambaGroupMapping')
1164                                                $result['sambaGroup'] = true;
1165
1166                                        $a_tmp = explode("-", $entry[0]['sambasid'][0]);
1167                                        array_pop($a_tmp);
1168                                        $result['sambasid'] = implode("-", $a_tmp);
1169                                }
1170                                return $result;
1171                        }
1172                }
1173        }       
1174       
1175        function get_maillist_info($uidnumber)
1176        {
1177               
1178                /* folling referral connection */
1179                $ldap_conn_following_ref = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
1180                if ($ldap_conn_following_ref)
1181                {
1182                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_PROTOCOL_VERSION, 3);
1183                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_REFERRALS, 1);
1184
1185                        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
1186                                ldap_bind($ldap_conn_following_ref, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
1187                }
1188               
1189                foreach ($this->manager_contexts as $index=>$context)
1190                {
1191                        $filter="(&(phpgwAccountType=l)(uidNumber=".$uidnumber."))";
1192                        $search = ldap_search($this->ldap, $context, $filter);
1193                        $entry = ldap_get_entries($this->ldap, $search);
1194                       
1195                        if ($entry['count'])
1196                        {
1197                                //Pega o dn do setor do usuario.
1198                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1199                                $sector_dn_array = explode(",", $entry[0]['dn']);
1200                                for($i=1; $i<count($sector_dn_array); $i++)
1201                                        $sector_dn .= $sector_dn_array[$i] . ',';
1202                                //Retira ultimo pipe.
1203                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1204                       
1205                                $result['context']                              = $sector_dn;
1206                                $result['uidnumber']                    = $entry[0]['uidnumber'][0];
1207                                $result['uid']                                  = strtolower($entry[0]['uid'][0]);
1208                                $result['cn']                                   = $entry[0]['cn'][0];
1209                                $result['mail']                                 = $entry[0]['mail'][0];
1210                                $result['accountStatus']                = $entry[0]['accountstatus'][0];
1211                                $result['phpgwAccountVisible']  = $entry[0]['phpgwaccountvisible'][0];
1212                       
1213                                //Members
1214                                for ($i=0; $i<$entry[0]['mailforwardingaddress']['count']; $i++)
1215                                {
1216                                        $justthese = array("cn", "uidnumber", "uid", "phpgwaccounttype", "mail");
1217                               
1218                                        // Montagem dinamica do filtro, para nao ter muitas conexoes com o ldap
1219                                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|";
1220                                        for ($k=0; (($k<10) && ($i<$entry[0]['mailforwardingaddress']['count'])); $k++)
1221                                        {
1222                                                $filter .= "(mail=".$entry[0]['mailforwardingaddress'][$i].")";
1223                                                $i++;
1224                                        }
1225                                        $i--;
1226                                        $filter .= "))";
1227                               
1228                                        $search = ldap_search($ldap_conn_following_ref, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1229                                        $user_entry = ldap_get_entries($ldap_conn_following_ref, $search);
1230                                                                       
1231                                        for ($j=0; $j<$user_entry['count']; $j++)
1232                                        {
1233                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['uid'] = $user_entry[$j]['uid'][0];
1234                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['cn'] = $user_entry[$j]['cn'][0];
1235                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['type'] = $user_entry[$j]['phpgwaccounttype'][0];
1236                                                $result['mailForwardingAddress'][] = $user_entry[$j]['mail'][0];
1237                                        }
1238                                }
1239
1240                                // Emails não encontrados no ldap
1241                                array_shift($entry[0]['mailforwardingaddress']); //Retira o count do array
1242                                $missing_emails = array_diff($entry[0]['mailforwardingaddress'], $result['mailForwardingAddress']);
1243                               
1244                                // Incluimos estes no resultado
1245                                foreach ($missing_emails as $index=>$mailforwardingaddress)
1246                                {
1247                                        $result['mailForwardingAddress_info'][$mailforwardingaddress]['uid'] = $mailforwardingaddress;
1248                                        $result['mailForwardingAddress_info'][$mailforwardingaddress]['cn'] = 'E-Mail nao encontrado';
1249                                        $result['mailForwardingAddress'][] = $mailforwardingaddress;
1250                                }
1251                               
1252                                ldap_close($ldap_conn_following_ref);
1253                                return $result;
1254                        }
1255                }
1256        }       
1257
1258        function get_maillist_scl_info($uidnumber)
1259        {
1260                foreach ($this->manager_contexts as $index=>$context)
1261                {
1262                        $filter="(&(phpgwAccountType=l)(uidNumber=$uidnumber))";
1263                        $search = ldap_search($this->ldap, $context, $filter);
1264                        $entry = ldap_get_entries($this->ldap, $search);
1265
1266                        if ($entry['count'])
1267                        {
1268                                //Pega o dn do setor do usuario.
1269                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1270                                $sector_dn_array = explode(",", $entry[0]['dn']);
1271                                for($i=1; $i<count($sector_dn_array); $i++)
1272                                        $sector_dn .= $sector_dn_array[$i] . ',';
1273                                //Retira ultimo pipe.
1274                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1275               
1276                                $result['dn']                                           = $entry[0]['dn'];
1277                                $result['context']                                      = $sector_dn;
1278                                $result['uidnumber']                            = $entry[0]['uidnumber'][0];
1279                                $result['uid']                                          = $entry[0]['uid'][0];
1280                                $result['cn']                                           = $entry[0]['cn'][0];
1281                                $result['mail']                                         = $entry[0]['mail'][0];
1282                                $result['accountStatus']                        = $entry[0]['accountstatus'][0];
1283                                $result['phpgwAccountVisible']          = $entry[0]['phpgwaccountvisible'][0];
1284                                $result['accountRestrictive']           = $entry[0]['accountrestrictive'][0];
1285                                $result['participantCanSendMail']       = $entry[0]['participantcansendmail'][0];
1286               
1287                                //Senders
1288                                for ($i=0; $i<$entry[0]['mailsenderaddress']['count']; $i++)
1289                                {
1290                                        $justthese = array("cn", "uidnumber", "uid", "mail");
1291                                        $filter="(&(phpgwAccountType=u)(mail=".$entry[0]['mailsenderaddress'][$i]."))";
1292                                        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1293                                        $user_entry = ldap_get_entries($this->ldap, $search);
1294                       
1295                                        $result['senders_info'][$user_entry[0]['mail'][0]]['uid'] = $user_entry[0]['uid'][0];
1296                                        $result['senders_info'][$user_entry[0]['mail'][0]]['cn'] = $user_entry[0]['cn'][0];
1297                                        $result['members'][] = $user_entry[0]['mail'][0];
1298                                }
1299                                return $result;
1300                        }
1301                }
1302        }       
1303
1304        function group_exist($gidnumber)
1305        {
1306                $justthese = array("cn");
1307                $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
1308                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1309                               
1310                $entry = ldap_get_entries($this->ldap, $search);
1311                if ($entry['count'] == 0)
1312                        return false;
1313                else
1314                        return true;
1315        }
1316
1317        function gidnumbers2cn($gidnumbers)
1318        {
1319                $result = array();
1320                if (count($gidnumbers))
1321                {
1322                        $justthese = array("cn");
1323                        $i = 0;
1324                        foreach ($gidnumbers as $gidnumber)
1325                        {
1326                                $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
1327                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1328                               
1329                                $entry = ldap_get_entries($this->ldap, $search);
1330                                if ($entry['count'] == 0)
1331                                        $result['groups_info'][$i]['cn'] = '_Grupo existe no BD mas não no LDAP';
1332                                else
1333                                        $result['groups_info'][$i]['cn'] = $entry[0]['cn'][0];
1334                                $result['groups_info'][$i]['gidnumber'] = $gidnumber;
1335                       
1336                                /* o gerente pode excluir um grupo de um usuario onde este grupo esta em outra OU ? */
1337                                /* é o mesmo que o manager editar um grupo de outra OU */
1338                                $result['groups_info'][$i]['group_disabled'] = 'true';
1339                                foreach ($this->manager_contexts as $index=>$context)
1340                                {
1341                                        if (strpos(strtolower($entry[0]['dn']), strtolower($context)))
1342                                        {
1343                                                $result['groups_info'][$i]['group_disabled'] = 'false';
1344                                        }
1345                                }
1346
1347                                $i++;
1348                        }
1349                }
1350                return $result;
1351        }
1352
1353        function uidnumber2uid($uidnumber)
1354        {
1355                $justthese = array("uid");
1356                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
1357                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1358                $entry = ldap_get_entries($this->ldap, $search);
1359                return $entry[0]['uid'][0];
1360        }
1361
1362        function uidnumber2mail($uidnumber)
1363        {
1364                $justthese = array("mail");
1365                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
1366                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1367                $entry = ldap_get_entries($this->ldap, $search);
1368                return $entry[0]['mail'][0];
1369        }
1370
1371       
1372        function change_user_context($dn, $newrdn, $newparent)
1373        {
1374                if (!ldap_rename ( $this->ldap, $dn, $newrdn, $newparent, true ))
1375                {
1376                        $return['status'] = false;
1377                        $return['msg'] = 'Erro em ldap_funcitons->change_user_context: ' . ldap_error($this->ldap);
1378                }
1379                else
1380                        $return['status'] = true;
1381               
1382                return $return;
1383        }
1384       
1385        function replace_user_attributes($dn, $ldap_mod_replace)
1386        {
1387                if (!@ldap_mod_replace ( $this->ldap, $dn, $ldap_mod_replace ))
1388                {
1389                        $return['status'] = false;
1390                        $return['error_number'] = ldap_errno($this->ldap);
1391                        $return['msg'] = 'Erro em ldap_funcitons->replace_user_attributes: ' . ldap_error($this->ldap);
1392                }
1393                else
1394                        $return['status'] = true;
1395               
1396                return $return;
1397        }
1398       
1399        function add_user_attributes($dn, $ldap_add)
1400        {
1401                if (!@ldap_mod_add ( $this->ldap, $dn, $ldap_add ))
1402                {
1403                        $return['status'] = false;
1404                        $return['error_number'] = ldap_errno($this->ldap);
1405                        $return['msg'] = 'Erro em ldap_funcitons->add_user_attributes: ' . ldap_error($this->ldap);
1406                }
1407                else
1408                        $return['status'] = true;
1409               
1410                return $return;
1411        }
1412       
1413        function remove_user_attributes($dn, $ldap_remove)
1414        {
1415                if (!@ldap_mod_del ( $this->ldap, $dn, $ldap_remove ))
1416                {
1417                        $return['status'] = false;
1418                        $return['msg'] = 'Erro em ldap_funcitons->remove_user_attributes: ' . ldap_error($this->ldap);
1419                }
1420                else
1421                        $return['status'] = true;
1422               
1423                return $return;
1424        }
1425       
1426        function set_user_password($uid, $password)
1427        {
1428                $justthese = array("userPassword");
1429                $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
1430                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1431            $entry = ldap_get_entries($this->ldap, $search);
1432                $dn = $entry[0]['dn'];
1433                $userPassword = $entry[0]['userpassword'][0];
1434                $ldap_mod_replace['userPassword'] = $password;
1435                $this->replace_user_attributes($dn, $ldap_mod_replace);
1436                return $userPassword;
1437        }
1438       
1439        function delete_user($user_info)
1440        {
1441                // Verifica acesso do gerente (OU) ao tentar deletar um usuário.
1442                $manager_access = false;
1443                foreach ($this->manager_contexts as $index=>$context)
1444                {
1445                        if ( (strpos(strtolower($user_info['context']), strtolower($context))) || (strtolower($user_info['context']) == strtolower($context)) )
1446                        {
1447                                $manager_access = true;
1448                                break;
1449                        }
1450                }
1451                if (!$manager_access)
1452                {
1453                        $return['status'] = false;
1454                        $return['msg'] .= 'Você não tem acesso para deletar este usuário.';
1455                        return $return;
1456                }
1457               
1458                $return['status'] = true;
1459                $return['msg'] = "";
1460                               
1461                // GROUPS
1462                $attrs = array();
1463                $attrs['memberuid'] = $user_info['uid'];
1464               
1465                if (count($user_info['groups_info']))
1466                {
1467                        foreach ($user_info['groups_info'] as $group_info)
1468                        {
1469                                $gidnumber = $group_info['gidnumber'];
1470                                $justthese = array("dn");
1471                                $filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
1472                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1473                        $entry = ldap_get_entries($this->ldap, $search);
1474                                $dn = $entry[0]['dn'];
1475
1476                                if (!@ldap_mod_del($this->ldap, $dn, $attrs))
1477                                {
1478                                        $return['status'] = false;
1479                                        $return['msg'] .= "Erro em ldap_functions->delete_user from group ($dn): " . ldap_error($this->ldap);
1480                                }
1481                        }
1482                }
1483               
1484                //INSTITUTIONAL ACCOUNTS
1485                $attrs = array();
1486                $attrs['mailForwardingAddress'] = $user_info['mail'];
1487               
1488                $justthese = array("dn");
1489                $filter="(&(phpgwAccountType=i)(mailforwardingaddress=".$user_info['mail']."))";
1490                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1491            $entries = ldap_get_entries($this->ldap, $search);
1492               
1493                for ($i=0; $i<$entries['count']; $i++)
1494                {
1495                        if ( !@ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs) )
1496                        {
1497                                $result['status'] = false;
1498                                $result['msg'] = "Erro na funcao ldap_functions->delete_user, instutional_accounts.\nRetorno do servidor:" . ldap_error($this->ldap);
1499                        }
1500                }
1501               
1502                // MAILLISTS
1503                $attrs = array();
1504                $attrs['mailForwardingAddress'] = $user_info['mail'];
1505               
1506                if (count($user_info['maillists_info']))
1507                {
1508                       
1509                        if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1510                        {
1511                                $return['status'] = false;
1512                                $return['msg'] .= 'Erro ao conectar ao ldap_master: ' . ldap_error($this->ldap);
1513                                return $return;
1514                        }
1515                       
1516                        foreach ($user_info['maillists_info'] as $maillists_info)
1517                        {
1518                                $uid = $maillists_info['uid'];
1519                                $justthese = array("dn");
1520                                $filter="(&(phpgwAccountType=l)(uid=".$uid."))";
1521                                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1522                        $entry = ldap_get_entries($ldapMasterConnect, $search);
1523                                $dn = $entry[0]['dn'];
1524                       
1525                                if (!@ldap_mod_del($ldapMasterConnect, $dn, $attrs))
1526                                {
1527                                        $return['status'] = false;
1528                                        if (ldap_errno($ldapMasterConnect) == '50')
1529                                        {
1530                                                $result['msg'] = "Erro na funcao ldap_functions->add_user2maillist.\n" .
1531                                                                                 "O usuário utilizado para gravação no LDAP, DEVE ter direito de escrita.\n".
1532                                                                                 "O usuário " . $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] . " não tem este direito.\n".
1533                                                                                "Edite \"Configuração Global do Catálogo\", no módulo Administrador, Catálogo de Endereços e adicione um usuário com direitos de escrita.";
1534                                        }
1535                                        else
1536                                                $result['msg'] = "Erro na funcao ldap_functions->add_user2maillist.\nRetorno do servidor:" . ldap_error($ldapMasterConnect);
1537                                }
1538                        }
1539                        ldap_close($ldapMasterConnect);
1540                }
1541                       
1542                // UID
1543                $dn = "uid=" . $user_info['uid'] . "," . $user_info['context'];
1544                if (!@ldap_delete($this->ldap, $dn))
1545                {
1546                        $return['status'] = false;
1547                        $return['msg'] .= 'Erro em ldap_funcitons->delete_user, listas de email: ' . ldap_error($this->ldap);
1548                }
1549               
1550                return $return;
1551        }
1552       
1553        function delete_maillist($uidnumber, $mail)
1554        {
1555                $return['status'] = true;
1556               
1557                $justthese = array("dn");
1558               
1559                // remove listas dentro de listas
1560                $filter="(&(phpgwAccountType=l)(mailForwardingAddress=".$mail."))";
1561                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1562                $entry = ldap_get_entries($this->ldap, $search);
1563                $attrs['mailForwardingAddress'] = $mail;
1564                for ($i=0; $i<=$entry['count']; $i++)
1565            {
1566                        $dn = $entry[$i]['dn'];
1567                @ldap_mod_del ( $this->ldap, $dn,  $attrs);
1568            }
1569               
1570                $filter="(&(phpgwAccountType=l)(uidnumber=".$uidnumber."))";
1571                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1572                $entry = ldap_get_entries($this->ldap, $search);
1573                $dn = $entry[0]['dn'];
1574               
1575                if (!@ldap_delete($this->ldap, $dn))
1576                {
1577                        $return['status'] = false;
1578                        $return['msg'] .= 'Erro em ldap_funcitons->delete_maillist, listas de email: ' . ldap_error($this->ldap);
1579                }
1580               
1581                return $return;
1582        }
1583
1584        function delete_group($gidnumber)
1585        {
1586                $return['status'] = true;
1587               
1588                $justthese = array("dn");
1589                $filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
1590                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1591                $entry = ldap_get_entries($this->ldap, $search);
1592                $dn = $entry[0]['dn'];
1593               
1594                if (!@ldap_delete($this->ldap, $dn))
1595                {
1596                        $return['status'] = false;
1597                        $return['msg'] .= 'Erro em ldap_funcitons->delete_maillist, listas de email: ' . ldap_error($this->ldap);
1598                }
1599               
1600                return $return;
1601        }
1602
1603        function check_access_to_renamed($uid)
1604        {
1605                $justthese = array("dn");
1606                $filter="(&(phpgwAccountType=u)(uid=$uid))";
1607               
1608                foreach ($this->manager_contexts as $index=>$context)
1609                {
1610                        $search = ldap_search($this->ldap, $context, $filter, $justthese);
1611                        $entry = ldap_get_entries($this->ldap, $search);
1612                        if ($entry['count'])
1613                                return true;
1614                }
1615            return false;
1616        }
1617       
1618        function rename_uid($uid, $new_uid)
1619        {
1620                $return['status'] = true;
1621               
1622                $justthese = array("dn");
1623                $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
1624                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1625            $entry = ldap_get_entries($this->ldap, $search);
1626                $dn = $entry[0]['dn'];
1627               
1628                $explode_dn = ldap_explode_dn($dn, 0);
1629                $rdn = "uid=" . $new_uid;
1630
1631                $parent = array();
1632                for ($j=1; $j<(count($explode_dn)-1); $j++)
1633                        $parent[] = $explode_dn[$j];
1634                $parent = implode(",", $parent);
1635               
1636                $return['new_dn'] = $rdn . ',' . $parent;
1637                       
1638                if (!@ldap_rename($this->ldap, $dn, $rdn, $parent, false))
1639                {
1640                        $return['status'] = false;
1641                        $return['msg'] .= 'Erro em ldap_funcitons->rename_uid: ' . ldap_error($this->ldap);
1642                }
1643               
1644                //Grupos
1645                $justthese = array("dn");
1646                $filter="(&(phpgwAccountType=g)(memberuid=".$uid."))";
1647                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1648            $entry = ldap_get_entries($this->ldap, $search);
1649        $array_mod_add['memberUid'] = $new_uid;
1650        $array_mod_del['memberUid'] = $uid;
1651
1652            for ($i=0; $i<=$entry['count']; $i++)
1653            {
1654                $dn = $entry[$i]['dn'];
1655                @ldap_mod_add ( $this->ldap, $dn,  $array_mod_add);
1656                @ldap_mod_del ( $this->ldap, $dn,  $array_mod_del);
1657            }
1658                return $return;
1659        }
1660
1661        function rename_cn($cn, $new_cn)
1662        {
1663                $return['status'] = true;
1664               
1665                $justthese = array("dn");
1666                $filter="(&(phpgwAccountType=g)(uid=".$cn."))";
1667                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1668            $entry = ldap_get_entries($this->ldap, $search);
1669                $dn = $entry[0]['dn'];
1670               
1671                $explode_dn = ldap_explode_dn($dn, 0);
1672                $rdn = "cn=" . $new_cn;
1673
1674                $parent = array();
1675                for ($j=1; $j<(count($explode_dn)-1); $j++)
1676                        $parent[] = $explode_dn[$j];
1677                $parent = implode(",", $parent);
1678               
1679                $return['new_dn'] = $rdn . ',' . $parent;
1680                       
1681                if (!@ldap_rename($this->ldap, $dn, $rdn, $parent, false))
1682                {
1683                        $return['status'] = false;
1684                }
1685               
1686                return $return;
1687        }
1688       
1689        function exist_sambadomains($contexts, $sambaDomainName)
1690        {
1691                $justthese = array("dn");
1692                $filter="(&(objectClass=sambaDomain)(sambaDomainName=$sambaDomainName))";
1693               
1694                foreach ($contexts as $index=>$context)
1695                {
1696                        $search = ldap_search($this->ldap, $context, $filter, $justthese);
1697                    $entry = ldap_get_entries($this->ldap, $search);
1698           
1699                        if ($entry['count'])
1700                                return true;
1701                }
1702                return false;
1703        }
1704       
1705        // Primeiro nilvel de organização.
1706        function exist_sambadomains_in_context($params)
1707        {
1708                $dn = $GLOBALS['phpgw_info']['server']['ldap_context'];
1709                $array_dn = ldap_explode_dn ( $dn, 0 );
1710               
1711                $context = $params['context'];
1712                $array_context = ldap_explode_dn ( $context, 0 );
1713               
1714                // Pego o setor no caso do contexto ser um sub-setor.
1715                if (($array_dn['count']+1) < ($array_context['count']))
1716                {
1717                        // inverto o array_dn para poder retirar o count
1718                        $array_dn_reverse  = array_reverse ( $array_dn, false );
1719                       
1720                        //retiro o count
1721                        array_pop($array_dn_reverse);
1722                       
1723                        //incluo o setor no dn
1724                        array_push ( $array_dn_reverse,  $array_context[ $array_context['count'] - 1 - $array_dn['count']]);
1725                       
1726                        // Volto a ordem natural
1727                        $array_dn  = array_reverse ( $array_dn_reverse, false );
1728                       
1729                        // Implodo
1730                        $context = implode ( ",", $array_dn );
1731                }
1732               
1733                $justthese = array("dn","sambaDomainName");
1734                $filter="(objectClass=sambaDomain)";
1735                $search = ldap_list($this->ldap, $context, $filter, $justthese);
1736            $entry = ldap_get_entries($this->ldap, $search);
1737           
1738            for ($i=0; $i<$entry['count']; $i++)
1739            {
1740                        $return['sambaDomains'][$i] = $entry[$i]['sambadomainname'][0];
1741            }
1742           
1743                if ($entry['count'])
1744                        $return['status'] = true;
1745                else
1746                        $return['status'] = false;
1747                       
1748                return $return;
1749        }
1750        function exist_domain_name_sid($sambadomainname, $sambasid)
1751        {
1752                $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
1753
1754                $justthese = array("dn","sambaDomainName");
1755                $filter="(&(objectClass=sambaDomain)(sambaSID=$sambasid)(sambaDomainName=$sambadomainname))";
1756                $search = ldap_search($this->ldap, $context, $filter, $justthese);
1757            $count_entries = ldap_count_entries($this->ldap, $search);
1758           
1759            if ($count_entries > 0)
1760                return true;
1761            else
1762                return false;
1763        }
1764       
1765        function add_sambadomain($sambadomainname, $sambasid, $context)
1766        {
1767                $result = array();
1768               
1769                $dn                                                             = "sambaDomainName=$sambadomainname,$context";
1770                $entry['sambaSID']                                      = $sambasid;
1771                $entry['objectClass']                           = 'sambaDomain';
1772                $entry['sambaAlgorithmicRidBase']       = '1000';
1773                $entry['sambaDomainName']                       = $sambadomainname;
1774               
1775                if (!@ldap_add ( $this->ldap, $dn, $entry ))
1776                {
1777                        $return['status'] = false;
1778                        $return['msg'] = "Erro ao adicionar Samba Domain";
1779                }
1780                else
1781                        $return['status'] = true;
1782               
1783                return $return;
1784        }
1785       
1786        function delete_sambadomain($sambadomainname)
1787        {
1788                $return['status'] = true;
1789                $filter="(sambaDomainName=$sambadomainname)";
1790                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter);
1791            $entry = ldap_get_entries($this->ldap, $search);
1792         
1793                if ($entry['count'] != 0)
1794            {
1795                        $dn = $entry[0]['dn'];
1796                       
1797                        if (!@ldap_delete($this->ldap, $dn))
1798                        {
1799                                $return['status'] = false;
1800                                $return['msg'] .= "Erro em ldap_funcitons->delete_sambadomain ($sambadomainname).\nRetorno do servidor: " . ldap_error($this->ldap);
1801                        }
1802            }
1803           
1804                return $return;
1805        }
1806       
1807        function search_user($params)
1808        {
1809                $search = $params['search'];
1810                $justthese = array("cn","uid", "mail");
1811        $users_list=ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], "(&(phpgwAccountType=u) (|(cn=*$search*)(mail=$search*)) )", $justthese);
1812       
1813        if (ldap_count_entries($this->ldap, $users_list) == 0)
1814        {
1815                $return['status'] = 'false';
1816                $return['msg'] = 'Nenhum resultado encontrado.';
1817                return $return;
1818        }
1819       
1820        ldap_sort($this->ldap, $users_list, "cn");
1821       
1822        $entries = ldap_get_entries($this->ldap, $users_list);
1823               
1824                $options = '';
1825                for ($i=0; $i<$entries['count']; $i++)
1826                {
1827                        $options .= "<option value=" . $entries[$i]['uid'][0] . ">" . $entries[$i]['cn'][0] . " (".$entries[$i]['mail'][0].")" . "</option>";
1828                }
1829       
1830        return $options;               
1831        }
1832       
1833        function create_institutional_accounts($params)
1834        {
1835                /* Begin: Access verification */
1836                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'add_institutional_accounts'))
1837                {
1838                        $return['status'] = false;
1839                        $return['msg'] = $this->functions->lang('You do not have right to create institutional accounts') . ".";
1840                        return $return;
1841                }
1842               
1843                $access_granted = false;
1844                foreach ($this->manager_contexts as $idx=>$manager_context)
1845                {
1846                        if (stristr($params['context'], $manager_context))
1847                        {
1848                                $access_granted = true;
1849                                break;
1850                        }
1851                }
1852                if (!$access_granted)
1853                {
1854                        $return['status'] = false;
1855                        $return['msg'] = $this->functions->lang('You do not have access to this organization') . ".";
1856                        return $return;
1857                }
1858                /* End: Access verification */
1859
1860                /* Begin: Validation */
1861                if ( (empty($params['cn'])) || (empty($params['mail'])) )
1862                {
1863                        $result['status'] = false;
1864                        $result['msg']  = $this->functions->lang('Field mail or name is empty');
1865                        return $result;
1866                }
1867
1868                if (! eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$", $params['mail']) )
1869                {
1870                        $result['status'] = false;
1871                        $result['msg']  = $this->functions->lang('Field mail is not formed correcty') . '.';
1872                        return $result;
1873                }
1874
1875                $uid = 'institutional_account_' . $params['mail'];
1876                $dn = "uid=$uid," . $params['context'];
1877
1878                $filter = "(mail=".$params['mail'].")";
1879                $justthese = array("cn");
1880                $search = @ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1881                $entries = @ldap_get_entries($this->ldap,$search);
1882                if ($entries['count'] != 0)
1883                {
1884                        $result['status'] = false;
1885                        $result['msg'] = $this->functions->lang('Field mail already in use');
1886                        return $result;
1887                }
1888                /* End: Validation */
1889                                               
1890                $info = array();
1891                $info['cn']                                     = $params['cn'];
1892                $info['sn']                                     = $params['cn'];
1893                $info['uid']                            = $uid;
1894                $info['mail']                           = $params['mail'];
1895                $info['phpgwAccountType']       = 'i';
1896                $info['objectClass'][]          = 'inetOrgPerson';
1897                $info['objectClass'][]          = 'phpgwAccount';
1898                $info['objectClass'][]          = 'top';
1899                $info['objectClass'][]          = 'person';
1900                $info['objectClass'][]          = 'qmailUser';
1901                $info['objectClass'][]          = 'organizationalPerson';
1902               
1903                if ($params['accountStatus'] == 'on')
1904                {
1905                        $info['accountStatus'] = 'active';
1906                }
1907                if ($params['phpgwAccountVisible'] == 'on')
1908                {
1909                        $info['phpgwAccountVisible'] = '-1';
1910                }
1911               
1912                if (!empty($params['owners']))
1913                {
1914                        foreach($params['owners'] as $index=>$uidnumber)
1915                        {
1916                                $info['mailForwardingAddress'][] = $this->uidnumber2mail($uidnumber);
1917                        }
1918                }               
1919               
1920                $result = array();
1921                if (!@ldap_add ( $this->ldap, $dn, $info ))
1922                {
1923                        $result['status'] = false;
1924                        $result['msg']  = $this->functions->lang('Error in function') . ' ldap_functions->create_institutional_accounts';
1925                        $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
1926                }
1927                else
1928                        $result['status'] = true;
1929               
1930                return $result;
1931        }
1932       
1933        function save_institutional_accounts($params)
1934        {
1935                /* Begin: Access verification */
1936                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_institutional_accounts'))
1937                {
1938                        $return['status'] = false;
1939                        $return['msg'] = $this->functions->lang('You do not have right to edit institutional accounts') . ".";
1940                        return $return;
1941                }
1942                $access_granted = false;
1943                foreach ($this->manager_contexts as $idx=>$manager_context)
1944                {
1945                        if (stristr($params['context'], $manager_context))
1946                        {
1947                                $access_granted = true;
1948                                break;
1949                        }
1950                }
1951                if (!$access_granted)
1952                {
1953                        $return['status'] = false;
1954                        $return['msg'] = $this->functions->lang('You do not have access to this organization') . ".";
1955                        return $return;
1956                }
1957                /* End: Access verification */
1958               
1959                /* Begin: Validation */
1960                if ( (empty($params['cn'])) || (empty($params['mail'])) )
1961                {
1962                        $result['status'] = false;
1963                        $result['msg']  = $this->functions->lang('Field mail or name is empty') . '.';
1964                        return $result;
1965                }
1966
1967                if (! eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$", $params['mail']) )
1968                {
1969                        $result['status'] = false;
1970                        $result['msg']  = $this->functions->lang('Field mail is not formed correcty') . '.';
1971                        return $result;
1972                }
1973
1974                $uid = 'institutional_account_' . $params['mail'];
1975                $dn = strtolower("uid=$uid," . $params['context']);
1976                $anchor = strtolower($params['anchor']);
1977
1978                $filter = "(mail=".$params['mail'].")";
1979                $justthese = array("cn");
1980                $search = @ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1981                $entries = @ldap_get_entries($this->ldap,$search);
1982               
1983                if ( ($entries['count'] > 1) || (($entries['count'] == 1) && ($entries[0]['dn'] != $anchor)) )
1984                {
1985                        $result['status'] = false;
1986                        $result['msg'] = $this->functions->lang('Field mail already in use.');
1987                        return $result;
1988                }
1989                /* End: Validation */
1990               
1991                $result = array();
1992                $result['status'] = true;
1993               
1994                if ($anchor != $dn)
1995                {
1996                        if (!@ldap_rename($this->ldap, $anchor, "uid=$uid", $params['context'], true))
1997                        {
1998                                $result['status'] = false;
1999                                $result['msg']  = $this->functions->lang('Error in function') . ' ldap_functions->save_institutional_accounts: ldap_rename';
2000                                $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
2001                        }
2002                }
2003               
2004                $info = array();
2005                $info['cn']                                     = $params['cn'];
2006                $info['sn']                                     = $params['cn'];
2007                $info['uid']                            = $uid;
2008                $info['mail']                           = $params['mail'];
2009               
2010                if ($params['accountStatus'] == 'on')
2011                        $info['accountStatus'] = 'active';
2012                else
2013                        $info['accountStatus'] = array();
2014               
2015                if ($params['phpgwAccountVisible'] == 'on')
2016                        $info['phpgwAccountVisible'] = '-1';
2017                else
2018                        $info['phpgwAccountVisible'] = array();
2019               
2020                if (!empty($params['owners']))
2021                {
2022                        foreach($params['owners'] as $index=>$uidnumber)
2023                        {
2024                                $mailForwardingAddress = $this->uidnumber2mail($uidnumber);
2025                                if ($mailForwardingAddress != '')
2026                                        $info['mailForwardingAddress'][] = $mailForwardingAddress;
2027                        }
2028                }
2029                else
2030                        $info['mailForwardingAddress'] = array();
2031               
2032                if (!@ldap_modify ( $this->ldap, $dn, $info ))
2033                {
2034                        $result['status'] = false;
2035                        $result['msg']  = $this->functions->lang('Error in function') . ' ldap_functions->save_institutional_accounts: ldap_modify';
2036                        $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
2037                }
2038
2039                return $result;
2040        }
2041       
2042        function get_institutional_accounts($params)
2043        {
2044                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'list_institutional_accounts'))
2045                {
2046                        $return['status'] = false;
2047                        $return['msg'] = $this->functions->lang('You do not have right to list institutional accounts') . ".";
2048                        return $return;
2049                }
2050
2051                $input = $params['input'];
2052                $justthese = array("cn", "mail", "uid");
2053                $trs = array();
2054                               
2055                foreach ($this->manager_contexts as $idx=>$context)
2056                {
2057                $institutional_accounts = ldap_search($this->ldap, $context, ("(&(phpgwAccountType=i)(|(mail=$input*)(cn=*$input*)))"), $justthese);
2058                $entries = ldap_get_entries($this->ldap, $institutional_accounts);
2059               
2060                        for ($i=0; $i<$entries['count']; $i++)
2061                        {
2062                                $tr = "<tr class='normal' onMouseOver=this.className='selected' onMouseOut=this.className='normal'><td onClick=edit_institutional_account('".$entries[$i]['uid'][0]."')>" . $entries[$i]['cn'][0] . "</td><td onClick=edit_institutional_account('".$entries[$i]['uid'][0]."')>" . $entries[$i]['mail'][0] . "</td><td align='center' onClick=delete_institutional_accounts('".$entries[$i]['uid'][0]."')><img HEIGHT='16' WIDTH='16' src=./expressoAdmin1_2/templates/default/images/delete.png></td></tr>";
2063                                $trs[$tr] = $entries[$i]['cn'][0];
2064                        }
2065                }
2066       
2067        $trs_string = '';
2068        if (count($trs))
2069        {
2070                natcasesort($trs);
2071                foreach ($trs as $tr=>$cn)
2072                {
2073                        $trs_string .= $tr;
2074                }
2075        }
2076       
2077        $return['status'] = 'true';
2078        $return['trs'] = $trs_string;
2079        return $return;
2080        }
2081       
2082        function get_institutional_account_data($params)
2083        {
2084                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_institutional_accounts'))
2085                {
2086                        $return['status'] = false;
2087                        $return['msg'] = $this->functions->lang('You do not have right to list institutional accounts') . ".";
2088                        return $return;
2089                }
2090               
2091                $uid = $params['uid'];
2092                $justthese = array("accountStatus", "phpgwAccountVisible", "cn", "mail", "mailForwardingAddress");
2093                               
2094        $institutional_accounts = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=i)(uid=$uid))"), $justthese);
2095        $entrie = ldap_get_entries($this->ldap, $institutional_accounts);
2096               
2097                if ($entrie['count'] != 1)
2098                {
2099                        $return['status'] = 'false';
2100                        $return['msg'] = 'Problemas carregando dados.';
2101                }
2102                else
2103                {
2104                        $tmp_user_context = split(",", $entrie[0]['dn']);
2105                        $tmp_reverse_user_context = array_reverse($tmp_user_context);
2106                        array_pop($tmp_reverse_user_context);
2107                        $return['user_context'] = implode(",", array_reverse($tmp_reverse_user_context));
2108                       
2109                        $return['status'] = 'true';
2110                        $return['accountStatus']                = $entrie[0]['accountstatus'][0];
2111                        $return['phpgwAccountVisible']  = $entrie[0]['phpgwaccountvisible'][0];
2112                        $return['cn']                                   = $entrie[0]['cn'][0];
2113                        $return['mail']                                 = $entrie[0]['mail'][0];
2114
2115                        if ($entrie[0]['mailforwardingaddress']['count'] > 0)
2116                        {
2117                                $a_cn = array();
2118                                for ($i=0; $i<$entrie[0]['mailforwardingaddress']['count']; $i++)
2119                                {
2120                                        $tmp = $this->mailforwardingaddress2uidnumber($entrie[0]['mailforwardingaddress'][$i]);
2121                                        if (!$tmp) {}
2122                                        else
2123                                                $a_cn[$tmp['uidnumber']] = $tmp['cn'];
2124                                }
2125                                natcasesort($a_cn);
2126                                foreach($a_cn as $uidnumber => $cn)
2127                                {
2128                                        $return['owners'] .= '<option value='. $uidnumber .'>' . $cn . '</option>';
2129                                }
2130                        }
2131                }
2132               
2133                return $return;
2134        }
2135       
2136        function mailforwardingaddress2uidnumber($mail)
2137        {
2138                $justthese = array("uidnumber","cn");
2139        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=u)(mail=$mail))"), $justthese);
2140        $entrie = ldap_get_entries($this->ldap, $search);
2141                if ($entrie['count'] != 1)
2142                        return false;
2143                else
2144                {
2145                        $return['uidnumber'] = $entrie[0]['uidnumber'][0];
2146                        $return['cn'] = $entrie[0]['cn'][0];
2147                        return $return;
2148                }
2149        }
2150       
2151        function delete_institutional_account_data($params)
2152        {
2153                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'remove_institutional_accounts'))
2154                {
2155                        $return['status'] = false;
2156                        $return['msg'] = $this->functions->lang('You do not have right to delete institutional accounts') . ".";
2157                        return $return;
2158                }
2159
2160                $uid = $params['uid'];
2161                $return['status'] = true;
2162                               
2163                $justthese = array("cn");
2164        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=i)(uid=$uid))"), $justthese);
2165        $entrie = ldap_get_entries($this->ldap, $search);
2166                if ($entrie['count'] > 1)
2167                {
2168                        $return['status'] = false;
2169                        $return['msg']  = $this->functions->lang('More then one uid was found');
2170                        return $return;
2171                }               
2172                if ($entrie['count'] == 0)
2173                {
2174                        $return['status'] = false;
2175                        $return['msg']  = $this->functions->lang('No uid was found');
2176                        return $return;
2177                }               
2178               
2179                $dn = $entrie[0]['dn'];
2180                if (!@ldap_delete($this->ldap, $dn))
2181                {
2182                        $return['status'] = false;
2183                        $return['msg']  = $this->functions->lang('Error in function') . " ldap_functions->delete_institutional_accounts: ldap_delete";
2184                        $return['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
2185                        return $return;
2186                }
2187               
2188                return $return;
2189        }
2190       
2191        function replace_mail_from_institutional_account($newMail, $oldMail)
2192        {
2193                $filter = "(&(phpgwAccountType=i)(mailforwardingaddress=$oldMail))";
2194                $justthese = array("dn");
2195                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2196                $entries = ldap_get_entries($this->ldap, $search);
2197                $result['status'] = true;
2198                for ($i=0; $i<$entries['count']; $i++)
2199                {
2200                        $attrs['mailforwardingaddress'] = $oldMail;
2201                        $res1 = @ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs);
2202                        $attrs['mailforwardingaddress'] = $newMail;
2203                        $res2 = @ldap_mod_add($this->ldap, $entries[$i]['dn'], $attrs);
2204               
2205                        if ((!$res1) || (!$res2))
2206                        {
2207                                $result['status'] = false;
2208                                $return['msg']  = $this->functions->lang('Error in function') . " ldap_functions->replace_mail_from_institutional_account.";
2209                        }
2210                }
2211               
2212                return $result;
2213        }
2214}
2215?>
Note: See TracBrowser for help on using the repository browser.