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

Revision 8197, 104.3 KB checked in by angelo, 11 years ago (diff)

Ticket #3476 - Validacao dos campos ao criar contas institucionais

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