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

Revision 8178, 104.1 KB checked in by angelo, 11 years ago (diff)

Ticket #3463 - Organizacao LDAP sendo carregada de maneira inconsistente

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2                /***************************************************************************
3                * Expresso Livre                                                           *
4                * http://www.expressolivre.org                                             *
5                * --------------------------------------------                             *
6                *  This program is free software; you can redistribute it and/or modify it *
7                *  under the terms of the GNU General Public License as published by the   *
8                *  Free Software Foundation; either version 2 of the License, or (at your  *
9                *  option) any later version.                                              *
10                \**************************************************************************/
11               
12define('PHPGW_INCLUDE_ROOT','../');
13define('PHPGW_API_INC','../phpgwapi/inc');     
14include_once(PHPGW_API_INC.'/class.common.inc.php');
15include_once('class.functions.inc.php');
16include_once('class.db_functions.inc.php');
17
18function ldapRebind($ldap_connection, $ldap_url)
19{
20        // Enquanto estivermos utilizando referral na arvore ldap, teremos que continuar a utilizar o usuário sistemas:expresso.
21        // Depois, quando não existir mais referral, não existirá a necessidade de ldapRebind.
22        //ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
23        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
24        {
25                @ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
26        }
27}
28
29class ldap_functions
30{
31        var $ldap;
32        var $current_config;
33        var $functions;
34        var $manager_contexts;
35        var $db_functions;
36       
37        function ldap_functions(){             
38                $GLOBALS['phpgw_info']['server'] = $_SESSION['phpgw_info']['expresso']['server'];
39                $this->current_config = $_SESSION['phpgw_info']['expresso']['expressoAdmin'];
40                $common = new common();
41               
42                if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) &&
43                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) &&
44                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) )
45                {
46                        $this->ldap = $common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_master_host'],
47                                                                                           $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'],
48                                                                                           $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
49                }
50                else
51                {
52                        $this->ldap = $common->ldapConnect();
53                }
54               
55                $this->db_functions = new db_functions();
56                $this->functions = new functions;
57                $manager_acl = $this->functions->read_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid']);
58                $this->manager_contexts = $manager_acl['contexts'];
59        }
60
61        function noAccess( $context, $target, $label = false )
62                {
63            if( !$label )
64                $label = str_replace( '_', ' ', $target );
65                       
66            if (!$this->functions->check_acl( $_SESSION['phpgw_info']['expresso']['user']['account_lid'], $target ))
67                        {
68                                $return['status'] = false;
69                $return['msg'] = $this->functions->lang("You do not have right to $label") . ".";
70                                return $return;
71                        }
72                       
73                        $access_granted = false;
74
75                        foreach ($this->manager_contexts as $idx=>$manager_context)
76                        {
77                    if (stristr($context, $manager_context))
78                                {
79                                        $access_granted = true;
80                                        break;
81                                }
82                        }
83                       
84                        if (!$access_granted)
85                        {
86                                $return['status'] = false;                             
87                                $return['msg'] = $this->functions->lang('You do not have access to this organization') . ".";                                                   
88                                return $return;
89                        }                       
90
91            return( false );
92        }
93       
94        function create_institutional_accounts($params)
95        {
96                /* Begin: Access verification */
97                $forbidden = $this->noAccess( $params['context'], 'add_institutional_accounts', 'create institutional accounts' );
98
99                if( $forbidden )
100                    return( $forbidden );
101//              if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'add_institutional_accounts'))
102//              {
103//                      $return['status'] = false;
104//                      $return['msg'] = $this->functions->lang('You do not have right to create institutional accounts') . ".";
105//                      return $return;
106//              }
107//             
108//              $access_granted = false;
109//              foreach ($this->manager_contexts as $idx=>$manager_context)
110//              {
111//                      if (stristr($params['context'], $manager_context))
112//                      {
113//                              $access_granted = true;
114//                              break;
115//                      }
116//              }
117//              if (!$access_granted)
118//              {
119//                      $return['status'] = false;
120//                      $return['msg'] = $this->functions->lang('You do not have access to this organization') . ".";
121//                      return $return;
122//              }
123                        /* End: Access verification */
124       
125                /* Begin: Validation */
126                if ( (empty($params['cn'])) || (empty($params['mail'])) )
127                {
128                        $result['status'] = false;
129                        $result['msg']  = $this->functions->lang('Field mail or name is empty');
130                        return $result;
131                }
132
133                if (! preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/i', $params['mail']) )
134                {
135                        $result['status'] = false;
136                        $result['msg']  = $this->functions->lang('Field mail is not formed correcty') . '.';
137                        return $result;
138                }
139
140                $uid = 'institutional_account_' . $params['mail'];
141                $dn = "uid=$uid," . $params['context'];
142
143                $filter = "(mail=".$params['mail'].")";
144                $justthese = array("cn");
145                $search = @ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
146                $entries = @ldap_get_entries($this->ldap,$search);
147                if ($entries['count'] != 0)
148                {
149                        $result['status'] = false;
150                        $result['msg'] = $this->functions->lang('Field mail already in use');
151                        return $result;
152                }
153                /* End: Validation */
154                                               
155                $info = array();
156                $info['cn']                                     = $params['cn'];
157                $info['sn']                                     = $params['cn'];
158                $info['uid']                            = $uid;
159                $info['mail']                           = $params['mail'];
160                $info['description']            = iconv("ISO-8859-1","UTF-8//TRANSLIT",$params['desc']);
161                $info['phpgwAccountType']       = 'i';
162                $info['objectClass'][]          = 'inetOrgPerson';
163                $info['objectClass'][]          = 'phpgwAccount';
164                $info['objectClass'][]          = 'top';
165                $info['objectClass'][]          = 'person';
166                $info['objectClass'][]          = 'qmailUser';
167                $info['objectClass'][]          = 'organizationalPerson';
168               
169                if ($params['accountStatus'] == 'on')
170                {
171                        $info['accountStatus'] = 'active';
172                }
173                if ($params['phpgwAccountVisible'] == 'on')
174                {
175                        $info['phpgwAccountVisible'] = '-1';
176                }
177               
178                if (!empty($params['owners']))
179                {
180                        foreach($params['owners'] as $index=>$uidnumber)
181                        {
182                                $info['mailForwardingAddress'][] = $this->uidnumber2mail($uidnumber);
183                        }
184                }               
185               
186                $result = array();
187                if (!@ldap_add ( $this->ldap, $dn, $info ))
188                {
189                        $result['status'] = false;
190                        $result['msg']  = $this->functions->lang('Error on function') . ' ldap_functions->create_institutional_accounts';
191                        $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
192                }
193                else
194                        $result['status'] = true;
195               
196                return $result;
197        }
198       
199        function save_institutional_accounts($params)
200        {
201                /* Begin: Access verification */
202                $forbidden = $this->noAccess( $params['context'], 'edit_institutional_accounts' );
203
204                if( $forbidden )
205                    return( $forbidden );
206//              if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_institutional_accounts'))
207//              {
208//                      $return['status'] = false;
209//                      $return['msg'] = $this->functions->lang('You do not have right to edit institutional accounts') . ".";
210//                      return $return;
211//              }
212//              $access_granted = false;
213//              foreach ($this->manager_contexts as $idx=>$manager_context)
214//              {
215//                      if (stristr($params['context'], $manager_context))
216//                      {
217//                              $access_granted = true;
218//                              break;
219//                      }
220//              }
221//              if (!$access_granted)
222//              {
223//                      $return['status'] = false;
224//                      $return['msg'] = $this->functions->lang('You do not have access to this organization') . ".";
225//                      return $return;
226//              }
227                /* End: Access verification */
228                               
229                        /* Begin: Validation */
230                        if ( (empty($params['cn'])) || (empty($params['mail'])) )
231                        {
232                                $result['status'] = false;
233                        $result['msg']  = $this->functions->lang('Field mail or name is empty') . '.';
234                        return $result;
235                }
236
237                if (! preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/i', $params['mail']) )
238                {
239                        $result['status'] = false;
240                        $result['msg']  = $this->functions->lang('Field mail is not formed correcty') . '.';
241                        return $result;
242                }
243
244        $institutional_accounts = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ('('.substr($params['anchor'], 0 , strpos($params['anchor'],','))).')');
245        $old  = ldap_get_entries($this->ldap, $institutional_accounts);
246        $oldOwners = array();
247
248
249        foreach($old[0]['mailforwardingaddress'] as $mailP)
250        {
251            $tmp = $this->mailforwardingaddress2uidnumber($mailP);
252            $oldOwners[$tmp['uidnumber']] = true;
253        }
254
255        if (!empty($params['owners']))
256        {
257            foreach($params['owners'] as $index => $uidnumber)
258            {
259                if(array_key_exists($uidnumber, $oldOwners))
260                    unset( $oldOwners[$uidnumber] );
261                else
262                    $this->functions->write_log("User added from the institutional account",'USER: '.$uidnumber.' - SHARED ACCOUNT: '.$params['anchor']);
263            }
264        }
265
266        if(count($oldOwners) > 0)
267            foreach($oldOwners as $i=>$v )
268            {
269                $this->functions->write_log("User removed from the institutional account",'USER: '.$i.' - SHARED ACCOUNT: '.$params['anchor']);
270            }
271
272
273
274                $uid = 'institutional_account_' . $params['mail'];
275                $dn = strtolower("uid=$uid," . $params['context']);
276                $anchor = strtolower($params['anchor']);
277
278                $filter = "(mail=".$params['mail'].")";
279                $justthese = array("cn");
280                $search = @ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
281                $entries = @ldap_get_entries($this->ldap,$search);
282               
283                if ( ($entries['count'] > 1) || (($entries['count'] == 1) && ($entries[0]['dn'] != $anchor)) )
284                {
285                        $result['status'] = false;
286                        $result['msg'] = $this->functions->lang('Field mail already in use.');
287                        return $result;
288                }
289                /* End: Validation */
290               
291                $result = array();
292                $result['status'] = true;
293               
294                if ($anchor != $dn)
295                {
296                        if (!@ldap_rename($this->ldap, $anchor, "uid=$uid", $params['context'], true))
297                        {
298                                $result['status'] = false;
299                                $result['msg']  = $this->functions->lang('Error on function') . ' ldap_functions->save_institutional_accounts: ldap_rename';
300                                $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
301                        }
302                }
303               
304                $info = array();
305                $info['cn']                                     = $params['cn'];
306                $info['sn']                                     = $params['cn'];
307                $info['uid']                            = $uid;
308                $info['mail']                           = $params['mail'];
309               
310                if ($params['accountStatus'] == 'on')
311                        $info['accountStatus'] = 'active';
312                else
313                        $info['accountStatus'] = array();
314               
315                if ($params['phpgwAccountVisible'] == 'on')
316                        $info['phpgwAccountVisible'] = '-1';
317                else
318                        $info['phpgwAccountVisible'] = array();
319               
320                if ($params['desc'] != '')
321                        $info['description'] = utf8_encode($params['desc']);
322                else
323                        $info['description'] = array();
324               
325                if (!empty($params['owners']))
326                {
327                        foreach($params['owners'] as $index => $uidnumber)
328                        {
329                                $mailForwardingAddress = $this->uidnumber2mail($uidnumber);
330                                if ($mailForwardingAddress != '')
331                                        $info['mailForwardingAddress'][] = $mailForwardingAddress;
332                        }
333                }
334                else
335                        $info['mailForwardingAddress'] = array();
336               
337                if (!@ldap_modify ( $this->ldap, $dn, $info ))
338                {
339                        $result['status'] = false;
340                        $result['msg']  = $this->functions->lang('Error on function') . ' ldap_functions->save_institutional_accounts: ldap_modify';
341                        $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
342                }
343
344
345        $this->functions->write_log('Update institutional account','Old DN:'.$params['anchor'].' New DN '.$dn);
346
347                return $result;
348        }
349
350        function save_shared_accounts($params)
351        {
352                /* Begin: Access verification */
353                $forbidden = $this->noAccess( $params['context'], 'edit_shared_accounts' );
354
355                if( $forbidden )
356                    return $forbidden;
357               
358                /* Begin: Validation */
359                if(!$params['desc'])
360                {
361                    $result['status'] = false;
362                    $result['msg']  = $this->functions->lang('Field description is empty');     return $result;
363
364                }
365
366                if ( (empty($params['cn'])) || (empty($params['mail'])) )
367                {
368                        $result['status'] = false;
369                        $result['msg']  = $this->functions->lang('Field mail or name is empty') . '.';
370                        return $result;
371                }
372
373                if (! preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/i', $params['mail']) )
374                {
375                        $result['status'] = false;
376                        $result['msg']  = $this->functions->lang('Field mail is not formed correcty') . '.';
377                        return $result;
378                }                       
379
380                $dnReal = "uid=".$params['uid']."," . $params['context'];
381                $dn = strtolower("uid=".$params['uid']."," . $params['context']);
382                $anchor = strtolower($params['anchor']);
383
384               
385                $filter = "(mail=".$params['mail'].")";
386                $justthese = array("cn","uidnumber");
387                $search = @ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
388                $entries = @ldap_get_entries($this->ldap,$search);
389
390                //DEBUG: Alteracao para compatibilizar com LDAP da CAIXA.
391                // estas funcoes do ExpressoAdmin nao levam em consideracao o DN do objeto encontrado
392                // e o "codigo" assume que o DN comeca com UID quando na CAIXA comeca com CN.
393
394                // Se for encontrado somente um objeto e este estiver diferente do ANCHOR, entao pega o DN
395                // do resultado da busca
396                if ( ($entries['count'] == 1) && (strtolower(utf8_decode($entries[0]['dn'])) != $anchor) )
397                {
398                        // Forca o DN
399                        $dn = strtolower (utf8_decode($entries[0]['dn']));
400                        $dnReal = $entries[0]['dn'];
401                        $anchor = $dn;
402                }
403               
404                if ( ($entries['count'] > 1) || (($entries['count'] == 1) && (strtolower(utf8_decode($entries[0]['dn'])) != $anchor)) )
405                {
406                        $result['status'] = false;
407                        $result['msg'] = $this->functions->lang('Field mail already in use.');
408                        return $result;
409                }
410                /* End: Validation */
411
412                $result = array();
413                $result['status'] = true;             
414
415                if ($anchor != $dn)
416                {
417                        if (!@ldap_rename($this->ldap, $params['anchor'], "uid={$params['uid']}", $params['context'], true))
418                        {
419                                $result['status'] = false;
420                                $result['msg']  = $this->functions->lang('Error on function') . ' ldap_functions->save_shared_accounts: ldap_rename';
421                                $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
422                        }
423                }
424               
425                $info = array();
426                $info['cn']             = utf8_encode($params['cn']);
427                $info['sn']             = utf8_encode($params['cn']);
428                $info['uid']            = $params['uid'];
429                $info['mail']           = $params['mail'];
430
431
432                $del = array();
433
434                if( $params['mailalternateaddress'] )
435                        $info['mailalternateaddress'] = $params['mailalternateaddress'];
436                else
437                    $del['mailalternateaddress'] = array();
438
439                if ($params['accountStatus'] == 'on')
440                        $info['accountStatus'] = 'active';
441                else
442                        $info['accountStatus'] = array();
443               
444                if ($params['phpgwAccountVisible'] == 'on')
445                        $info['phpgwAccountVisible'] = '-1';
446                else
447                        $info['phpgwAccountVisible'] = array();
448               
449                if ($params['desc'] != '')
450                        $info['description'] = utf8_encode($params['desc']);
451                else
452                        $info['description'] = array();
453
454                ldap_set_option ($this->ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
455
456                if( !empty( $del ) )
457                    @ldap_mod_del( $this->ldap, $dnReal, $del );
458
459                if (!@ldap_modify ( $this->ldap,$dnReal, $info ))
460                {
461                        $result['status'] = false;
462                        $result['msg']  = $this->functions->lang('Error on function') . ' ldap_functions->save_shared_accounts: ldap_modify';
463                        $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
464                }
465                //print_r($info);echo "Teste $dn".$result['msg'];exit();
466                return $result;
467        }
468
469        function create_shared_accounts($params)
470        {
471                /* Begin: Access verification */
472
473                $forbidden = $this->noAccess( $params['context'], 'add_shared_accounts', 'create shared accounts' );
474
475                if( $forbidden )
476                    return( $forbidden );
477
478                /* End: Access verification */
479
480                       
481                /* Begin: Validation */
482
483                if(!$params['desc'])
484                {
485                    $result['status'] = false;
486                    $result['msg']  = $this->functions->lang('Field description is empty');     return $result;
487
488                }
489
490                if ( (empty($params['cn'])) || (empty($params['mail'])) )
491                {
492                        $result['status'] = false;
493                                $result['msg']  = $this->functions->lang('Field mail or name is empty');        return $result;
494                        }
495       
496                        if (! preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/i', $params['mail']) )
497                        {
498                                $result['status'] = false;
499                                $result['msg']  = $this->functions->lang('Field mail is not formed correcty') . '.';
500                                return $result;
501                        }                                         
502                        $dn = "uid={$params['uid']}," . $params['context'];
503                        $filter = "(mail=".$params['mail'].")";
504                        $justthese = array("cn");
505                        $search = @ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
506                        $entries = @ldap_get_entries($this->ldap,$search);
507                        if ($entries['count'] != 0)
508                        {
509                        $result['status'] = false;
510                        $result['msg'] = $this->functions->lang('Field mail already in use');
511                        return $result;
512                }
513
514                // Leio o ID a ser usado na criação do objecto. Esta função já incrementa o ID no BD.
515                $next_id = ($this->db_functions->get_next_id('accounts'));
516                if ((!is_numeric($next_id['id'])) || (!$next_id['status']))
517                {
518                        $return['status'] = false;
519                        $return['msg'] = $this->functions->lang('problems getting user id') . ".\n" . $id['msg'];
520                        return $return;
521                }
522                else
523                {
524                        $id = $next_id['id'];
525                        }
526
527                        /* End: Validation */
528                                                       
529                        $info = array();
530                $info['cn']                                     = utf8_encode($params['cn']);
531                $info['sn']                                     = utf8_encode($params['cn']);
532                $info['uidnumber']                                      = $id;
533                $info['homeDirectory']                          = '/dev/null';
534                $info['gidNumber']                                      = '1000';
535                        $info['uid']                            = $params['uid'];
536                        $info['mail']                           = $params['mail'];
537                        $info['description'] = utf8_encode($params['desc']);                   
538                        $info['phpgwAccountType']       = 's';
539                $info['objectClass'][0]         = 'inetOrgPerson';
540                $info['objectClass'][1]         = 'phpgwAccount';
541                $info['objectClass'][2]         = 'top';
542                $info['objectClass'][3]         = 'person';
543                $info['objectClass'][4]         = 'qmailUser';
544                $info['objectClass'][5]         = 'organizationalPerson';
545                $info['objectClass'][6]         = 'posixAccount';
546                       
547                        if ($params['accountStatus'] == 'on')
548                        {
549                                $info['accountStatus'] = 'active';
550                        }
551                        if ($params['phpgwAccountVisible'] == 'on')
552                        {
553                                $info['phpgwAccountVisible'] = '-1';
554                        }
555                if( !empty( $params['mailalternateaddress'] ) )
556                        $info['mailalternateaddress'] = $params['mailalternateaddress'];
557                       
558                        /*if (!empty($params['owners']))
559                        {
560                                foreach($params['owners'] as $index=>$uidnumber)
561                                {
562                                        $info['mailForwardingAddress'][] = $this->uidnumber2mail($uidnumber);
563                                }
564                        }*/
565                        $result = array();
566                        //print_r($info);exit();
567                        if (!@ldap_add ( $this->ldap, $dn, $info ))
568                        {
569                                $result['status'] = false;
570                                $result['msg']  = $this->functions->lang('Error on function') . ' ldap_functions->create_shared_accounts';
571                                $result['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
572                        }
573                        else{
574                                $result['status'] = true;                                                       
575                        }
576                        return $result;
577                }
578       
579        /* expressoAdmin: email lists : deve utilizar o ldap Host Master com o usuario e senha do CC*/
580        /* ldap connection following referrals and using Master config, from setup */
581        function ldapMasterConnect()
582        {
583                /*
584                $common = new common();
585                if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) &&
586                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) &&
587                         (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) )
588                {
589                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_master_host']);
590                        ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
591                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
592                        ldap_set_rebind_proc($ldap_connection, ldapRebind);
593                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
594                }
595                else
596                {
597                        $ldap_connection = $common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_host'],
598                                                                                           $GLOBALS['phpgw_info']['server']['ldap_root_dn'],
599                                                                                           $GLOBALS['phpgw_info']['server']['ldap_root_pw'], true);
600                }
601               
602                // If success, return follow_referral connection. Else, return normal connection.
603                if ($ldap_connection)
604                        return $ldap_connection;
605                else
606                        return $this->ldap;
607                */
608               
609                // Este if é para utilizar o master. (para replicação)
610                if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) && ($ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_master_host'])) )
611                {
612                        ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
613                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
614                        ldap_set_rebind_proc($ldap_connection, ldapRebind);
615                        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
616                        {
617                                if ( ! ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']) )
618                                {
619                                        return false;
620                                }
621                        }
622                        return $ldap_connection;
623                }
624                else
625                {
626                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
627                        if ($ldap_connection)
628                        {
629                                ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
630                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
631                                if ( ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']) )
632                                        return $ldap_connection;
633                        }
634                }
635               
636                return false;
637        }
638               
639        function validate_fields($params)
640        {
641                /* ldap connection following referals and using Contac Center config*/
642                if (is_array($_SESSION['phpgw_info']['expresso']['cc_ldap_server']))
643                {
644                        $ldap_connection = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
645                        if ($ldap_connection)
646                        {
647                                ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
648                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
649                               
650                                if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
651                                        ldap_bind($ldap_connection, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
652                                $context = $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['dn'];
653                        }
654                        else
655                        {
656                                $result['status'] = false;
657                                $result['msg'] = $this->functions->lang('Connection with ldap fail') . ".";
658                                return $result;
659                        }
660                }
661                else
662                {
663                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
664                        ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
665                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
666                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
667                        $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
668                }
669               
670                $result['status'] = true;
671               
672                $params = unserialize($params['attributes']);
673                $type = $params['type'];
674                $uid = $params['uid'];
675                $mail = $params['mail'];
676                $mailalternateaddress = $params['mailalternateaddress'];
677                $cpf = $params['cpf'];
678                               
679                if ($_SESSION['phpgw_info']['expresso']['global_denied_users'][$uid])
680                {
681                        $result['status'] = false;
682                        $result['msg'] = $this->functions->lang('this login can not be used because is a system account') . ".";
683                        return $result;
684                }
685               
686                if (($type == 'create_user') || ($type == 'rename_user'))
687                {
688                        if ($this->current_config['expressoAdmin_prefix_org'] == 'true')
689                        {
690                                //Obtenho UID sem a organização. Na criação o uid já vem sem a organização
691                                $tmp_uid_without_org = preg_split('/-/', $params['uid']);
692                                $tmp_reverse_uid_without_org = array_reverse($tmp_uid_without_org);
693                                array_pop($tmp_reverse_uid_without_org);
694                                $uid_without_org = implode("-", $tmp_reverse_uid_without_org);
695                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(uid=$uid)(uid=$uid_without_org)))";
696                        }
697                        else
698                        {
699                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$uid))";
700                        }
701                        /*
702                        //UID
703                        if (($type == 'rename_user') && ($this->current_config['expressoAdmin_prefix_org'] == 'true'))
704                        {
705                                //Obtenho UID sem a organização. Na criação o uid já vem sem a organização
706                                $tmp_uid_without_org = preg_split('/-/', $params['uid']);
707                                $tmp_reverse_uid_without_org = array_reverse($tmp_uid_without_org);
708                                array_pop($tmp_reverse_uid_without_org);
709                                $uid_without_org = implode("-", $tmp_reverse_uid_without_org);
710                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(uid=$uid)(uid=$uid_without_org)))";
711                        }
712                        else
713                        {
714                                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$uid))";
715                        }
716                        */
717                       
718                        $justthese = array("uid", "mail", "cn");
719                        $search = ldap_search($ldap_connection, $context, $filter, $justthese);
720                        $count_entries = ldap_count_entries($ldap_connection,$search);
721                        if ($count_entries > 0)
722                        {
723                                $entries = ldap_get_entries($ldap_connection, $search);
724                               
725                                for ($i=0; $i<$entries['count']; ++$i)
726                                {
727                                        $users .= $entries[$i]['cn'][0] . ' - ' . $entries[$i]['mail'][0] . "\n";
728                                }
729                               
730                                $result['status'] = false;
731                                $result['msg'] = $this->functions->lang('this login is already used by') . ":\n" . $users;
732                                return $result;
733                        }
734
735                        // GRUPOS
736                        $filter = "(&(phpgwAccountType=g)(cn=$uid))";
737                        $justthese = array("cn");
738                        $search = ldap_search($ldap_connection, $context, $filter, $justthese);
739                        $count_entries = ldap_count_entries($ldap_connection,$search);
740                        if ($count_entries > 0)
741                        {
742                                $result['status'] = false;
743                                $result['msg'] = $this->functions->lang('This login is being used by a group') . ".";
744                                return $result;
745                        }
746                       
747                       
748                        // UID em outras organizações, pesquiso apenas na maquina local e se utilizar prefix_org
749                        if ($this->current_config['expressoAdmin_prefix_org'] == 'true')
750                        {
751                                $ldap_connection2 = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
752                                ldap_set_option($ldap_connection2,LDAP_OPT_PROTOCOL_VERSION,3);
753                                ldap_set_option($ldap_connection2, LDAP_OPT_REFERRALS, false);
754                                ldap_bind($ldap_connection2, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
755                                $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
756                               
757                                //Obtenho UID sem a organização
758                                /*
759                                $tmp_uid_without_org = preg_split('/-/', $params['uid']);
760                                if (count($tmp_uid_without_org) < 2)
761                                {
762                                        $result['status'] = false;
763                                        $result['msg'] = 'Novo login sem organização.';
764                                        return $result;
765                                }
766                                $tmp_reverse_uid_without_org = array_reverse($tmp_uid_without_org);
767                                array_pop($tmp_reverse_uid_without_org);
768                                $uid_without_org = implode("-", $tmp_reverse_uid_without_org);
769                                */
770                               
771                                $filter = "(ou=*)";
772                                $justthese = array("ou");
773                                $search = ldap_list($ldap_connection2, $context, $filter, $justthese);
774                                $entries = ldap_get_entries($ldap_connection2   ,$search);
775                               
776                                foreach ($entries as $index=>$org)
777                                {
778                                        $organization = $org['ou'][0];
779                                        $organization = strtolower($organization);
780                               
781                                        $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$organization-$uid))";
782                                       
783                                        $justthese = array("uid");
784                                        $search = ldap_search($ldap_connection2, $context, $filter, $justthese);
785                                        $count_entries = ldap_count_entries($ldap_connection2,$search);
786                                        if ($count_entries > 0)
787                                        {
788                                                $result['status'] = false;
789                                                $result['msg'] = $this->functions->lang('this login is already used by a user in another organization') . ".";
790                                                ldap_close($ldap_connection2);
791                                                return $result;
792                                        }
793                                }
794                                ldap_close($ldap_connection2);
795                        }
796                }
797               
798                if ($type == 'rename_user')
799                {
800                        return $result;
801                }
802               
803                // MAIL
804                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mail)(mailalternateaddress=$mail)))";
805                $justthese = array("mail", "uid");
806                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
807                $entries = ldap_get_entries($ldap_connection,$search);
808                if ($entries['count'] == 1){
809                        if ($entries[0]['uid'][0] != $uid){
810                                $result['status'] = false;
811                                $result['msg'] = $this->functions->lang('this email address is being used by 1 user') . ": " . $entries[0]['uid'][0];
812                                return $result;
813                        }
814                }
815                else if ($entries['count'] > 1){
816                        $result['status'] = false;
817                        $result['msg'] = $this->functions->lang('this email address is being used by 2 or more users') . ".";
818                        return $result;
819                }
820               
821                // MAILAlternateAddress
822                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mailalternateaddress)(mailalternateaddress=$mailalternateaddress)))";
823                $justthese = array("mail", "uid");
824                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
825                $entries = ldap_get_entries($ldap_connection,$search);
826                if ($entries['count'] == 1){
827                        if ($entries[0]['uid'][0] != $uid){
828                                $result['status'] = false;
829                                $result['msg'] = $this->functions->lang('alternative email is being used by 1 user') . ": " . $entries[0]['uid'][0];
830                                return $result;
831                        }
832                }
833                else if ($entries['count'] > 1){
834                        $result['status'] = false;
835                        $result['msg'] = $this->functions->lang('alternative email is being used by 2 or more users') . ".";
836                        return $result;
837                }
838
839                //Begin: Check CPF, only if the manager has access to this field.
840                if ($this->functions->check_acl($_SESSION['phpgw_session']['session_lid'], 'manipulate_corporative_information'))
841                {
842                        if (!empty($cpf))
843                        {
844                                if (!$this->functions->checkCPF($cpf))
845                                {
846                                        $result['status'] = false;
847                                        $result['msg'] = $this->functions->lang('Field CPF is invalid') . '.';
848                                        return $result;
849                                }
850                                else
851                                {
852                                        //retira caracteres que não são números.
853                                        $cpf = preg_replace('/[^0-9]/', '', $cpf);
854                               
855                                        $local_ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
856                                        if ($ldap_connection)
857                                        {
858                                                ldap_set_option($local_ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
859                                                ldap_set_option($local_ldap_connection, LDAP_OPT_REFERRALS, false);
860                                                ldap_bind($local_ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
861                                        }
862                                        else
863                                        {
864                                                $result['status'] = false;
865                                                $result['msg'] = $this->functions->lang('Connection with ldap fail') . ".";
866                                                return $result;
867                                        }
868                               
869                                        $filter = "(&(phpgwAccountType=u)(cpf=$cpf))";
870                                        $justthese = array("cn","uid" ,"mail");
871                                        $search = ldap_search($local_ldap_connection, $context, $filter, $justthese);
872                                        $entries = ldap_get_entries($local_ldap_connection,$search);
873                               
874                                        if ( ($entries['count'] != 1) && (strcasecmp($uid, $entries[0]['uid'][0]) != 0) )
875                                        {
876                                                if ($entries['count'] > 0)
877                                                {
878                                                        $result['question'] = $this->functions->lang('Field CPF used by') . ":\n";
879                                                                for ($i=0; $i<$entries['count']; ++$i)
880                                                                        {
881                                                                                if (strcasecmp($uid, $entries[$i]['uid'][0]) != 0)
882                                                                        $result['question'] .= "- " . $entries[$i]['cn'][0] ." - ".$entries[$i]['uid'][0] ." - ".$entries[$i]['mail'][0] . "\n";
883                                                                        }
884                                                                        $result['question'] .= $this->functions->lang("Do you want to continue anyway") . "?";
885                                                                        return $result;
886                                                }
887                                        }
888                                        ldap_close($local_ldap_connection);
889                                }
890                        }
891                        else if ($this->current_config['expressoAdmin_cpf_obligation'])
892                        {
893                                $result['status'] = false;
894                                $result['msg'] = $this->functions->lang('Field CPF must be completed') . '.';
895                                return $result;
896                        }
897                }
898                //End: Check CPF
899
900                return $result;
901        }
902       
903        function generate_login($params) {
904                $params = unserialize($params['attributes']);
905                $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
906                $justthese = array("uid");
907                $i=1;
908                $login = array("status" => False,"msg" => lang("Login generator disabled"));
909               
910                if( (isset($this->current_config['expressoAdmin_loginGenScript'])) &&
911                                ($this->current_config['expressoAdmin_loginGenScript'])) {
912                       
913                        include_once "if.login.inc.php";
914                        include_once "class.".$this->current_config['expressoAdmin_loginGenScript'].
915                                        ".inc.php";
916
917                        $classe = new ReflectionClass($this->current_config['expressoAdmin_loginGenScript']);
918                                       
919                        if(!$classe->implementsInterface('login'))
920                        {
921                                return array(
922                                        "status" => False,
923                                        "msg" => lang("Login interface not implemented (contact suport)")
924                                );
925                        }
926
927                        $login = $classe->newInstance()->generate_login($params["first_name"],$params["second_name"],$this->ldap);
928                       
929                        /*
930                                If login exists, it concatenates a number to the end.
931                                resulting in a new login
932                         */
933                        $i = 1;
934                        while($i < 1000) // Limit of 1000 equal names
935                        {
936                                $search = ldap_search($this->ldap, $context, "(uid=".$login.")", $justthese);
937                                if (ldap_count_entries($this->ldap,$search) == 0)
938                                        break;
939                                else
940                                {
941                                        if ($i > 1) // If login have a number, remove the number and put the new one
942                                                $login=substr($login,0,strlen($login)-strlen($i)).$i;
943                                        else
944                                                $login.=$i;
945                                        ++$i;
946                                }
947                        }
948                }
949               
950                return array('status'=>true,'msg' => $login);
951        }
952        function validate_fields_group($params)
953        {
954                /* ldap connection following referals and using Contac Center config*/
955                if (is_array($_SESSION['phpgw_info']['expresso']['cc_ldap_server']))
956                {
957                        $ldap_connection = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
958                        if ($ldap_connection)
959                        {
960                                ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
961                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
962                                if ( ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
963                                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'], $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw']);
964                                $context = $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['dn'];
965                        }
966                        else
967                        {
968                                $result['status'] = false;
969                                $result['msg'] = $this->functions->lang('Connection with ldap fail') . ".";
970                                return $result;
971                        }
972                }
973                else
974                {
975                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
976                        ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
977                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
978                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
979                        $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
980                }
981
982                $cn = $params['cn'];
983                $result['status'] = true;
984               
985                if ($_SESSION['phpgw_info']['expresso']['global_denied_groups'][$cn])
986                {
987                        $result['status'] = false;
988                        $result['msg'] = $this->functions->lang('This group name can not be used because is a System Account') . ".";
989                        return $result;
990                }
991               
992                // CN
993                $filter = "(&(phpgwAccountType=g)(cn=$cn))";
994                $justthese = array("cn");
995                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
996                $count_entries = ldap_count_entries($ldap_connection,$search);
997                if ($count_entries > 0)
998                {
999                        $result['status'] = false;
1000                        $result['msg'] = $this->functions->lang('This name is already used') . ".";
1001                        return $result;
1002                }
1003               
1004                // UID
1005                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$cn))";
1006                $justthese = array("uid");
1007                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
1008                $count_entries = ldap_count_entries($ldap_connection,$search);
1009                if ($count_entries > 0)
1010                {
1011                        $result['status'] = false;
1012                        $result['msg'] = $this->functions->lang('This grupo name is already used by an user') . ".";
1013                        return $result;
1014                }
1015               
1016                return $result;
1017        }
1018       
1019        function validate_fields_maillist($params)
1020        {
1021                /* ldap connection following referals and using Contac Center config*/
1022                if (is_array($_SESSION['phpgw_info']['expresso']['cc_ldap_server']))
1023                {
1024                        $ldap_connection = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
1025                        if ($ldap_connection)
1026                        {
1027                                ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
1028                                ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
1029                                if ( ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
1030                                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['acc'], $GLOBALS['phpgw_info']['expresso']['cc_ldap_server']['pw']);
1031                                $context = $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['dn'];
1032                        }
1033                        else
1034                        {
1035                                $result['status'] = false;
1036                                $result['msg'] = $this->functions->lang('Connection with ldap fail') . ".";
1037                                return $result;
1038                        }
1039                }
1040                else
1041                {
1042                        $ldap_connection = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1043                        ldap_set_option($ldap_connection,LDAP_OPT_PROTOCOL_VERSION,3);
1044                        ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, true);
1045                        ldap_bind($ldap_connection, $GLOBALS['phpgw_info']['server']['ldap_root_dn'], $GLOBALS['phpgw_info']['server']['ldap_root_pw']);
1046                        $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
1047                }
1048               
1049                $uid = $params['uid'];
1050                $mail = $params['mail'];
1051                $result['status'] = true;
1052               
1053                if ($_SESSION['phpgw_info']['expresso']['global_denied_users'][$uid])
1054                {
1055                        $result['status'] = false;
1056                        $result['msg'] = $this->functions->lang('This LOGIN can not be used because is a System Account') . ".";
1057                        return $result;
1058                }
1059               
1060                // UID
1061                $filter = "(&(phpgwAccountType=l)(uid=$uid))";
1062                $justthese = array("uid");
1063                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
1064                $count_entries = ldap_count_entries($ldap_connection,$search);
1065                if ($count_entries > 0)
1066                {
1067                        $result['status'] = false;
1068                        $result['msg'] = $this->functions->lang('this email list login is already used') . ".";
1069                        return $result;
1070                }
1071               
1072                // MAIL
1073                $filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mail)(mailalternateaddress=$mail)))";
1074                $justthese = array("mail");
1075                $search = ldap_search($ldap_connection, $context, $filter, $justthese);
1076                $count_entries = ldap_count_entries($ldap_connection,$search);
1077                if ($count_entries > 0)
1078                {
1079                        $result['status'] = false;
1080                        $result['msg'] = $this->functions->lang('this email address is already used') . ".";
1081                        return $result;
1082                }
1083               
1084                return $result;
1085        }
1086
1087        function get_available( $params, $justthese = false, $targetTypes = false )
1088        {
1089            $search = $params['sentence'] ? $params['sentence'] : $params['filter'];
1090               
1091            if( !$justthese )
1092                $justthese = array('cn', 'uidNumber','uid');
1093       
1094            if( !$targetTypes )
1095                $targetTypes = 'u';
1096       
1097            $ldapService = ServiceLocator::getService('ldap');
1098                       
1099            $entries = $ldapService->accountSearch( $search, $justthese, $params['context'], $targetTypes, 'cn' );
1100
1101            return( $entries );
1102        }
1103                       
1104        function get_options( $entries, $label, $value = false, $uid = false )
1105                {
1106            if( !$value )
1107                $value = $label;
1108
1109            $options = '';
1110            foreach( $entries as  $entry )
1111                        {
1112                if( $uid )
1113                    $entry[$label] .= '('.$entry[$uid].')';
1114
1115                $options .= '<option value='.$entry[$value].'>'.$entry[$label].'</option>';
1116                }
1117
1118        return $options;
1119        }
1120       
1121        function get_json( $entries, $label, $value = false, $uid = false )
1122        {
1123            if( !$value )
1124                $value = $label;
1125
1126            $options = array();
1127
1128            foreach( $entries as  $entry )
1129            {
1130                if( $uid )
1131                    $entry[$label] .= '('.$entry[$uid].')';
1132
1133                 $options[] = '"'.$entry[$value].'"'.':'.'"'.$entry[$label].'"';
1134
1135                        }
1136
1137             return "{".implode(',',$options)."}";
1138        }
1139
1140
1141        //Busca usuários de um contexto e já retorna as options do select;
1142        function get_available_users($params)
1143                                {
1144             $entries = $this->get_available($params );
1145
1146//              $options = '';
1147//              foreach ($entries as  $value)
1148//                  $options .= '<option value='.$value['uidnumber'].'>'.$value['cn'].'('.$value['uid'].')</option>';
1149
1150             return $this->get_options( $entries, 'cn', 'uidnumber', 'uid' );
1151        }
1152
1153        //Busca usuários e contas compartilhadas de um contexto e já retorna as options do select;
1154        function get_available_users_and_shared_acounts($params)
1155        {
1156             $entries = $this->get_available($params, array('cn', 'uidNumber','uid'), array('u','s') );
1157//              $options = '';
1158//              foreach ($entries as  $value)
1159//                  $options .= '<option value='.$value['uidnumber'].'>'.$value['cn'].'('.$value['uid'].')</option>';
1160               
1161             return $this->get_options( $entries, 'cn', 'uidnumber', 'uid' );
1162        }
1163               
1164        function get_available_users2($params)
1165        {
1166             $entries = $this->get_available($params, array('cn', 'uid') );
1167               
1168//              $options = array();
1169//              foreach ($entries as $value)
1170//                  $options[] = '"'.$value['uid'].'"'.':'.'"'.$value['cn'].'('.$value['uid'].')'.'"';
1171               
1172             return $this->get_json( $entries, 'cn', 'uid', 'uid' );
1173        }
1174
1175        function get_available_users3($params)
1176                {
1177             $ldapService = ServiceLocator::getService('ldap');
1178             $groups = $ldapService->accountSearch($params['filter'], array('gidNumber','cn','uid'), $params['context'], 'g', 'cn');
1179             $users = $ldapService->accountSearch($params['filter'], array('uidNumber','cn','uid'), $params['context'], 'u', 'cn');
1180
1181             $user_options ='';
1182             $group_options ='';
1183             $user_options2 ='';
1184             $group_options2 ='';
1185
1186             foreach($groups as  $group)
1187             {
1188                $group_options .= '<option  value="'.$group['gidnumber'].'">'.$group['cn'].' ('.$group['gidnumber'].')</option>'."\n";
1189                $group_options2 .= '<option  value="'.$group['gidnumber'].',G">'.$group['cn'].' ('.$group['gidnumber'].')</option>'."\n";
1190                }
1191
1192             foreach($users as $user)
1193             {
1194                $user_options .= '<option  value="'.$user['uid'].'">'.$user['cn'].' ('.$user['uid'].')</option>'."\n";
1195                $user_options2 .= '<option  value="'.$user['uid'].',U">'.$user['cn'].' ('.$user['uid'].')</option>'."\n";
1196
1197             }
1198
1199            return array("users" => $user_options, "groups" => $group_options , "users2" => $user_options2, "groups2" => $group_options2);
1200        }
1201
1202        /**
1203         * @abstract Busca usuários de um contexto e retorna já formatado com as options do select.
1204         * @params array params com as informações do formulário com os dados do contexto e etc.
1205         * @return array com os usuários do contexto já com a formatação das options do select.
1206         */
1207        function get_available_users_messages_size($params)
1208                        {
1209/*             $ldapService = ServiceLocator::getService('ldap');
1210             $entries = $ldapService->accountSearch($params['sentence'], array('cn', 'uidNumber','uid'), $params['context'], 'u', 'cn');
1211             $options = array();
1212
1213             foreach ($entries as $value)
1214                 $options[] = '"'.$value['uid'].'"'.':'.'"'.$value['cn'].'('.$value['uid'].')'.'"';*/
1215                 
1216            $entries = $this->get_available( $params, array('cn', 'uid') );
1217
1218             return $this->get_json( $entries, 'cn', 'uid','uid' );
1219                        }
1220
1221        /**
1222         * @abstract Busca usuários e grupos de um contexto e retorna já formatado com as options do select.
1223         * @params array params com as informações do formulário com os dados do contexto e etc.
1224         * @return array com os usuários do contexto já com a formatação das options do select.
1225         */
1226        function get_available_users_and_groups_messages_size($params)
1227        {
1228             $ldapService = ServiceLocator::getService('ldap');
1229             $groups = $ldapService->accountSearch($params['sentence'], array('gidNumber','cn','uid'), $params['context'], 'g', 'cn');
1230             $users = $ldapService->accountSearch($params['sentence'], array('cn','uid'), $params['context'], 'u', 'cn');
1231             $optionsUsers = array();
1232             $optionsGroups = array();
1233             foreach ($users as $value)
1234                 $optionsUsers[] = '"'.$value['uid'].'"'.':'.'"'.$value['cn'].'('.$value['uid'].')'.'"';
1235
1236             foreach ($groups as $value)
1237                 $optionsGroups[] = '"'.$value['gidNumber'].'"'.':'.'"'.$value['cn'].'('.$value['uid'].')'.'"';
1238
1239             return "{".implode(',',$optionsUsers).implode(',',$optionsGroups)."}";
1240        }
1241
1242 
1243        //Busca usuários e listas de um contexto e já retorna as options do select;
1244        function get_available_users_and_maillist($params)
1245                        {
1246
1247             $ldapService = ServiceLocator::getService('ldap');
1248             $users = $ldapService->accountSearch($params['sentence'], array('cn', 'mail','uid'), $params['context'], 'u', 'cn');
1249             $listas = $ldapService->accountSearch($params['sentence'], array('cn', 'mail','uid'), $params['context'], 'l', 'cn');
1250             $options = '';
1251             if(count($listas) > 0)
1252                                {
1253                 $options .= '<option  value="-1" disabled>------------------------------&nbsp;&nbsp;&nbsp;&nbsp;'.$this->functions->lang('email lists').'&nbsp;&nbsp;&nbsp;&nbsp;------------------------------ </option>'."\n";
1254                 foreach ($listas as  $value)
1255                    $options .= '<option value='.$value['mail'].'>'.$value['cn'].'('.$value['uid'].')</option>';
1256                                }
1257
1258             if(count($users) > 0)
1259             {
1260                $options .= '<option  value="-1" disabled>-----------------------------&nbsp;&nbsp;&nbsp;&nbsp;'.$this->functions->lang('users').'&nbsp;&nbsp;&nbsp;&nbsp;---------------------------- </option>'."\n";
1261                foreach ($users as  $value)
1262                    $options .= '<option value='.$value['mail'].'>'.$value['cn'].'('.$value['uid'].')</option>';
1263                        }
1264             
1265             return $options;
1266                }
1267               
1268        function get_available_groups($params)
1269                {
1270//              $ldapService = ServiceLocator::getService('ldap');
1271//              $entries = $ldapService->accountSearch($params['sentence'], array('cn', 'gidnumber'), $params['context'], 'g', 'cn');
1272//              $options = '';
1273//
1274//              foreach ($entries as  $value)
1275//                  $options .= '<option value='.$value['gidnumber'].'>'.$value['cn'].'</option>';
1276                 
1277            $entries = $this->get_available( $params, array( 'cn', 'gidNumber' ), 'g' );
1278
1279             return $this->get_options( $entries, 'cn', 'gidnumber' );
1280                }
1281                       
1282        function get_available_maillists($params)
1283        {
1284                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1285                        return false;
1286                       
1287                $context = $params['context'];
1288                $justthese = array("uid","mail","uidNumber");
1289                $maillists=ldap_list($ldapMasterConnect, $context, ("(phpgwAccountType=l)"), $justthese);
1290                ldap_sort($ldapMasterConnect, $maillists, "uid");
1291               
1292                $entries = ldap_get_entries($ldapMasterConnect, $maillists);
1293                       
1294                $options = '';                 
1295                for ($i=0; $i<$entries['count']; ++$i)
1296                        {
1297                        $options .= "<option value=" . $entries[$i]['uid'][0] . ">" . $entries[$i]['uid'][0] . " (" . $entries[$i]['mail'][0] . ")" . "</option>";
1298                }
1299               
1300        ldap_close($ldapMasterConnect);
1301                return $options;
1302        }
1303
1304        function get_available_institutional_account($params)
1305        {
1306            if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1307                    return false;
1308
1309            $filtro =utf8_encode($params['filter']);
1310            $context =utf8_encode($params['context']);//adicionado
1311            $justthese = array("uid","mail","uidNumber");
1312            $maillists=ldap_list($ldapMasterConnect, $context, ("(&(phpgwAccountType=i)(mail=*$filtro*))"), $justthese);
1313            ldap_sort($ldapMasterConnect, $maillists, "uid");
1314       
1315            $entries = ldap_get_entries($ldapMasterConnect, $maillists);
1316               
1317                $options = '';
1318                for ($i=0; $i<$entries['count']; ++$i)
1319                {
1320                            $options .= "<option value=" . $entries[$i]['mail'][0] . ">" . $entries[$i]['mail'][0] . "</option>";
1321                }
1322       
1323            ldap_close($ldapMasterConnect);
1324
1325
1326        return $options;               
1327        }
1328       
1329        function get_available_shared_account($params)
1330        {
1331                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1332                        return false;
1333               
1334            $filtro =utf8_encode($params['filter']);
1335            $context =utf8_encode($params['context']);//adicionado
1336                $justthese = array("uid","mail","uidNumber");
1337            $maillists=ldap_search($ldapMasterConnect, $context, ("(&(phpgwAccountType=s)(mail=*$filtro*))"), $justthese);
1338        ldap_sort($ldapMasterConnect, $maillists, "uid");
1339       
1340        $entries = ldap_get_entries($ldapMasterConnect, $maillists);
1341       
1342                $options = '';                 
1343                for ($i=0; $i<$entries['count']; ++$i)
1344                {
1345                            $options .= "<option value=" . $entries[$i]['mail'][0] . ">" . $entries[$i]['mail'][0] . "</option>";
1346                }
1347       
1348        ldap_close($ldapMasterConnect);
1349        return $options;
1350        }
1351       
1352        function ldap_add_entry($dn, $entry)
1353        {
1354                $result = array();
1355                if (!@ldap_add ( $this->ldap, $dn, $entry ))
1356                {
1357                        $result['status']               = false;
1358                        $result['error_number'] = ldap_errno($this->ldap);
1359                        $result['msg']                  = $this->functions->lang('Error on function') . " ldap_functions->ldap_add_entry ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_errno($this->ldap) . ldap_error($this->ldap);
1360                }
1361                else
1362                        $result['status'] = true;
1363               
1364                return $result;
1365        }
1366       
1367        function ldap_save_photo($dn, $pathphoto, $photo_exist=false)
1368        {
1369                $fd = fopen($pathphoto, "r");
1370                $fsize = filesize($pathphoto);
1371                $jpegStr = fread($fd, $fsize);
1372                fclose ($fd);
1373                $attrs['jpegPhoto'] = $jpegStr;
1374                       
1375                if ($photo_exist)
1376                        $res = @ldap_mod_replace($this->ldap, $dn, $attrs);
1377                else
1378                        $res = @ldap_mod_add($this->ldap, $dn, $attrs);
1379                       
1380                if ($res)
1381                {
1382                        $result['status'] = true;
1383                }
1384                else
1385                {
1386                        $result['status'] = false;
1387                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->ldap_save_photo ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
1388                }
1389               
1390                return $result;
1391        }
1392       
1393        function ldap_remove_photo($dn)
1394        {
1395                $attrs['jpegPhoto'] = array();
1396                $res = ldap_mod_del($this->ldap, $dn, $attrs);
1397               
1398                if ($res)
1399                {
1400                        $result['status'] = true;
1401                }
1402                else
1403                {
1404                        $result['status'] = false;
1405                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->ldap_remove_photo ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
1406                }
1407               
1408                return $result;
1409        }       
1410       
1411        // Pode receber tanto um único memberUid quanto um array de memberUid's
1412        function add_user2group($gidNumber, $memberUid)
1413        {
1414                $filter = "(&(phpgwAccountType=g)(gidNumber=$gidNumber))";
1415                $justthese = array("dn");
1416                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1417                $entry = ldap_get_entries($this->ldap, $search);
1418                $group_dn = $entry[0]['dn'];
1419                $attrs['memberUid'] = $memberUid;
1420               
1421                $res = @ldap_mod_add($this->ldap, $group_dn, $attrs);
1422               
1423                if ($res)
1424                {
1425                        $result['status'] = true;
1426                }
1427                else
1428                {
1429                        $result['status'] = false;
1430                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->add_user2group ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
1431                }
1432                return $result;
1433        }
1434       
1435        function remove_user2group($gidNumber, $memberUid)
1436        {
1437                $filter = "(&(phpgwAccountType=g)(gidNumber=$gidNumber))";
1438                $justthese = array("dn");
1439                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1440                $entry = ldap_get_entries($this->ldap, $search);
1441                $group_dn = $entry[0]['dn'];
1442                $attrs['memberUid'] = $memberUid;
1443                $res = @ldap_mod_del($this->ldap, $group_dn, $attrs);
1444               
1445                if ($res)
1446                {
1447                        $result['status'] = true;
1448                }
1449                else
1450                {
1451                        $result['status'] = false;
1452                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->remove_user2group ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
1453                }
1454                return $result;
1455        }
1456       
1457        function add_user2maillist($uid, $mail)
1458        {
1459                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1460                {
1461                        $result['status'] = false;
1462                        $result['msg'] = $this->functions->lang('Ldap connection fail') . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
1463                        return $result;
1464                }
1465                       
1466                $filter = "(&(phpgwAccountType=l)(uid=$uid))";
1467                $justthese = array("dn");
1468                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1469                $entry = ldap_get_entries($ldapMasterConnect, $search);
1470                $group_dn = $entry[0]['dn'];
1471                $attrs['mailForwardingAddress'] = $mail;
1472                $res = @ldap_mod_add($ldapMasterConnect, $group_dn, $attrs);
1473               
1474                if ($res)
1475                {
1476                        $result['status'] = true;
1477                }
1478                else
1479                {
1480                        $result['status'] = false;
1481                        if (ldap_errno($ldapMasterConnect) == '50')
1482                        {
1483                                $result['msg'] =        $this->functions->lang('Error on the function') . ' ldap_functions->add_user2maillist' . ".\n" .
1484                                                                        $this->functions->lang('The user used for record on LPDA, must have write access') . ".\n";
1485                                                                        $this->functions->lang('The user') . ' ' . $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] . ' ' . $this->functions->lang('does not have this access') . ".\n";
1486                                                                        $this->functions->lang('Edit Global Catalog Config, in the admin module, and add an user with write access') . ".\n";
1487                        }                                       
1488                        else
1489                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->add_user2maillist ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
1490                }
1491               
1492                ldap_close($ldapMasterConnect);
1493                return $result;
1494        }
1495       
1496        function add_user2maillist_scl($dn, $array_emails)
1497        {
1498                $attrs['mailSenderAddress'] = $array_emails;
1499               
1500                $res = @ldap_mod_add($this->ldap, $dn, $attrs);
1501               
1502                if ($res)
1503                {
1504                        $result['status'] = true;
1505                }
1506                else
1507                {
1508                        $result['status'] = false;
1509                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->add_user2maillist_scp ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
1510                }
1511                return $result;
1512        }
1513
1514        function remove_user2maillist($uid, $mail)
1515        {
1516                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1517                {
1518                        $result['status'] = false;
1519                        $result['msg'] = $this->functions->lang('Ldap connection fail') . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
1520                        return $result;
1521                }
1522               
1523                $filter = "(&(phpgwAccountType=l)(uid=$uid))";
1524                $justthese = array("dn");
1525                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1526                $entry = ldap_get_entries($ldapMasterConnect, $search);
1527                $group_dn = $entry[0]['dn'];
1528                $attrs['mailForwardingAddress'] = $mail;
1529                $res = @ldap_mod_del($ldapMasterConnect, $group_dn, $attrs);
1530               
1531                if ($res)
1532                {
1533                        $result['status'] = true;
1534                }
1535                else
1536                {
1537                        $result['status'] = false;
1538                        if (ldap_errno($ldapMasterConnect) == '50')
1539                        {
1540                                $result['msg'] =        $this->functions->lang('Error on the function') . ' ldap_functions->remove_user2maillist' . ".\n" .
1541                                                                        $this->functions->lang('The user used for record on LPDA, must have write access') . ".\n";
1542                                                                        $this->functions->lang('The user') . ' ' . $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] . ' ' . $this->functions->lang('does not have this access') . ".\n";
1543                                                                        $this->functions->lang('Edit Global Catalog Config, in the admin module, and add an user with write access') . ".\n";
1544                        }                                       
1545                        else
1546                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->remove_user2maillist ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
1547                }
1548                ldap_close($ldapMasterConnect);
1549                return $result;
1550        }
1551
1552        function remove_user2maillist_scl($dn, $array_emails)
1553        {
1554                $attrs['mailSenderAddress'] = $array_emails;
1555                $res = @ldap_mod_del($this->ldap, $dn, $attrs);
1556               
1557                if ($res)
1558                {
1559                        $result['status'] = true;
1560                }
1561                else
1562                {
1563                        $result['status'] = false;
1564                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->remove_user2maillist_scp ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
1565                }
1566                return $result;
1567        }
1568
1569        function replace_user2maillists($new_mail, $old_mail)
1570        {
1571                $filter = "(&(phpgwAccountType=l)(mailforwardingaddress=$old_mail))";
1572                $justthese = array("dn");
1573                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1574                $entries = ldap_get_entries($this->ldap, $search);
1575                $result['status'] = true;
1576                for ($i=0; $i<$entries['count']; ++$i)
1577                {
1578                        $attrs['mailforwardingaddress'] = $old_mail;
1579                        $res1 = @ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs);
1580                        $attrs['mailforwardingaddress'] = $new_mail;
1581                        $res2 = @ldap_mod_add($this->ldap, $entries[$i]['dn'], $attrs);
1582               
1583                        if ((!$res1) || (!$res2))
1584                        {
1585                                $result['status'] = false;
1586                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->replace_user2maillists ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
1587                        }
1588                }
1589               
1590                return $result;
1591        }
1592       
1593        function get_user_info($uidnumber)
1594        {
1595                foreach ($this->manager_contexts as $index=>$context)
1596                {
1597                        $filter="(&(phpgwAccountType=u)(uidNumber=".$uidnumber."))";
1598                        $search = ldap_search($this->ldap, $context, $filter);
1599                        $entry = ldap_get_entries($this->ldap, $search);
1600                       
1601                        if ($entry['count'])
1602                        {
1603                                //Pega o dn do setor do usuario.
1604                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1605                                $sector_dn_array = explode(",", $entry[0]['dn']);
1606                $sector_dn_array_count = count($sector_dn_array);
1607                                for($i=1; $i<$sector_dn_array_count; ++$i)
1608                                        $sector_dn .= $sector_dn_array[$i] . ',';
1609                                //Retira ultimo pipe.
1610                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1611               
1612                                $result['context']                              = $sector_dn;
1613                                $result['uid']                                  = $entry[0]['uid'][0];
1614                                $result['uidnumber']                    = $entry[0]['uidnumber'][0];
1615                                $result['gidnumber']                    = $entry[0]['gidnumber'][0];
1616                                $result['departmentnumber']             = $entry[0]['departmentnumber'][0];
1617                                $result['givenname']                    = $entry[0]['givenname'][0];
1618                                $result['sn']                                   = utf8_decode($entry[0]['sn'][0]);
1619                                $result['telephonenumber']              = $entry[0]['telephonenumber'][0];
1620                                $result['passwd_expired']               = $entry[0]['phpgwlastpasswdchange'][0];
1621                                $result['phpgwaccountstatus']   = $entry[0]['phpgwaccountstatus'][0];
1622                                $result['phpgwaccountvisible']  = $entry[0]['phpgwaccountvisible'][0];
1623                                $result['accountstatus']                = $entry[0]['accountstatus'][0];
1624                                $result['mail']                                 = $entry[0]['mail'][0];
1625                                $result['mailalternateaddress'] = $entry[0]['mailalternateaddress'];
1626                                $result['mailforwardingaddress']= $entry[0]['mailforwardingaddress'];
1627                                $result['deliverymode']                 = $entry[0]['deliverymode'][0];
1628                                $result['userPasswordRFC2617']  = $entry[0]['userpasswordrfc2617'][0];
1629
1630                                //Photo
1631                                if ($entry[0]['jpegphoto']['count'] == 1)
1632                                        $result['photo_exist'] = 'true';
1633               
1634                                // Samba
1635                                for ($i=0; $i<$entry[0]['objectclass']['count']; ++$i)
1636                                {
1637                                        if ($entry[0]['objectclass'][$i] == 'sambaSamAccount')
1638                                                $result['sambaUser'] = true;
1639                                }
1640                                if (($this->current_config['expressoAdmin_samba_support'] == 'true') && ($result['sambaUser']))
1641                                {
1642                                        $result['sambaaccflags'] = $entry[0]['sambaacctflags'][0];
1643                                        $result['sambalogonscript'] = $entry[0]['sambalogonscript'][0];
1644                                        $result['homedirectory'] = $entry[0]['homedirectory'][0];
1645                                        $a_tmp = explode("-", $entry[0]['sambasid'][0]);
1646                                        array_pop($a_tmp);
1647                                        $result['sambasid'] = implode("-", $a_tmp);
1648                                }
1649
1650                                // Verifica o acesso do gerente aos atributos corporativos
1651                                if ($this->functions->check_acl($_SESSION['phpgw_session']['session_lid'], 'manipulate_corporative_information'))
1652                                {
1653                                        $result['corporative_information_employeenumber']= $entry[0]['employeenumber'][0];
1654                                        $result['corporative_information_cpf']                  = $entry[0]['cpf'][0];
1655                                        $result['corporative_information_rg']                   = $entry[0]['rg'][0];
1656                                        $result['corporative_information_rguf']                 = $entry[0]['rguf'][0];
1657                                        $result['corporative_information_description']  = utf8_decode($entry[0]['description'][0]);
1658                                }
1659                               
1660                                // MailLists
1661                                $result['maillists_info'] = $this->get_user_maillists($result['mail']);
1662                                if($result['maillists_info'])
1663                                {
1664                                        foreach ($result['maillists_info'] as $maillist)
1665                                        {
1666                                                $result['maillists'][] = $maillist['uid'];
1667                                        }
1668                                }
1669                               
1670                                // Groups
1671                                $justthese = array("gidnumber","cn");
1672                                $filter="(&(phpgwAccountType=g)(memberuid=".$result['uid']."))";
1673                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1674                        ldap_sort($this->ldap, $search, "cn");
1675                        $entries = ldap_get_entries($this->ldap, $search);
1676                        for ($i=0; $i<$entries['count']; ++$i)
1677                        {
1678                                $result['groups_ldap'][ $entries[$i]['gidnumber'][0] ] = utf8_decode($entries[$i]['cn'][0]);
1679                        }
1680                        }
1681                }
1682                if (is_array($result))
1683                        return $result;
1684                else
1685                        return false;
1686        }
1687
1688
1689        function get_user_cn_by_uid($uid)
1690        {
1691            foreach ($this->manager_contexts as $index=>$context)
1692            {
1693
1694                    $justthese = array("cn");
1695                    $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
1696                    $search = ldap_search($this->ldap, $context, $filter, $justthese);
1697                    $entry = ldap_get_entries($this->ldap, $search);
1698                    if($entry)
1699                        return utf8_decode($entry[0]['cn'][0]);
1700            }
1701            return null;
1702        }
1703
1704        function get_group_cn_by_gidnumber($gidnumber)
1705        {
1706            foreach ($this->manager_contexts as $index=>$context)
1707                {
1708               
1709                    $justthese = array("cn");
1710                    $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
1711                    $search = ldap_search($this->ldap, $context, $filter, $justthese);
1712                    $entry = ldap_get_entries($this->ldap, $search);
1713                    if($entry)
1714                        return utf8_decode($entry[0]['cn'][0]);
1715                        }
1716            return null;
1717                }
1718               
1719       
1720        function get_user_info_by_uid($uid)
1721        {
1722                foreach ($this->manager_contexts as $index=>$context)
1723                {
1724                        $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
1725                        $justthese = array("cn");
1726                        $search = ldap_search($this->ldap, $context, $filter);
1727                        $entry = ldap_get_entries($this->ldap, $search);
1728                       
1729                        if ($entry['count'])
1730                        {
1731                                //Pega o dn do setor do usuario.
1732                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1733                                $sector_dn_array = explode(",", $entry[0]['dn']);
1734                $sector_dn_array_count = count($sector_dn_array);
1735                                for($i=1; $i<$sector_dn_array_count; ++$i)
1736                                        $sector_dn .= $sector_dn_array[$i] . ',';
1737                                //Retira ultimo pipe.
1738                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1739               
1740                                $result['context']                              = $sector_dn;
1741                                $result['uid']                                  = $entry[0]['uid'][0];
1742                                $result['cn']                                   = utf8_decode($entry[0]['cn'][0]);
1743                                $result['uidnumber']                    = $entry[0]['uidnumber'][0];
1744                                $result['gidnumber']                    = $entry[0]['gidnumber'][0];
1745                                $result['departmentnumber']             = $entry[0]['departmentnumber'][0];
1746                                $result['givenname']                    = $entry[0]['givenname'][0];
1747                                $result['sn']                                   = $entry[0]['sn'][0];
1748                                $result['telephonenumber']              = $entry[0]['telephonenumber'][0];
1749                                $result['passwd_expired']               = $entry[0]['phpgwlastpasswdchange'][0];
1750                                $result['phpgwaccountstatus']   = $entry[0]['phpgwaccountstatus'][0];
1751                                $result['phpgwaccountvisible']  = $entry[0]['phpgwaccountvisible'][0];
1752                                $result['accountstatus']                = $entry[0]['accountstatus'][0];
1753                                $result['mail']                                 = $entry[0]['mail'][0];
1754                                $result['mailalternateaddress'] = $entry[0]['mailalternateaddress'];
1755                                $result['mailforwardingaddress']= $entry[0]['mailforwardingaddress'];
1756                                $result['deliverymode']                 = $entry[0]['deliverymode'][0];
1757                                $result['userPasswordRFC2617']  = $entry[0]['userpasswordrfc2617'][0];
1758
1759                                //Photo
1760                                if ($entry[0]['jpegphoto']['count'] == 1)
1761                                        $result['photo_exist'] = 'true';
1762               
1763                                // Samba
1764                                for ($i=0; $i<$entry[0]['objectclass']['count']; ++$i)
1765                                {
1766                                        if ($entry[0]['objectclass'][$i] == 'sambaSamAccount')
1767                                                $result['sambaUser'] = true;
1768                                }
1769                                if (($this->current_config['expressoAdmin_samba_support'] == 'true') && ($result['sambaUser']))
1770                                {
1771                                        $result['sambaaccflags'] = $entry[0]['sambaacctflags'][0];
1772                                        $result['sambalogonscript'] = $entry[0]['sambalogonscript'][0];
1773                                        $result['homedirectory'] = $entry[0]['homedirectory'][0];
1774                                        $a_tmp = explode("-", $entry[0]['sambasid'][0]);
1775                                        array_pop($a_tmp);
1776                                        $result['sambasid'] = implode("-", $a_tmp);
1777                                }
1778
1779                                // Verifica o acesso do gerente aos atributos corporativos
1780                                if ($this->functions->check_acl($_SESSION['phpgw_session']['session_lid'], 'manipulate_corporative_information'))
1781                                {
1782                                        $result['corporative_information_employeenumber']= $entry[0]['employeenumber'][0];
1783                                        $result['corporative_information_cpf']                  = $entry[0]['cpf'][0];
1784                                        $result['corporative_information_rg']                   = $entry[0]['rg'][0];
1785                                        $result['corporative_information_rguf']                 = $entry[0]['rguf'][0];
1786                                        $result['corporative_information_description']  = utf8_decode($entry[0]['description'][0]);
1787                                }
1788                               
1789                                // MailLists
1790                                $result['maillists_info'] = $this->get_user_maillists($result['mail']);
1791                                if($result['maillists_info'])
1792                                {
1793                                        foreach ($result['maillists_info'] as $maillist)
1794                                        {
1795                                                $result['maillists'][] = $maillist['uid'];
1796                                        }
1797                                }
1798                               
1799                                // Groups
1800                                $justthese = array("gidnumber","cn");
1801                                $filter="(&(phpgwAccountType=g)(memberuid=".$result['uid']."))";
1802                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1803                        ldap_sort($this->ldap, $search, "cn");
1804                        $entries = ldap_get_entries($this->ldap, $search);
1805                        for ($i=0; $i<$entries['count']; ++$i)
1806                        {
1807                                $result['groups_ldap'][ $entries[$i]['gidnumber'][0] ] = utf8_decode($entries[$i]['cn'][0]);
1808                        }
1809                        }
1810                }
1811                if (is_array($result))
1812                        return $result;
1813                else
1814                        return false;
1815        }
1816               
1817        function get_user_maillists($mail)
1818        {
1819                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
1820                        return false;
1821               
1822                $result = array();
1823               
1824                //Mostra somente os mailists dos contextos do gerente
1825                $justthese = array("uid","mail","uidnumber");
1826                $filter="(&(phpgwAccountType=l)(mailforwardingaddress=$mail))";
1827               
1828                foreach ($this->manager_contexts as $index=>$context)
1829                {
1830                        $search = ldap_search($ldapMasterConnect, $context, $filter, $justthese);
1831                $entries = ldap_get_entries($ldapMasterConnect, $search);
1832               
1833                for ($i=0; $i<$entries['count']; ++$i)
1834                {
1835                                $result[ $entries[$i]['uid'][0] ]['uid']                = $entries[$i]['uid'][0];
1836                                $result[ $entries[$i]['uid'][0] ]['mail']               = $entries[$i]['mail'][0];
1837                               
1838                                $a_tmp[] = $entries[$i]['uid'][0];
1839                }
1840                }
1841       
1842        if($a_tmp) {
1843                natcasesort($a_tmp);
1844       
1845                foreach ($a_tmp as $uid)
1846                {
1847                                $return[$uid]['uid']            = $result[$uid]['uid'];
1848                                $return[$uid]['mail']           = $result[$uid]['mail'];
1849                }
1850        }
1851        ldap_close($ldapMasterConnect);
1852                return $return;
1853        }
1854       
1855        function get_group_info($gidnumber)
1856        {
1857                foreach ($this->manager_contexts as $index=>$context)
1858                {
1859                        $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
1860                        $search = ldap_search($this->ldap, $context, $filter);
1861                        $entry = ldap_get_entries($this->ldap, $search);
1862                       
1863                        if ($entry['count'])
1864                        {
1865                                //Pega o dn do setor do grupo.
1866                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1867                                $sector_dn_array = explode(",", $entry[0]['dn']);
1868                $sector_dn_array_count = count($sector_dn_array);
1869                                for($i=1; $i<$sector_dn_array_count; ++$i)
1870                                        $sector_dn .= $sector_dn_array[$i] . ',';
1871                                //Retira ultimo pipe.
1872                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1873               
1874                                $result['context']                              = $sector_dn;
1875                                $result['cn']                                   = $entry[0]['cn'][0];
1876                                $result['description']                  = $entry[0]['description'][0];
1877                                $result['gidnumber']                    = $entry[0]['gidnumber'][0];
1878                                $result['phpgwaccountvisible']  = $entry[0]['phpgwaccountvisible'][0];
1879                                $result['email']                                = $entry[0]['mail'][0];
1880               
1881                                //MemberUid
1882                                for ($i=0; $i<$entry[0]['memberuid']['count']; ++$i)
1883                                {
1884                                        $justthese = array("cn","uid","uidnumber");
1885                       
1886                                        // Montagem dinamica do filtro
1887                                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s))(|";
1888                                        for ($k=0; (($k<10) && ($i<$entry[0]['memberuid']['count'])); ++$k)
1889                                        {
1890                                                $filter .= "(uid=".$entry[0]['memberuid'][$i].")";
1891                        ++$i;
1892                                        }
1893                                        $i--;
1894                                        $filter .= "))";
1895                       
1896                                        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1897                                        $user_entry = ldap_get_entries($this->ldap, $search);
1898
1899                                        for ($j=0; $j<$user_entry['count']; ++$j)
1900                                        {
1901                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['cn'] = $user_entry[$j]['cn'][0];
1902                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['uidnumber'] = $user_entry[$j]['uidnumber'][0];
1903                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['type'] = 'u';
1904                                        }
1905                                }
1906               
1907                                // Checamos e-mails que não fazem parte do expresso.
1908                                // Criamos um array temporario
1909                                $tmp_array = array();
1910                                if($result['memberuid_info'])
1911                                        foreach ($result['memberuid_info'] as $uid => $user_data)
1912                                        {
1913                                                $tmp_array[] = $uid;
1914                                        }
1915               
1916                                if($entry[0]['memberuid']) {
1917                                        // Retira o count do array
1918                                        array_shift($entry[0]['memberuid']);
1919                                        // Vemos a diferença
1920                                        $array_diff = array_diff($entry[0]['memberuid'], $tmp_array);
1921                                        // Incluimos no resultado                       
1922                                        foreach ($array_diff as $index=>$uid)
1923                                        {
1924                                                $result['memberuid_info'][$uid]['cn'] = $uid;
1925                                        }
1926                                }
1927               
1928                                // Samba
1929                                for ($i=0; $i<$entry[0]['objectclass']['count']; ++$i)
1930                                {
1931                                        if ($entry[0]['objectclass'][$i] == 'sambaGroupMapping')
1932                                                $result['sambaGroup'] = true;
1933
1934                                        $a_tmp = explode("-", $entry[0]['sambasid'][0]);
1935                                        array_pop($a_tmp);
1936                                        $result['sambasid'] = implode("-", $a_tmp);
1937                                }
1938                                return $result;
1939                        }
1940                }
1941        }       
1942       
1943        function get_maillist_info($uidnumber)
1944        {
1945                /* folling referral connection */
1946                $ldap_conn_following_ref = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
1947                if ($ldap_conn_following_ref)
1948                {
1949                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_PROTOCOL_VERSION, 3);
1950                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_REFERRALS, 1);
1951
1952                        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
1953                                ldap_bind($ldap_conn_following_ref, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
1954                }
1955               
1956                foreach ($this->manager_contexts as $index=>$context)
1957                {
1958                        $filter="(&(phpgwAccountType=l)(uidNumber=".$uidnumber."))";
1959                        $search = ldap_search($this->ldap, $context, $filter);
1960                        $entry = ldap_get_entries($this->ldap, $search);
1961                       
1962                        if ($entry['count'])
1963                        {
1964                                //Pega o dn do setor do usuario.
1965                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1966                                $sector_dn_array = explode(",", $entry[0]['dn']);
1967                $sector_dn_array_count = count($sector_dn_array);
1968                                for($i=1; $i<$sector_dn_array_count; ++$i)
1969                                        $sector_dn .= $sector_dn_array[$i] . ',';
1970                                //Retira ultimo pipe.
1971                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1972                       
1973                                $result['context']                              = $sector_dn;
1974                                $result['uidnumber']                    = $entry[0]['uidnumber'][0];
1975                                $result['uid']                                  = strtolower($entry[0]['uid'][0]);
1976                                $result['cn']                                   = $entry[0]['cn'][0];
1977                                $result['mail']                                 = $entry[0]['mail'][0];
1978                                $result['description']                  = utf8_decode($entry[0]['description'][0]);
1979                                $result['accountStatus']                = $entry[0]['accountstatus'][0];
1980                                $result['phpgwAccountVisible']  = $entry[0]['phpgwaccountvisible'][0];
1981                       
1982                                //Members
1983                                for ($i=0; $i<$entry[0]['mailforwardingaddress']['count']; ++$i)
1984                                {
1985                                        $justthese = array("cn", "uidnumber", "uid", "phpgwaccounttype", "mail");
1986                               
1987                                        // Montagem dinamica do filtro, para nao ter muitas conexoes com o ldap
1988                                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|";
1989                                        for ($k=0; (($k<10) && ($i<$entry[0]['mailforwardingaddress']['count'])); ++$k)
1990                                        {
1991                                                $filter .= "(mail=".$entry[0]['mailforwardingaddress'][$i].")";
1992                        ++$i;
1993                                        }
1994                                        $i--;
1995                                        $filter .= "))";
1996                               
1997                                        $search = ldap_search($ldap_conn_following_ref, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1998                                        $user_entry = ldap_get_entries($ldap_conn_following_ref, $search);
1999                                                                       
2000                                        for ($j=0; $j<$user_entry['count']; ++$j)
2001                                        {
2002                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['uid'] = $user_entry[$j]['uid'][0];
2003                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['cn'] = $user_entry[$j]['cn'][0];
2004                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['type'] = $user_entry[$j]['phpgwaccounttype'][0];
2005                                                $result['mailForwardingAddress'][] = $user_entry[$j]['mail'][0];
2006                                        }
2007                                }
2008
2009                                // Emails não encontrados no ldap
2010                                array_shift($entry[0]['mailforwardingaddress']); //Retira o count do array
2011                                $missing_emails = array_diff($entry[0]['mailforwardingaddress'], $result['mailForwardingAddress']);
2012                               
2013                                // Incluimos estes no resultado
2014                                foreach ($missing_emails as $index=>$mailforwardingaddress)
2015                                {
2016                                        $result['mailForwardingAddress_info'][$mailforwardingaddress]['uid'] = $mailforwardingaddress;
2017                                        $result['mailForwardingAddress_info'][$mailforwardingaddress]['cn'] = 'E-Mail nao encontrado';
2018                                        $result['mailForwardingAddress'][] = $mailforwardingaddress;
2019                                }
2020                               
2021                                ldap_close($ldap_conn_following_ref);
2022                                return $result;
2023                        }
2024                }
2025        }       
2026
2027        function get_maillist_scl_info($uidnumber)
2028        {
2029                foreach ($this->manager_contexts as $index=>$context)
2030                {
2031                        $filter="(&(phpgwAccountType=l)(uidNumber=$uidnumber))";
2032                        $search = ldap_search($this->ldap, $context, $filter);
2033                        $entry = ldap_get_entries($this->ldap, $search);
2034
2035                        if ($entry['count'])
2036                        {
2037                                //Pega o dn do setor do usuario.
2038                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
2039                                $sector_dn_array = explode(",", $entry[0]['dn']);
2040                $sector_dn_array_count = count($sector_dn_array);
2041                                for($i=1; $i<$sector_dn_array_count; ++$i)
2042                                        $sector_dn .= $sector_dn_array[$i] . ',';
2043                                //Retira ultimo pipe.
2044                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
2045               
2046                                $result['dn']                                           = $entry[0]['dn'];
2047                                $result['context']                                      = $sector_dn;
2048                                $result['uidnumber']                            = $entry[0]['uidnumber'][0];
2049                                $result['uid']                                          = $entry[0]['uid'][0];
2050                                $result['cn']                                           = $entry[0]['cn'][0];
2051                                $result['mail']                                         = $entry[0]['mail'][0];
2052                                $result['accountStatus']                        = $entry[0]['accountstatus'][0];
2053                                $result['phpgwAccountVisible']          = $entry[0]['phpgwaccountvisible'][0];
2054                                $result['accountRestrictive']           = $entry[0]['accountrestrictive'][0];
2055                                $result['participantCanSendMail']       = $entry[0]['participantcansendmail'][0];
2056               
2057                                //Senders
2058                                for ($i=0; $i<$entry[0]['mailsenderaddress']['count']; ++$i)
2059                                {
2060                                        $justthese = array("cn", "uidnumber", "uid", "mail");
2061                                        $filter="(&(phpgwAccountType=u)(mail=".$entry[0]['mailsenderaddress'][$i]."))";
2062                                        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2063                                        $user_entry = ldap_get_entries($this->ldap, $search);
2064                       
2065                                        $result['senders_info'][$user_entry[0]['mail'][0]]['uid'] = $user_entry[0]['uid'][0];
2066                                        $result['senders_info'][$user_entry[0]['mail'][0]]['cn'] = $user_entry[0]['cn'][0];
2067                                        $result['members'][] = $user_entry[0]['mail'][0];
2068                                }
2069                                return $result;
2070                        }
2071                }
2072        }       
2073
2074        function group_exist($gidnumber)
2075        {
2076                $justthese = array("cn");
2077                $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
2078                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2079                               
2080                $entry = ldap_get_entries($this->ldap, $search);
2081                if ($entry['count'] == 0)
2082                        return false;
2083                else
2084                        return true;
2085        }
2086
2087        function gidnumbers2cn($gidnumbers)
2088        {
2089                $result = array();
2090                if (count($gidnumbers))
2091                {
2092                        $justthese = array("cn","uid");
2093                        $i = 0;
2094                        foreach ($gidnumbers as $gidnumber)
2095                        {
2096                                $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
2097                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2098                               
2099                                $entry = ldap_get_entries($this->ldap, $search);
2100                                if ($entry['count'] == 0)
2101                                        $result['groups_info'][$i]['cn'] = '_' . $this->functions->lang('group only exist on DB, but does not exist on ldap');
2102                                       
2103                                else
2104                                {
2105                                        $result['groups_info'][$i]['uid'] = $entry[0]['uid'][0];
2106                                        $result['groups_info'][$i]['cn'] = $entry[0]['cn'][0];
2107                                }
2108                                $result['groups_info'][$i]['gidnumber'] = $gidnumber;
2109                       
2110                                /* o gerente pode excluir um grupo de um usuario onde este grupo esta em outra OU ? */
2111                                /* é o mesmo que o manager editar um grupo de outra OU */
2112                                $result['groups_info'][$i]['group_disabled'] = 'true';
2113                                foreach ($this->manager_contexts as $index=>$context)
2114                                {
2115                                        if (strpos(strtolower($entry[0]['dn']), strtolower($context)))
2116                                        {
2117                                                $result['groups_info'][$i]['group_disabled'] = 'false';
2118                                        }
2119                                }
2120
2121                ++$i;
2122                        }
2123                }
2124                return $result;
2125        }
2126
2127        function uidnumber2uid($uidnumber)
2128        {
2129                $justthese = array("uid");
2130                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
2131                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2132                $entry = ldap_get_entries($this->ldap, $search);
2133                return $entry[0]['uid'][0];
2134        }
2135       
2136        function uid2cn($uid)
2137        {
2138                $justthese = array("cn");
2139                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=".$uid."))";
2140                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2141                $entry = ldap_get_entries($this->ldap, $search);
2142                return utf8_decode($entry[0]['cn'][0]);
2143        }
2144
2145        function uid2uidnumber($uid)
2146        {
2147                $justthese = array("uidNumber");
2148                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=l))(uid=".$uid."))";
2149                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2150                $entry = ldap_get_entries($this->ldap, $search);
2151                return $entry[0]['uidnumber'][0];
2152        }
2153
2154        function uidnumber2mail($uidnumber)
2155        {
2156                $justthese = array("mail");
2157                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
2158                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2159                $entry = ldap_get_entries($this->ldap, $search);
2160                return $entry[0]['mail'][0];
2161        }
2162
2163        function get_associated_domain($params)
2164        {
2165                        $justthese = array("associatedDomain");
2166                        $filter="(objectClass=domainRelatedObject)";;
2167                        $context = $params['context'];
2168                        $search = ldap_search($this->ldap,$context, $filter, $justthese);
2169                        $entry = ldap_get_entries($this->ldap, $search);
2170                        return $entry[0]['associateddomain'][0];
2171        }
2172       
2173        function change_user_context($dn, $newrdn, $newparent)
2174        {
2175                if (!ldap_rename ( $this->ldap, $dn, $newrdn, $newparent, true ))
2176                {
2177                        $return['status'] = false;
2178                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->change_user_context ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2179                }
2180                else
2181                        $return['status'] = true;
2182               
2183                return $return;
2184        }
2185       
2186        function replace_user_attributes($dn, $ldap_mod_replace)
2187        {
2188                if (!@ldap_mod_replace ( $this->ldap, $dn, $ldap_mod_replace ))
2189                {
2190                        $return['status'] = false;
2191                        $return['error_number'] = ldap_errno($this->ldap);
2192                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->replace_user_attributes ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2193                }
2194                else
2195                        $return['status'] = true;
2196               
2197                return $return;
2198        }
2199       
2200        function add_user_attributes($dn, $ldap_add)
2201        {
2202                if (!@ldap_mod_add ( $this->ldap, $dn, $ldap_add ))
2203                {
2204                        $return['status'] = false;
2205                        $return['error_number'] = ldap_errno($this->ldap);
2206                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->add_user_attributes ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2207                }
2208                else
2209                        $return['status'] = true;
2210               
2211                return $return;
2212        }
2213       
2214        function remove_user_attributes($dn, $ldap_remove)
2215        {
2216                if (!@ldap_mod_del ( $this->ldap, $dn, $ldap_remove ))
2217                {
2218                        $return['status'] = false;
2219                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->remove_user_attributes ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2220                }
2221                else
2222                        $return['status'] = true;
2223               
2224                return $return;
2225        }
2226       
2227        function set_user_password($uid, $password)
2228        {
2229                $justthese = array("userPassword");
2230                $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
2231                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2232            $entry = ldap_get_entries($this->ldap, $search);
2233                $dn = $entry[0]['dn'];
2234                $userPassword = $entry[0]['userpassword'][0];
2235                $ldap_mod_replace['userPassword'] = $password;
2236                $this->replace_user_attributes($dn, $ldap_mod_replace);
2237                return $userPassword;
2238        }
2239       
2240        function delete_user($user_info)
2241        {
2242                // Verifica acesso do gerente (OU) ao tentar deletar um usuário.
2243                $manager_access = false;
2244                foreach ($this->manager_contexts as $index=>$context)
2245                {
2246                        if ( (strpos(strtolower($user_info['context']), strtolower($context))) || (strtolower($user_info['context']) == strtolower($context)) )
2247                        {
2248                                $manager_access = true;
2249                                break;
2250                        }
2251                }
2252                if (!$manager_access)
2253                {
2254                        $return['status'] = false;
2255                        $result['msg'] = $this->functions->lang('You do not have access to delete this user') . ".";
2256                        return $return;
2257                }
2258               
2259                $return['status'] = true;
2260                $return['msg'] = "";
2261                               
2262                // GROUPS
2263                $attrs = array();
2264                $attrs['memberuid'] = $user_info['uid'];
2265               
2266                if (count($user_info['groups_info']))
2267                {
2268                        foreach ($user_info['groups_info'] as $group_info)
2269                        {
2270                                $gidnumber = $group_info['gidnumber'];
2271                                $justthese = array("dn");
2272                                $filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
2273                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2274                        $entry = ldap_get_entries($this->ldap, $search);
2275                                $dn = $entry[0]['dn'];
2276
2277                                if (!@ldap_mod_del($this->ldap, $dn, $attrs))
2278                                {
2279                                        $return['status'] = false;
2280                                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_user from group ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2281                                }
2282                        }
2283                }
2284               
2285                //INSTITUTIONAL ACCOUNTS
2286                $attrs = array();
2287                $attrs['mailForwardingAddress'] = $user_info['mail'];
2288               
2289                $justthese = array("dn");
2290                $filter="(&(phpgwAccountType=i)(mailforwardingaddress=".$user_info['mail']."))";
2291                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2292            $entries = ldap_get_entries($this->ldap, $search);
2293               
2294                for ($i=0; $i<$entries['count']; ++$i)
2295                {
2296                        if ( !@ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs) )
2297                        {
2298                                $result['status'] = false;
2299                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_user, institutional accounts ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2300                        }
2301                }
2302               
2303                // MAILLISTS
2304                $attrs = array();
2305                $attrs['mailForwardingAddress'] = $user_info['mail'];
2306               
2307                if (count($user_info['maillists_info']))
2308                {
2309                       
2310                        if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
2311                        {
2312                                $return['status'] = false;
2313                                $result['msg'] = $this->functions->lang('Connection with ldap_master fail') . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2314                                return $return;
2315                        }
2316                       
2317                        foreach ($user_info['maillists_info'] as $maillists_info)
2318                        {
2319                                $uid = $maillists_info['uid'];
2320                                $justthese = array("dn");
2321                                $filter="(&(phpgwAccountType=l)(uid=".$uid."))";
2322                                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2323                        $entry = ldap_get_entries($ldapMasterConnect, $search);
2324                                $dn = $entry[0]['dn'];
2325                       
2326                                if (!@ldap_mod_del($ldapMasterConnect, $dn, $attrs))
2327                                {
2328                                        $return['status'] = false;
2329                                        if (ldap_errno($ldapMasterConnect) == '50')
2330                                        {
2331                                                $result['msg'] =        $this->functions->lang('Error on the function') . ' ldap_functions->add_user2maillist' . ".\n" .
2332                                                                                        $this->functions->lang('The user used for record on LPDA, must have write access') . ".\n";
2333                                                                                        $this->functions->lang('The user') . ' ' . $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] . ' ' . $this->functions->lang('does not have this access') . ".\n";
2334                                                                                        $this->functions->lang('Edit Global Catalog Config, in the admin module, and add an user with write access') . ".\n";
2335                                        }
2336                                        else
2337                                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_user, email lists ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
2338                                }
2339                        }
2340                        ldap_close($ldapMasterConnect);
2341                }
2342                       
2343                // UID
2344                $dn = "uid=" . $user_info['uid'] . "," . $user_info['context'];
2345                if (!@ldap_delete($this->ldap, $dn))
2346                {
2347                        $return['status'] = false;
2348                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_user, email lists ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
2349                }
2350                /* jakjr */
2351                return $return;
2352        }
2353       
2354        function delete_maillist($uidnumber, $mail)
2355        {
2356                $return['status'] = true;
2357               
2358                $justthese = array("dn");
2359               
2360                // remove listas dentro de listas
2361                $filter="(&(phpgwAccountType=l)(mailForwardingAddress=".$mail."))";
2362                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2363                $entry = ldap_get_entries($this->ldap, $search);
2364                $attrs['mailForwardingAddress'] = $mail;
2365                for ($i=0; $i<=$entry['count']; ++$i)
2366            {
2367                        $dn = $entry[$i]['dn'];
2368                @ldap_mod_del ( $this->ldap, $dn,  $attrs);
2369            }
2370               
2371                $filter="(&(phpgwAccountType=l)(uidnumber=".$uidnumber."))";
2372                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2373                $entry = ldap_get_entries($this->ldap, $search);
2374                $dn = $entry[0]['dn'];
2375               
2376                if (!@ldap_delete($this->ldap, $dn))
2377                {
2378                        $return['status'] = false;
2379                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_maillist ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2380                }
2381               
2382                return $return;
2383        }
2384
2385        function delete_group($gidnumber)
2386        {
2387                $return['status'] = true;
2388               
2389                $justthese = array("dn");
2390                $filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
2391                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2392                $entry = ldap_get_entries($this->ldap, $search);
2393                $dn = $entry[0]['dn'];
2394               
2395                if (!@ldap_delete($this->ldap, $dn))
2396                {
2397                        $return['status'] = false;
2398                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_group ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2399                }
2400               
2401                return $return;
2402        }
2403
2404        function check_access_to_renamed($uid)
2405        {
2406                $justthese = array("dn");
2407                $filter="(&(phpgwAccountType=u)(uid=$uid))";
2408               
2409                foreach ($this->manager_contexts as $index=>$context)
2410                {
2411                        $search = ldap_search($this->ldap, $context, $filter, $justthese);
2412                        $entry = ldap_get_entries($this->ldap, $search);
2413                        if ($entry['count'])
2414                                return true;
2415                }
2416            return false;
2417        }
2418
2419        function check_rename_new_uid($uid)
2420        {
2421                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
2422                        return false;
2423               
2424                $justthese = array("dn");
2425                $filter="(&(phpgwAccountType=u)(uid=$uid))";
2426               
2427                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2428                $count_entries = @ldap_count_entries($ldapMasterConnect, $search);
2429               
2430                if ($count_entries)
2431                        return false;
2432                       
2433                return true;
2434        }
2435       
2436        function rename_uid($uid, $new_uid)
2437        {
2438                $return['status'] = true;
2439               
2440                $justthese = array("dn");
2441                $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
2442                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2443            $entry = ldap_get_entries($this->ldap, $search);
2444                $dn = $entry[0]['dn'];
2445               
2446                $explode_dn = ldap_explode_dn($dn, 0);
2447                $rdn = "uid=" . $new_uid;
2448
2449                $parent = array();
2450                for ($j=1; $j<(count($explode_dn)-1); ++$j)
2451                        $parent[] = $explode_dn[$j];
2452                $parent = implode(",", $parent);
2453               
2454                $return['new_dn'] = $rdn . ',' . $parent;
2455                       
2456                if (!@ldap_rename($this->ldap, $dn, $rdn, $parent, true))
2457                {
2458                        $return['status'] = false;
2459                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->rename_uid ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2460                }
2461               
2462                //Grupos
2463                $justthese = array("dn");
2464                $filter="(&(phpgwAccountType=g)(memberuid=".$uid."))";
2465                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2466            $entry = ldap_get_entries($this->ldap, $search);
2467        $array_mod_add['memberUid'] = $new_uid;
2468        $array_mod_del['memberUid'] = $uid;
2469
2470            for ($i=0; $i<=$entry['count']; ++$i)
2471            {
2472                $dn = $entry[$i]['dn'];
2473                @ldap_mod_add ( $this->ldap, $dn,  $array_mod_add);
2474                @ldap_mod_del ( $this->ldap, $dn,  $array_mod_del);
2475            }
2476                return $return;
2477        }
2478
2479        function rename_cn($cn, $new_cn)
2480        {
2481                $return['status'] = true;
2482               
2483                $justthese = array("dn");
2484                $filter="(&(phpgwAccountType=g)(uid=".$cn."))";
2485                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2486            $entry = ldap_get_entries($this->ldap, $search);
2487                $dn = $entry[0]['dn'];
2488               
2489                $explode_dn = ldap_explode_dn($dn, 0);
2490                $rdn = "cn=" . $new_cn;
2491
2492                $parent = array();
2493                for ($j=1; $j<(count($explode_dn)-1); ++$j)
2494                        $parent[] = $explode_dn[$j];
2495                $parent = implode(",", $parent);
2496               
2497                $return['new_dn'] = $rdn . ',' . $parent;
2498                       
2499                if (!@ldap_rename($this->ldap, $dn, $rdn, $parent, false))
2500                {
2501                        $return['status'] = false;
2502                }
2503               
2504                return $return;
2505        }
2506       
2507        function exist_sambadomains($contexts, $sambaDomainName)
2508        {
2509                $justthese = array("dn");
2510                $filter="(&(objectClass=sambaDomain)(sambaDomainName=$sambaDomainName))";
2511               
2512                foreach ($contexts as $index=>$context)
2513                {
2514                        $search = ldap_search($this->ldap, $context, $filter, $justthese);
2515                    $entry = ldap_get_entries($this->ldap, $search);
2516           
2517                        if ($entry['count'])
2518                                return true;
2519                }
2520                return false;
2521        }
2522       
2523        // Primeiro nilvel de organização.
2524        function exist_sambadomains_in_context($params)
2525        {
2526                $dn = $GLOBALS['phpgw_info']['server']['ldap_context'];
2527                $array_dn = ldap_explode_dn ( $dn, 0 );
2528               
2529                $context = $params['context'];
2530                $array_context = ldap_explode_dn ( $context, 0 );
2531               
2532                // Pego o setor no caso do contexto ser um sub-setor.
2533                if (($array_dn['count']+1) < ($array_context['count']))
2534                {
2535                        // inverto o array_dn para poder retirar o count
2536                        $array_dn_reverse  = array_reverse ( $array_dn, false );
2537                       
2538                        //retiro o count
2539                        array_pop($array_dn_reverse);
2540                       
2541                        //incluo o setor no dn
2542                        array_push ( $array_dn_reverse,  $array_context[ $array_context['count'] - 1 - $array_dn['count']]);
2543                       
2544                        // Volto a ordem natural
2545                        $array_dn  = array_reverse ( $array_dn_reverse, false );
2546                       
2547                        // Implodo
2548                        $context = implode ( ",", $array_dn );
2549                }
2550               
2551                $justthese = array("dn","sambaDomainName");
2552                $filter="(objectClass=sambaDomain)";
2553                $search = ldap_list($this->ldap, $context, $filter, $justthese);
2554            $entry = ldap_get_entries($this->ldap, $search);
2555           
2556            for ($i=0; $i<$entry['count']; ++$i)
2557            {
2558                        $return['sambaDomains'][$i] = $entry[$i]['sambadomainname'][0];
2559            }
2560           
2561                if ($entry['count'])
2562                        $return['status'] = true;
2563                else
2564                        $return['status'] = false;
2565                       
2566                return $return;
2567        }
2568        function exist_domain_name_sid($sambadomainname, $sambasid)
2569        {
2570                $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
2571
2572                $justthese = array("dn","sambaDomainName");
2573                $filter="(&(objectClass=sambaDomain)(sambaSID=$sambasid)(sambaDomainName=$sambadomainname))";
2574                $search = ldap_search($this->ldap, $context, $filter, $justthese);
2575            $count_entries = ldap_count_entries($this->ldap, $search);
2576               
2577            if ($count_entries > 0)
2578                return true;
2579            else
2580                return false;
2581                }
2582               
2583        function add_sambadomain($sambadomainname, $sambasid, $context)
2584        {
2585                $result = array();
2586               
2587                $dn                                                             = "sambaDomainName=$sambadomainname,$context";
2588                $entry['sambaSID']                                      = $sambasid;
2589                $entry['objectClass']                           = 'sambaDomain';
2590                $entry['sambaAlgorithmicRidBase']       = '1000';
2591                $entry['sambaDomainName']                       = $sambadomainname;
2592               
2593                if (!@ldap_add ( $this->ldap, $dn, $entry ))
2594                        {
2595                        $return['status'] = false;
2596                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->add_sambadomain ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2597                }
2598                else
2599                        $return['status'] = true;
2600               
2601                return $return;
2602        }
2603               
2604        function delete_sambadomain($sambadomainname)
2605        {
2606                $return['status'] = true;
2607                $filter="(sambaDomainName=$sambadomainname)";
2608                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter);
2609            $entry = ldap_get_entries($this->ldap, $search);
2610               
2611                if ($entry['count'] != 0)
2612                {
2613                        $dn = $entry[0]['dn'];
2614                       
2615                        if (!@ldap_delete($this->ldap, $dn))
2616                        {
2617                                $return['status'] = false;
2618                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_sambadomain ($sambadomainname)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2619                        }
2620                }
2621               
2622                return $return;
2623        }
2624       
2625        function search_user($params)
2626                {
2627             $ldapService = ServiceLocator::getService('ldap');
2628             $entries = $ldapService->accountSearch($params['search'], array('cn','uid', "mail"), $params['context'], 'u', 'cn');
2629
2630             if (count($entries) == 0)
2631             {
2632                    $return['status'] = 'false';
2633                    $return['msg'] = $this->functions->lang('Any result was found') . '.';
2634                    return $return;
2635                }
2636             $options = '';
2637
2638             foreach ($entries as  $value)
2639                 $options .= '<option value='.$value['uid'].'>'.$value['cn'].'('.$value['mail'].')'.'</option>';
2640   
2641        return $options;               
2642        }
2643       
2644        function get_institutional_accounts($params)
2645        {
2646                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'list_institutional_accounts'))
2647                {
2648                        $return['status'] = false;
2649                        $return['msg'] = $this->functions->lang('You do not have right to list institutional accounts') . ".";
2650                        return $return;
2651                }
2652
2653                $input = $params['input'];
2654                $justthese = array("cn", "mail", "uid");
2655                $trs = array();
2656                               
2657                foreach ($this->manager_contexts as $idx=>$context)
2658                {
2659                $institutional_accounts = ldap_search($this->ldap, $context, ("(&(phpgwAccountType=i)(|(mail=$input*)(cn=*$input*)))"), $justthese);
2660                $entries = ldap_get_entries($this->ldap, $institutional_accounts);
2661               
2662                        for ($i=0; $i<$entries['count']; ++$i)
2663                        {
2664                                $tr = "<tr class='normal' onMouseOver=this.className='selected' onMouseOut=this.className='normal'><td onClick=edit_institutional_account('".$entries[$i]['uid'][0]."')>" . utf8_decode($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>";
2665                                $trs[$tr] = utf8_decode($entries[$i]['cn'][0]);
2666                        }
2667                }
2668       
2669        $trs_string = '';
2670        if (count($trs))
2671        {
2672                natcasesort($trs);
2673                foreach ($trs as $tr=>$cn)
2674                {
2675                        $trs_string .= $tr;
2676                }
2677        }
2678       
2679        $return['status'] = 'true';
2680        $return['trs'] = $trs_string;
2681        return $return;
2682}       
2683       
2684        function get_institutional_account_data($params)
2685        {
2686                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_institutional_accounts'))
2687                {
2688                        $return['status'] = false;
2689                        $return['msg'] = $this->functions->lang('You do not have right to edit institutional accounts') . ".";
2690                        return $return;
2691                }
2692               
2693                $uid = $params['uid'];
2694                //$justthese = array("accountStatus", "phpgwAccountVisible", "cn", "mail", "mailForwardingAddress", "description");
2695                               
2696        $institutional_accounts = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=i)(uid=$uid))"));
2697        $entrie = ldap_get_entries($this->ldap, $institutional_accounts);
2698               
2699                if ($entrie['count'] != 1)
2700                {
2701                        $return['status'] = 'false';
2702                        $result['msg'] = $this->functions->lang('Problems loading datas') . '.';
2703                }
2704                else
2705                {
2706                        $tmp_user_context = preg_split('/,/', utf8_decode($entrie[0]['dn']));
2707                        $tmp_reverse_user_context = array_reverse($tmp_user_context);
2708                        array_pop($tmp_reverse_user_context);
2709                        $return['user_context'] = implode(",", array_reverse($tmp_reverse_user_context));
2710                       
2711                        $return['status'] = 'true';
2712                        $return['accountStatus']                = $entrie[0]['accountstatus'][0];
2713                        $return['phpgwAccountVisible']  = $entrie[0]['phpgwaccountvisible'][0];
2714                        $return['cn']                                   = utf8_decode($entrie[0]['cn'][0]);
2715                        $return['mail']                                 = $entrie[0]['mail'][0];
2716                        $return['description']                  = utf8_decode($entrie[0]['description'][0]);
2717
2718                        if ($entrie[0]['mailforwardingaddress']['count'] > 0)
2719                        {
2720                                $a_cn = array();
2721                                for ($i=0; $i<$entrie[0]['mailforwardingaddress']['count']; ++$i)
2722                                {
2723                                        $tmp = $this->mailforwardingaddress2uidnumber($entrie[0]['mailforwardingaddress'][$i]);
2724                                        if (!$tmp) {}
2725                                        else
2726                                                $a_cn[$tmp['uidnumber']] = $tmp['cn'].'('.$tmp['uid'].')';
2727                                }
2728                                natcasesort($a_cn);
2729                                foreach($a_cn as $uidnumber => $cn)
2730                                {
2731                                        $return['owners'] .= '<option value='. $uidnumber .'>' . $cn . '</option>';
2732                                }
2733                        }
2734                }
2735               
2736                return $return;
2737        }
2738        function get_shared_accounts($params)
2739                {
2740                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'list_shared_accounts'))
2741                {
2742                        $return['status'] = false;
2743                        $return['msg'] = $this->functions->lang('You do not have right to list shared accounts') . ".";
2744                        return $return;
2745                }
2746
2747                $input = $params['input'];
2748                $justthese = array("cn", "dn", "mail", "uid");
2749                $trs = array();
2750                               
2751                foreach ($this->manager_contexts as $idx=>$context)
2752                {
2753                $institutional_accounts = ldap_search($this->ldap, $context, ("(&(phpgwAccountType=s)(|(mail=$input*)(cn=*$input*)))"), $justthese);
2754                $entries = ldap_get_entries($this->ldap, $institutional_accounts);
2755               
2756                        for ($i=0; $i<$entries['count']; ++$i)
2757                        {
2758                                $tr = "<tr class='normal' onMouseOver=this.className='selected' onMouseOut=this.className='normal'><td onClick=edit_shared_account('".$entries[$i]['uid'][0]."')>" . utf8_decode($entries[$i]['cn'][0]) . "</td><td onClick=edit_shared_account('".$entries[$i]['uid'][0]."')>" . utf8_decode($entries[$i]['cn'][0]). " (" . $entries[$i]['uid'][0] . ")" . "</td><td onClick=edit_shared_account('".$entries[$i]['uid'][0]."')>" . $entries[$i]['mail'][0] . "<td align='center' onClick=delete_shared_accounts('".$entries[$i]['uid'][0]."','".$entries[$i]['mail'][0]."')><img HEIGHT='16' WIDTH='16' src=./expressoAdmin1_2/templates/default/images/delete.png></td></tr>";
2759                                $trs[$tr] = utf8_decode($entries[$i]['cn'][0]);
2760                        }
2761                }
2762       
2763        $trs_string = '';
2764        if (count($trs))
2765        {
2766                natcasesort($trs);
2767                foreach ($trs as $tr=>$cn)
2768                {
2769                        $trs_string .= $tr;
2770                }
2771        }
2772       
2773        $return['status'] = 'true';
2774        $return['trs'] = $trs_string;
2775        return $return;
2776        }
2777       
2778        function get_shared_account_data($params)
2779        {
2780                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_shared_accounts'))
2781                {
2782                        $return['status'] = false;
2783                        $return['msg'] = $this->functions->lang('You do not have right to edit an shared accounts') . ".";
2784                        return $return;
2785                }
2786               
2787                $uid = $params['uid'];
2788                //$justthese = array("accountStatus", "phpgwAccountVisible", "cn", "mail", "mailForwardingAddress", "description");
2789                               
2790        $shared_accounts = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=s)(uid=$uid))"));
2791        $entrie = ldap_get_entries($this->ldap, $shared_accounts);
2792               
2793                if ($entrie['count'] != 1)
2794                {
2795                        $return['status'] = 'false';
2796                        $result['msg'] = $this->functions->lang('Problems loading datas') . '.';
2797                }
2798                else
2799                {
2800                        $tmp_user_context = preg_split('/,/', $entrie[0]['dn']);
2801                        $tmp_reverse_user_context = array_reverse($tmp_user_context);
2802                        array_pop($tmp_reverse_user_context);
2803                        $return['user_context'] = implode(",", array_reverse($tmp_reverse_user_context));
2804                       
2805                        $return['status'] = 'true';
2806                        $return['accountStatus']                = $entrie[0]['accountstatus'][0];
2807
2808                        $return['phpgwAccountVisible']  = $entrie[0]['phpgwaccountvisible'][0];
2809                        $return['cn']                   = utf8_decode($entrie[0]['cn'][0]);
2810                        $return['mail']                                 = $entrie[0]['mail'][0];
2811                        $return['description']                  = utf8_decode($entrie[0]['description'][0]);
2812                        $return['dn']                   = utf8_decode($entrie[0]['dn']);
2813                        $return['mailalternateaddress'] = $entrie[0]['mailalternateaddress'];
2814                }
2815               
2816
2817               
2818               
2819                return $return;
2820        }               
2821        function mailforwardingaddress2uidnumber($mail)
2822        {
2823                $justthese = array("uidnumber","cn", "uid");
2824        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=u)(mail=$mail))"), $justthese);
2825        $entrie = ldap_get_entries($this->ldap, $search);
2826                if ($entrie['count'] != 1)
2827                        return false;
2828                else
2829                {
2830                        $return['uidnumber'] = $entrie[0]['uidnumber'][0];
2831                        $return['cn'] = utf8_decode($entrie[0]['cn'][0]);
2832                        $return['uid'] = $entrie[0]['uid'][0];
2833                        return $return;
2834                }
2835        }
2836
2837        function uid2mailforwardingaddress($uid)
2838        {
2839                $justthese = array("mail");
2840        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=u)(uid=$uid))"), $justthese);
2841        $entrie = ldap_get_entries($this->ldap, $search);
2842                if ($entrie['count'] != 1)
2843                        return false;
2844                else
2845                {
2846                        $return['mail'] = $entrie[0]['mail'][0];
2847                        return $return;
2848                }
2849        }
2850       
2851        function delete_institutional_account_data($params)
2852        {
2853                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'remove_institutional_accounts'))
2854                {
2855                        $return['status'] = false;
2856                        $return['msg'] = $this->functions->lang('You do not have right to delete institutional accounts') . ".";
2857                        return $return;
2858                }
2859
2860                $uid = $params['uid'];
2861                $return['status'] = true;
2862                               
2863                $justthese = array("cn");
2864        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=i)(uid=$uid))"), $justthese);
2865        $entrie = ldap_get_entries($this->ldap, $search);
2866                if ($entrie['count'] > 1)
2867                {
2868                        $return['status'] = false;
2869                        $return['msg']  = $this->functions->lang('More then one uid was found');
2870                        return $return;
2871                }               
2872                if ($entrie['count'] == 0)
2873                {
2874                        $return['status'] = false;
2875                        $return['msg']  = $this->functions->lang('No uid was found');
2876                        return $return;
2877                }               
2878               
2879                $dn = utf8_decode($entrie[0]['dn']);
2880                if (!@ldap_delete($this->ldap, $dn))
2881                {
2882                        $return['status'] = false;
2883                        $return['msg']  = $this->functions->lang('Error on function') . " ldap_functions->delete_institutional_accounts: ldap_delete";
2884                        $return['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
2885                        return $return;
2886                }
2887
2888        $this->db_functions->write_log('Removed institutional account',$dn);
2889
2890                return $return;
2891        }
2892       
2893        function replace_mail_from_institutional_account($newMail, $oldMail)
2894        {
2895                $filter = "(&(phpgwAccountType=i)(mailforwardingaddress=$oldMail))";
2896                $justthese = array("dn");
2897                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2898                $entries = ldap_get_entries($this->ldap, $search);
2899                $result['status'] = true;
2900                for ($i=0; $i<$entries['count']; ++$i)
2901                {
2902                        $attrs['mailforwardingaddress'] = $oldMail;
2903                        $res1 = @ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs);
2904                        $attrs['mailforwardingaddress'] = $newMail;
2905                        $res2 = @ldap_mod_add($this->ldap, $entries[$i]['dn'], $attrs);
2906               
2907                        if ((!$res1) || (!$res2))
2908                        {
2909                                $result['status'] = false;
2910                                $return['msg']  = $this->functions->lang('Error on function') . " ldap_functions->replace_mail_from_institutional_account.";
2911                        }
2912                }
2913               
2914                return $result;
2915        }
2916        function delete_shared_account_data($params)
2917        {
2918                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'delete_shared_accounts'))
2919                {
2920                        $return['status'] = false;
2921                        $return['msg'] = $this->functions->lang('You do not have right to delete shared accounts') . ".";
2922                        return $return;
2923                }               
2924                $uid = $params['uid'];
2925                $return['status'] = true;
2926
2927                $justthese = array("cn");
2928        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], "(&(phpgwAccountType=s)(uid=$uid))", $justthese);
2929
2930        $entrie = ldap_get_entries($this->ldap, $search);
2931       
2932                if ($entrie['count'] > 1)
2933                {
2934                        $return['status'] = false;
2935                        $return['msg']  = $this->functions->lang('More then one uid was found');
2936                        return $return;
2937                }
2938                if ($entrie['count'] == 0)
2939                {
2940                        $return['status'] = false;
2941                        $return['msg']  = $this->functions->lang('No uid was found');
2942                        return $return;
2943                }
2944
2945                $dn = $entrie[0]['dn'];
2946                if (!@ldap_delete($this->ldap, $dn))
2947                {
2948                        $return['status'] = false;
2949                        $return['msg']  = $this->functions->lang('Error on function') . " ldap_functions->delete_shared_accounts: ldap_delete";
2950                        $return['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
2951                        return $return;
2952                }
2953
2954                return $return;
2955        }               
2956
2957}
2958?>
Note: See TracBrowser for help on using the repository browser.