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

Revision 317, 68.6 KB checked in by niltonneto, 16 years ago (diff)

Versionamento feito pelo desenvolvedor (jakjr).

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