source: sandbox/2.5.1-evolucao/expressoAdmin1_2/inc/class.ldap_functions.inc.php @ 8236

Revision 8236, 104.9 KB checked in by angelo, 11 years ago (diff)

Ticket #3491 - Compatibilizar Expresso com novas versoes do PHP

  • 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               
12if (!defined('PHPGW_INCLUDE_ROOT')) define('PHPGW_INCLUDE_ROOT','../');
13if (!defined('PHPGW_API_INC')) define('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 (isset($params['phpgwAccountVisible']) && $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 ( isset($params['phpgwAccountVisible']) && ($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 = isset($params['mailalternateaddress']) ? $params['mailalternateaddress'] : '';
684                $cpf = $params['cpf'];
685                               
686                if (isset($_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 (isset($this->current_config['expressoAdmin_cpf_obligation']) && $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 (isset($_SESSION['phpgw_info']['expresso']['global_denied_groups'][$cn]) && $_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 (isset($_SESSION['phpgw_info']['expresso']['global_denied_users'][$uid]) && $_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                                $sector_dn = '';
1877                                for($i=1; $i<$sector_dn_array_count; ++$i)
1878                                        $sector_dn .= $sector_dn_array[$i] . ',';
1879                                //Retira ultimo pipe.
1880                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1881               
1882                                $result['context']                              = $sector_dn;
1883                                $result['cn']                                   = $entry[0]['cn'][0];
1884                                $result['description']                  = $entry[0]['description'][0];
1885                                $result['gidnumber']                    = $entry[0]['gidnumber'][0];
1886                                $result['phpgwaccountvisible']  = isset($entry[0]['phpgwaccountvisible']) ? $entry[0]['phpgwaccountvisible'][0] : '';
1887                                $result['email']                                = $entry[0]['mail'][0];
1888               
1889                                //MemberUid
1890                                for ($i=0; $i<$entry[0]['memberuid']['count']; ++$i)
1891                                {
1892                                        $justthese = array("cn","uid","uidnumber");
1893                       
1894                                        // Montagem dinamica do filtro
1895                                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s))(|";
1896                                        for ($k=0; (($k<10) && ($i<$entry[0]['memberuid']['count'])); ++$k)
1897                                        {
1898                                                $filter .= "(uid=".$entry[0]['memberuid'][$i].")";
1899                        ++$i;
1900                                        }
1901                                        $i--;
1902                                        $filter .= "))";
1903                       
1904                                        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
1905                                        $user_entry = ldap_get_entries($this->ldap, $search);
1906
1907                                        for ($j=0; $j<$user_entry['count']; ++$j)
1908                                        {
1909                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['cn'] = $user_entry[$j]['cn'][0];
1910                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['uidnumber'] = $user_entry[$j]['uidnumber'][0];
1911                                                $result['memberuid_info'][$user_entry[$j]['uid'][0]]['type'] = 'u';
1912                                        }
1913                                }
1914               
1915                                // Checamos e-mails que não fazem parte do expresso.
1916                                // Criamos um array temporario
1917                                $tmp_array = array();
1918                                if($result['memberuid_info'])
1919                                        foreach ($result['memberuid_info'] as $uid => $user_data)
1920                                        {
1921                                                $tmp_array[] = $uid;
1922                                        }
1923               
1924                                if($entry[0]['memberuid']) {
1925                                        // Retira o count do array
1926                                        array_shift($entry[0]['memberuid']);
1927                                        // Vemos a diferença
1928                                        $array_diff = array_diff($entry[0]['memberuid'], $tmp_array);
1929                                        // Incluimos no resultado                       
1930                                        foreach ($array_diff as $index=>$uid)
1931                                        {
1932                                                $result['memberuid_info'][$uid]['cn'] = $uid;
1933                                        }
1934                                }
1935               
1936                                // Samba
1937                                for ($i=0; $i<$entry[0]['objectclass']['count']; ++$i)
1938                                {
1939                                        if ($entry[0]['objectclass'][$i] == 'sambaGroupMapping')
1940                                                $result['sambaGroup'] = true;
1941                                        if (isset($entry[0]['sambasid'])){
1942                                                $a_tmp = explode("-",$entry[0]['sambasid'][0]);
1943                                                array_pop($a_tmp);
1944                                                $result['sambasid'] = implode("-", $a_tmp);
1945                                        }
1946                                }
1947                                return $result;
1948                        }
1949                }
1950        }       
1951       
1952        function get_maillist_info($uidnumber)
1953        {
1954                /* folling referral connection */
1955                $ldap_conn_following_ref = ldap_connect($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['host']);
1956                if ($ldap_conn_following_ref)
1957                {
1958                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_PROTOCOL_VERSION, 3);
1959                        ldap_set_option($ldap_conn_following_ref, LDAP_OPT_REFERRALS, 1);
1960
1961                        if ( ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] != '') && ($_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw'] != '') )
1962                                ldap_bind($ldap_conn_following_ref, $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'], $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['pw']);
1963                }
1964               
1965                foreach ($this->manager_contexts as $index=>$context)
1966                {
1967                        $filter="(&(phpgwAccountType=l)(uidNumber=".$uidnumber."))";
1968                        $search = ldap_search($this->ldap, $context, $filter);
1969                        $entry = ldap_get_entries($this->ldap, $search);
1970                       
1971                        if ($entry['count'])
1972                        {
1973                                //Pega o dn do setor do usuario.
1974                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
1975                                $sector_dn_array = explode(",", $entry[0]['dn']);
1976                $sector_dn_array_count = count($sector_dn_array);
1977                                for($i=1; $i<$sector_dn_array_count; ++$i)
1978                                        $sector_dn .= $sector_dn_array[$i] . ',';
1979                                //Retira ultimo pipe.
1980                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
1981                       
1982                                $result['context']                              = $sector_dn;
1983                                $result['uidnumber']                    = $entry[0]['uidnumber'][0];
1984                                $result['uid']                                  = strtolower($entry[0]['uid'][0]);
1985                                $result['cn']                                   = $entry[0]['cn'][0];
1986                                $result['mail']                                 = $entry[0]['mail'][0];
1987                                $result['description']                  = utf8_decode($entry[0]['description'][0]);
1988                                $result['accountStatus']                = $entry[0]['accountstatus'][0];
1989                                $result['phpgwAccountVisible']  = $entry[0]['phpgwaccountvisible'][0];
1990                       
1991                                //Members
1992                                for ($i=0; $i<$entry[0]['mailforwardingaddress']['count']; ++$i)
1993                                {
1994                                        $justthese = array("cn", "uidnumber", "uid", "phpgwaccounttype", "mail");
1995                               
1996                                        // Montagem dinamica do filtro, para nao ter muitas conexoes com o ldap
1997                                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|";
1998                                        for ($k=0; (($k<10) && ($i<$entry[0]['mailforwardingaddress']['count'])); ++$k)
1999                                        {
2000                                                $filter .= "(mail=".$entry[0]['mailforwardingaddress'][$i].")";
2001                        ++$i;
2002                                        }
2003                                        $i--;
2004                                        $filter .= "))";
2005                               
2006                                        $search = ldap_search($ldap_conn_following_ref, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2007                                        $user_entry = ldap_get_entries($ldap_conn_following_ref, $search);
2008                                                                       
2009                                        for ($j=0; $j<$user_entry['count']; ++$j)
2010                                        {
2011                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['uid'] = $user_entry[$j]['uid'][0];
2012                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['cn'] = $user_entry[$j]['cn'][0];
2013                                                $result['mailForwardingAddress_info'][$user_entry[$j]['mail'][0]]['type'] = $user_entry[$j]['phpgwaccounttype'][0];
2014                                                $result['mailForwardingAddress'][] = $user_entry[$j]['mail'][0];
2015                                        }
2016                                }
2017
2018                                // Emails não encontrados no ldap
2019                                array_shift($entry[0]['mailforwardingaddress']); //Retira o count do array
2020                                $missing_emails = array_diff($entry[0]['mailforwardingaddress'], $result['mailForwardingAddress']);
2021                               
2022                                // Incluimos estes no resultado
2023                                foreach ($missing_emails as $index=>$mailforwardingaddress)
2024                                {
2025                                        $result['mailForwardingAddress_info'][$mailforwardingaddress]['uid'] = $mailforwardingaddress;
2026                                        $result['mailForwardingAddress_info'][$mailforwardingaddress]['cn'] = 'E-Mail nao encontrado';
2027                                        $result['mailForwardingAddress'][] = $mailforwardingaddress;
2028                                }
2029                               
2030                                ldap_close($ldap_conn_following_ref);
2031                                return $result;
2032                        }
2033                }
2034        }       
2035
2036        function get_maillist_scl_info($uidnumber)
2037        {
2038                foreach ($this->manager_contexts as $index=>$context)
2039                {
2040                        $filter="(&(phpgwAccountType=l)(uidNumber=$uidnumber))";
2041                        $search = ldap_search($this->ldap, $context, $filter);
2042                        $entry = ldap_get_entries($this->ldap, $search);
2043
2044                        if ($entry['count'])
2045                        {
2046                                //Pega o dn do setor do usuario.
2047                                $entry[0]['dn'] = strtolower($entry[0]['dn']);
2048                                $sector_dn_array = explode(",", $entry[0]['dn']);
2049                $sector_dn_array_count = count($sector_dn_array);
2050                                for($i=1; $i<$sector_dn_array_count; ++$i)
2051                                        $sector_dn .= $sector_dn_array[$i] . ',';
2052                                //Retira ultimo pipe.
2053                                $sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
2054               
2055                                $result['dn']                                           = $entry[0]['dn'];
2056                                $result['context']                                      = $sector_dn;
2057                                $result['uidnumber']                            = $entry[0]['uidnumber'][0];
2058                                $result['uid']                                          = $entry[0]['uid'][0];
2059                                $result['cn']                                           = $entry[0]['cn'][0];
2060                                $result['mail']                                         = $entry[0]['mail'][0];
2061                                $result['accountStatus']                        = $entry[0]['accountstatus'][0];
2062                                $result['phpgwAccountVisible']          = $entry[0]['phpgwaccountvisible'][0];
2063                                $result['accountRestrictive']           = $entry[0]['accountrestrictive'][0];
2064                                $result['participantCanSendMail']       = $entry[0]['participantcansendmail'][0];
2065               
2066                                //Senders
2067                                for ($i=0; $i<$entry[0]['mailsenderaddress']['count']; ++$i)
2068                                {
2069                                        $justthese = array("cn", "uidnumber", "uid", "mail");
2070                                        $filter="(&(phpgwAccountType=u)(mail=".$entry[0]['mailsenderaddress'][$i]."))";
2071                                        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2072                                        $user_entry = ldap_get_entries($this->ldap, $search);
2073                       
2074                                        $result['senders_info'][$user_entry[0]['mail'][0]]['uid'] = $user_entry[0]['uid'][0];
2075                                        $result['senders_info'][$user_entry[0]['mail'][0]]['cn'] = $user_entry[0]['cn'][0];
2076                                        $result['members'][] = $user_entry[0]['mail'][0];
2077                                }
2078                                return $result;
2079                        }
2080                }
2081        }       
2082
2083        function group_exist($gidnumber)
2084        {
2085                $justthese = array("cn");
2086                $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
2087                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2088                               
2089                $entry = ldap_get_entries($this->ldap, $search);
2090                if ($entry['count'] == 0)
2091                        return false;
2092                else
2093                        return true;
2094        }
2095
2096        function gidnumbers2cn($gidnumbers)
2097        {
2098                $result = array();
2099                if (count($gidnumbers))
2100                {
2101                        $justthese = array("cn","uid");
2102                        $i = 0;
2103                        foreach ($gidnumbers as $gidnumber)
2104                        {
2105                                $filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
2106                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2107                               
2108                                $entry = ldap_get_entries($this->ldap, $search);
2109                                if ($entry['count'] == 0)
2110                                        $result['groups_info'][$i]['cn'] = '_' . $this->functions->lang('group only exist on DB, but does not exist on ldap');
2111                                       
2112                                else
2113                                {
2114                                        $result['groups_info'][$i]['uid'] = $entry[0]['uid'][0];
2115                                        $result['groups_info'][$i]['cn'] = $entry[0]['cn'][0];
2116                                }
2117                                $result['groups_info'][$i]['gidnumber'] = $gidnumber;
2118                       
2119                                /* o gerente pode excluir um grupo de um usuario onde este grupo esta em outra OU ? */
2120                                /* é o mesmo que o manager editar um grupo de outra OU */
2121                                $result['groups_info'][$i]['group_disabled'] = 'true';
2122                                foreach ($this->manager_contexts as $index=>$context)
2123                                {
2124                                        if (strpos(strtolower($entry[0]['dn']), strtolower($context)))
2125                                        {
2126                                                $result['groups_info'][$i]['group_disabled'] = 'false';
2127                                        }
2128                                }
2129
2130                ++$i;
2131                        }
2132                }
2133                return $result;
2134        }
2135
2136        function uidnumber2uid($uidnumber)
2137        {
2138                $justthese = array("uid");
2139                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
2140                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2141                $entry = ldap_get_entries($this->ldap, $search);
2142                return $entry[0]['uid'][0];
2143        }
2144       
2145        function uid2cn($uid)
2146        {
2147                $justthese = array("cn");
2148                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=".$uid."))";
2149                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2150                $entry = ldap_get_entries($this->ldap, $search);
2151                return utf8_decode($entry[0]['cn'][0]);
2152        }
2153
2154        function uid2uidnumber($uid)
2155        {
2156                $justthese = array("uidNumber");
2157                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=l))(uid=".$uid."))";
2158                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2159                $entry = ldap_get_entries($this->ldap, $search);
2160                return $entry[0]['uidnumber'][0];
2161        }
2162
2163        function uidnumber2mail($uidnumber)
2164        {
2165                $justthese = array("mail");
2166                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
2167                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2168                $entry = ldap_get_entries($this->ldap, $search);
2169                return $entry[0]['mail'][0];
2170        }
2171
2172        function get_associated_domain($params)
2173        {
2174                        $justthese = array("associatedDomain");
2175                        $filter="(objectClass=domainRelatedObject)";;
2176                        $context = $params['context'];
2177                        $search = ldap_search($this->ldap,$context, $filter, $justthese);
2178                        $entry = ldap_get_entries($this->ldap, $search);
2179                        return ( ($entry['count'] > 0) ? $entry[0]['associateddomain'][0] : $entry);
2180        }
2181       
2182        function change_user_context($dn, $newrdn, $newparent)
2183        {
2184                if (!ldap_rename ( $this->ldap, $dn, $newrdn, $newparent, true ))
2185                {
2186                        $return['status'] = false;
2187                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->change_user_context ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2188                }
2189                else
2190                        $return['status'] = true;
2191               
2192                return $return;
2193        }
2194       
2195        function replace_user_attributes($dn, $ldap_mod_replace)
2196        {
2197                if (!@ldap_mod_replace ( $this->ldap, $dn, $ldap_mod_replace ))
2198                {
2199                        $return['status'] = false;
2200                        $return['error_number'] = ldap_errno($this->ldap);
2201                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->replace_user_attributes ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2202                }
2203                else
2204                        $return['status'] = true;
2205               
2206                return $return;
2207        }
2208       
2209        function add_user_attributes($dn, $ldap_add)
2210        {
2211                if (!@ldap_mod_add ( $this->ldap, $dn, $ldap_add ))
2212                {
2213                        $return['status'] = false;
2214                        $return['error_number'] = ldap_errno($this->ldap);
2215                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->add_user_attributes ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2216                }
2217                else
2218                        $return['status'] = true;
2219               
2220                return $return;
2221        }
2222       
2223        function remove_user_attributes($dn, $ldap_remove)
2224        {
2225                if (!@ldap_mod_del ( $this->ldap, $dn, $ldap_remove ))
2226                {
2227                        $return['status'] = false;
2228                        $return['msg'] = $this->functions->lang('Error on function') . " ldap_functions->remove_user_attributes ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2229                }
2230                else
2231                        $return['status'] = true;
2232               
2233                return $return;
2234        }
2235       
2236        function set_user_password($uid, $password)
2237        {
2238                $justthese = array("userPassword");
2239                $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
2240                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2241            $entry = ldap_get_entries($this->ldap, $search);
2242                $dn = $entry[0]['dn'];
2243                $userPassword = $entry[0]['userpassword'][0];
2244                $ldap_mod_replace['userPassword'] = $password;
2245                $this->replace_user_attributes($dn, $ldap_mod_replace);
2246                return $userPassword;
2247        }
2248       
2249        function delete_user($user_info)
2250        {
2251                // Verifica acesso do gerente (OU) ao tentar deletar um usuário.
2252                $manager_access = false;
2253                foreach ($this->manager_contexts as $index=>$context)
2254                {
2255                        if ( (strpos(strtolower($user_info['context']), strtolower($context))) || (strtolower($user_info['context']) == strtolower($context)) )
2256                        {
2257                                $manager_access = true;
2258                                break;
2259                        }
2260                }
2261                if (!$manager_access)
2262                {
2263                        $return['status'] = false;
2264                        $result['msg'] = $this->functions->lang('You do not have access to delete this user') . ".";
2265                        return $return;
2266                }
2267               
2268                $return['status'] = true;
2269                $return['msg'] = "";
2270                               
2271                // GROUPS
2272                $attrs = array();
2273                $attrs['memberuid'] = $user_info['uid'];
2274               
2275                if (count($user_info['groups_info']))
2276                {
2277                        foreach ($user_info['groups_info'] as $group_info)
2278                        {
2279                                $gidnumber = $group_info['gidnumber'];
2280                                $justthese = array("dn");
2281                                $filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
2282                                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2283                        $entry = ldap_get_entries($this->ldap, $search);
2284                                $dn = $entry[0]['dn'];
2285
2286                                if (!@ldap_mod_del($this->ldap, $dn, $attrs))
2287                                {
2288                                        $return['status'] = false;
2289                                        $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);
2290                                }
2291                        }
2292                }
2293               
2294                //INSTITUTIONAL ACCOUNTS
2295                $attrs = array();
2296                $attrs['mailForwardingAddress'] = $user_info['mail'];
2297               
2298                $justthese = array("dn");
2299                $filter="(&(phpgwAccountType=i)(mailforwardingaddress=".$user_info['mail']."))";
2300                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2301            $entries = ldap_get_entries($this->ldap, $search);
2302               
2303                for ($i=0; $i<$entries['count']; ++$i)
2304                {
2305                        if ( !@ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs) )
2306                        {
2307                                $result['status'] = false;
2308                                $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);
2309                        }
2310                }
2311               
2312                // MAILLISTS
2313                $attrs = array();
2314                $attrs['mailForwardingAddress'] = $user_info['mail'];
2315               
2316                if (count($user_info['maillists_info']))
2317                {
2318                       
2319                        if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
2320                        {
2321                                $return['status'] = false;
2322                                $result['msg'] = $this->functions->lang('Connection with ldap_master fail') . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2323                                return $return;
2324                        }
2325                       
2326                        foreach ($user_info['maillists_info'] as $maillists_info)
2327                        {
2328                                $uid = $maillists_info['uid'];
2329                                $justthese = array("dn");
2330                                $filter="(&(phpgwAccountType=l)(uid=".$uid."))";
2331                                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2332                        $entry = ldap_get_entries($ldapMasterConnect, $search);
2333                                $dn = $entry[0]['dn'];
2334                       
2335                                if (!@ldap_mod_del($ldapMasterConnect, $dn, $attrs))
2336                                {
2337                                        $return['status'] = false;
2338                                        if (ldap_errno($ldapMasterConnect) == '50')
2339                                        {
2340                                                $result['msg'] =        $this->functions->lang('Error on the function') . ' ldap_functions->add_user2maillist' . ".\n" .
2341                                                                                        $this->functions->lang('The user used for record on LPDA, must have write access') . ".\n";
2342                                                                                        $this->functions->lang('The user') . ' ' . $_SESSION['phpgw_info']['expresso']['cc_ldap_server']['acc'] . ' ' . $this->functions->lang('does not have this access') . ".\n";
2343                                                                                        $this->functions->lang('Edit Global Catalog Config, in the admin module, and add an user with write access') . ".\n";
2344                                        }
2345                                        else
2346                                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_user, email lists ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
2347                                }
2348                        }
2349                        ldap_close($ldapMasterConnect);
2350                }
2351                       
2352                // UID
2353                $dn = "uid=" . $user_info['uid'] . "," . $user_info['context'];
2354                if (!@ldap_delete($this->ldap, $dn))
2355                {
2356                        $return['status'] = false;
2357                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_user, email lists ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($ldapMasterConnect);
2358                }
2359                /* jakjr */
2360                return $return;
2361        }
2362       
2363        function delete_maillist($uidnumber, $mail)
2364        {
2365                $return['status'] = true;
2366               
2367                $justthese = array("dn");
2368               
2369                // remove listas dentro de listas
2370                $filter="(&(phpgwAccountType=l)(mailForwardingAddress=".$mail."))";
2371                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2372                $entry = ldap_get_entries($this->ldap, $search);
2373                $attrs['mailForwardingAddress'] = $mail;
2374                for ($i=0; $i<=$entry['count']; ++$i)
2375            {
2376                        $dn = $entry[$i]['dn'];
2377                @ldap_mod_del ( $this->ldap, $dn,  $attrs);
2378            }
2379               
2380                $filter="(&(phpgwAccountType=l)(uidnumber=".$uidnumber."))";
2381                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2382                $entry = ldap_get_entries($this->ldap, $search);
2383                $dn = $entry[0]['dn'];
2384               
2385                if (!@ldap_delete($this->ldap, $dn))
2386                {
2387                        $return['status'] = false;
2388                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_maillist ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2389                }
2390               
2391                return $return;
2392        }
2393
2394        function delete_group($gidnumber)
2395        {
2396                $return['status'] = true;
2397               
2398                $justthese = array("dn");
2399                $filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
2400                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2401                $entry = ldap_get_entries($this->ldap, $search);
2402                $dn = $entry[0]['dn'];
2403               
2404                if (!@ldap_delete($this->ldap, $dn))
2405                {
2406                        $return['status'] = false;
2407                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_group ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2408                }
2409               
2410                return $return;
2411        }
2412
2413        function check_access_to_renamed($uid)
2414        {
2415                $justthese = array("dn");
2416                $filter="(&(phpgwAccountType=u)(uid=$uid))";
2417               
2418                foreach ($this->manager_contexts as $index=>$context)
2419                {
2420                        $search = ldap_search($this->ldap, $context, $filter, $justthese);
2421                        $entry = ldap_get_entries($this->ldap, $search);
2422                        if ($entry['count'])
2423                                return true;
2424                }
2425            return false;
2426        }
2427
2428        function check_rename_new_uid($uid)
2429        {
2430                if ( !$ldapMasterConnect = $this->ldapMasterConnect() )
2431                        return false;
2432               
2433                $justthese = array("dn");
2434                $filter="(&(phpgwAccountType=u)(uid=$uid))";
2435               
2436                $search = ldap_search($ldapMasterConnect, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2437                $count_entries = @ldap_count_entries($ldapMasterConnect, $search);
2438               
2439                if ($count_entries)
2440                        return false;
2441                       
2442                return true;
2443        }
2444       
2445        function rename_uid($uid, $new_uid)
2446        {
2447                $return['status'] = true;
2448               
2449                $justthese = array("dn");
2450                $filter="(&(phpgwAccountType=u)(uid=".$uid."))";
2451                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2452            $entry = ldap_get_entries($this->ldap, $search);
2453                $dn = $entry[0]['dn'];
2454               
2455                $explode_dn = ldap_explode_dn($dn, 0);
2456                $rdn = "uid=" . $new_uid;
2457
2458                $parent = array();
2459                for ($j=1; $j<(count($explode_dn)-1); ++$j)
2460                        $parent[] = $explode_dn[$j];
2461                $parent = implode(",", $parent);
2462               
2463                $return['new_dn'] = $rdn . ',' . $parent;
2464                       
2465                if (!@ldap_rename($this->ldap, $dn, $rdn, $parent, true))
2466                {
2467                        $return['status'] = false;
2468                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->rename_uid ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2469                }
2470               
2471                //Grupos
2472                $justthese = array("dn");
2473                $filter="(&(phpgwAccountType=g)(memberuid=".$uid."))";
2474                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2475            $entry = ldap_get_entries($this->ldap, $search);
2476        $array_mod_add['memberUid'] = $new_uid;
2477        $array_mod_del['memberUid'] = $uid;
2478
2479            for ($i=0; $i<=$entry['count']; ++$i)
2480            {
2481                $dn = $entry[$i]['dn'];
2482                @ldap_mod_add ( $this->ldap, $dn,  $array_mod_add);
2483                @ldap_mod_del ( $this->ldap, $dn,  $array_mod_del);
2484            }
2485                return $return;
2486        }
2487
2488        function rename_cn($cn, $new_cn)
2489        {
2490                $return['status'] = true;
2491               
2492                $justthese = array("dn");
2493                $filter="(&(phpgwAccountType=g)(uid=".$cn."))";
2494                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2495            $entry = ldap_get_entries($this->ldap, $search);
2496                $dn = $entry[0]['dn'];
2497               
2498                $explode_dn = ldap_explode_dn($dn, 0);
2499                $rdn = "cn=" . $new_cn;
2500
2501                $parent = array();
2502                for ($j=1; $j<(count($explode_dn)-1); ++$j)
2503                        $parent[] = $explode_dn[$j];
2504                $parent = implode(",", $parent);
2505               
2506                $return['new_dn'] = $rdn . ',' . $parent;
2507                       
2508                if (!@ldap_rename($this->ldap, $dn, $rdn, $parent, false))
2509                {
2510                        $return['status'] = false;
2511                }
2512               
2513                return $return;
2514        }
2515       
2516        function exist_sambadomains($contexts, $sambaDomainName)
2517        {
2518                $justthese = array("dn");
2519                $filter="(&(objectClass=sambaDomain)(sambaDomainName=$sambaDomainName))";
2520               
2521                foreach ($contexts as $index=>$context)
2522                {
2523                        $search = ldap_search($this->ldap, $context, $filter, $justthese);
2524                    $entry = ldap_get_entries($this->ldap, $search);
2525           
2526                        if ($entry['count'])
2527                                return true;
2528                }
2529                return false;
2530        }
2531       
2532        // Primeiro nilvel de organização.
2533        function exist_sambadomains_in_context($params)
2534        {
2535                $dn = $GLOBALS['phpgw_info']['server']['ldap_context'];
2536                $array_dn = ldap_explode_dn ( $dn, 0 );
2537               
2538                $context = $params['context'];
2539                $array_context = ldap_explode_dn ( $context, 0 );
2540               
2541                // Pego o setor no caso do contexto ser um sub-setor.
2542                if (($array_dn['count']+1) < ($array_context['count']))
2543                {
2544                        // inverto o array_dn para poder retirar o count
2545                        $array_dn_reverse  = array_reverse ( $array_dn, false );
2546                       
2547                        //retiro o count
2548                        array_pop($array_dn_reverse);
2549                       
2550                        //incluo o setor no dn
2551                        array_push ( $array_dn_reverse,  $array_context[ $array_context['count'] - 1 - $array_dn['count']]);
2552                       
2553                        // Volto a ordem natural
2554                        $array_dn  = array_reverse ( $array_dn_reverse, false );
2555                       
2556                        // Implodo
2557                        $context = implode ( ",", $array_dn );
2558                }
2559               
2560                $justthese = array("dn","sambaDomainName");
2561                $filter="(objectClass=sambaDomain)";
2562                $search = ldap_list($this->ldap, $context, $filter, $justthese);
2563            $entry = ldap_get_entries($this->ldap, $search);
2564           
2565            for ($i=0; $i<$entry['count']; ++$i)
2566            {
2567                        $return['sambaDomains'][$i] = $entry[$i]['sambadomainname'][0];
2568            }
2569           
2570                if ($entry['count'])
2571                        $return['status'] = true;
2572                else
2573                        $return['status'] = false;
2574                       
2575                return $return;
2576        }
2577        function exist_domain_name_sid($sambadomainname, $sambasid)
2578        {
2579                $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
2580
2581                $justthese = array("dn","sambaDomainName");
2582                $filter="(&(objectClass=sambaDomain)(sambaSID=$sambasid)(sambaDomainName=$sambadomainname))";
2583                $search = ldap_search($this->ldap, $context, $filter, $justthese);
2584            $count_entries = ldap_count_entries($this->ldap, $search);
2585               
2586            if ($count_entries > 0)
2587                return true;
2588            else
2589                return false;
2590                }
2591               
2592        function add_sambadomain($sambadomainname, $sambasid, $context)
2593        {
2594                $result = array();
2595               
2596                $dn                                                             = "sambaDomainName=$sambadomainname,$context";
2597                $entry['sambaSID']                                      = $sambasid;
2598                $entry['objectClass']                           = 'sambaDomain';
2599                $entry['sambaAlgorithmicRidBase']       = '1000';
2600                $entry['sambaDomainName']                       = $sambadomainname;
2601               
2602                if (!@ldap_add ( $this->ldap, $dn, $entry ))
2603                        {
2604                        $return['status'] = false;
2605                        $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->add_sambadomain ($dn)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2606                }
2607                else
2608                        $return['status'] = true;
2609               
2610                return $return;
2611        }
2612               
2613        function delete_sambadomain($sambadomainname)
2614        {
2615                $return['status'] = true;
2616                $filter="(sambaDomainName=$sambadomainname)";
2617                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter);
2618            $entry = ldap_get_entries($this->ldap, $search);
2619               
2620                if ($entry['count'] != 0)
2621                {
2622                        $dn = $entry[0]['dn'];
2623                       
2624                        if (!@ldap_delete($this->ldap, $dn))
2625                        {
2626                                $return['status'] = false;
2627                                $result['msg'] = $this->functions->lang('Error on function') . " ldap_functions->delete_sambadomain ($sambadomainname)" . ".\n" . $this->functions->lang('Server returns') . ': ' . ldap_error($this->ldap);
2628                        }
2629                }
2630               
2631                return $return;
2632        }
2633       
2634        function search_user($params)
2635                {
2636             $ldapService = ServiceLocator::getService('ldap');
2637             $entries = $ldapService->accountSearch($params['search'], array('cn','uid', "mail"), $params['context'], 'u', 'cn');
2638
2639             if (count($entries) == 0)
2640             {
2641                    $return['status'] = 'false';
2642                    $return['msg'] = $this->functions->lang('Any result was found') . '.';
2643                    return $return;
2644                }
2645             $options = '';
2646
2647             foreach ($entries as  $value)
2648                 $options .= '<option value='.$value['uid'].'>'.$value['cn'].'('.$value['mail'].')'.'</option>';
2649   
2650        return $options;               
2651        }
2652       
2653        function get_institutional_accounts($params)
2654        {
2655                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'list_institutional_accounts'))
2656                {
2657                        $return['status'] = false;
2658                        $return['msg'] = $this->functions->lang('You do not have right to list institutional accounts') . ".";
2659                        return $return;
2660                }
2661
2662                $input = $params['input'];
2663                $justthese = array("cn", "mail", "uid");
2664                $trs = array();
2665                               
2666                foreach ($this->manager_contexts as $idx=>$context)
2667                {
2668                $institutional_accounts = ldap_search($this->ldap, $context, ("(&(phpgwAccountType=i)(|(mail=$input*)(cn=*$input*)))"), $justthese);
2669                $entries = ldap_get_entries($this->ldap, $institutional_accounts);
2670               
2671                        for ($i=0; $i<$entries['count']; ++$i)
2672                        {
2673                                $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>";
2674                                $trs[$tr] = utf8_decode($entries[$i]['cn'][0]);
2675                        }
2676                }
2677       
2678        $trs_string = '';
2679        if (count($trs))
2680        {
2681                natcasesort($trs);
2682                foreach ($trs as $tr=>$cn)
2683                {
2684                        $trs_string .= $tr;
2685                }
2686        }
2687       
2688        $return['status'] = 'true';
2689        $return['trs'] = $trs_string;
2690        return $return;
2691}       
2692       
2693        function get_institutional_account_data($params)
2694        {
2695                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_institutional_accounts'))
2696                {
2697                        $return['status'] = false;
2698                        $return['msg'] = $this->functions->lang('You do not have right to edit institutional accounts') . ".";
2699                        return $return;
2700                }
2701               
2702                $uid = $params['uid'];
2703                //$justthese = array("accountStatus", "phpgwAccountVisible", "cn", "mail", "mailForwardingAddress", "description");
2704                               
2705        $institutional_accounts = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=i)(uid=$uid))"));
2706        $entrie = ldap_get_entries($this->ldap, $institutional_accounts);
2707               
2708                if ($entrie['count'] != 1)
2709                {
2710                        $return['status'] = 'false';
2711                        $result['msg'] = $this->functions->lang('Problems loading datas') . '.';
2712                }
2713                else
2714                {
2715                        $tmp_user_context = preg_split('/,/', utf8_decode($entrie[0]['dn']));
2716                        $tmp_reverse_user_context = array_reverse($tmp_user_context);
2717                        array_pop($tmp_reverse_user_context);
2718                        $return['user_context'] = implode(",", array_reverse($tmp_reverse_user_context));
2719                       
2720                        $return['status'] = 'true';
2721                        $return['accountStatus']                = $entrie[0]['accountstatus'][0];
2722                        $return['phpgwAccountVisible']  = isset($entrie[0]['phpgwaccountvisible']) ? $entrie[0]['phpgwaccountvisible'][0] : '';
2723                        $return['cn']                                   = utf8_decode($entrie[0]['cn'][0]);
2724                        $return['mail']                                 = $entrie[0]['mail'][0];
2725                        $return['description']                  = utf8_decode($entrie[0]['description'][0]);
2726
2727                        if ($entrie[0]['mailforwardingaddress']['count'] > 0)
2728                        {
2729                                $a_cn = array();
2730                                for ($i=0; $i<$entrie[0]['mailforwardingaddress']['count']; ++$i)
2731                                {
2732                                        $tmp = $this->mailforwardingaddress2uidnumber($entrie[0]['mailforwardingaddress'][$i]);
2733                                        if (!$tmp) {}
2734                                        else
2735                                                $a_cn[$tmp['uidnumber']] = $tmp['cn'].'('.$tmp['uid'].')';
2736                                }
2737                                natcasesort($a_cn);
2738                                $return['owners'] = '';
2739                                foreach($a_cn as $uidnumber => $cn)
2740                                {
2741                                        $return['owners'] .= '<option value='. $uidnumber .'>' . $cn . '</option>';
2742                                }
2743                        }
2744                }
2745               
2746                return $return;
2747        }
2748        function get_shared_accounts($params)
2749                {
2750                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'list_shared_accounts'))
2751                {
2752                        $return['status'] = false;
2753                        $return['msg'] = $this->functions->lang('You do not have right to list shared accounts') . ".";
2754                        return $return;
2755                }
2756
2757                $input = $params['input'];
2758                $justthese = array("cn", "dn", "mail", "uid");
2759                $trs = array();
2760                               
2761                foreach ($this->manager_contexts as $idx=>$context)
2762                {
2763                $institutional_accounts = ldap_search($this->ldap, $context, ("(&(phpgwAccountType=s)(|(mail=$input*)(cn=*$input*)))"), $justthese);
2764                $entries = ldap_get_entries($this->ldap, $institutional_accounts);
2765               
2766                        for ($i=0; $i<$entries['count']; ++$i)
2767                        {
2768                                $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>";
2769                                $trs[$tr] = utf8_decode($entries[$i]['cn'][0]);
2770                        }
2771                }
2772       
2773        $trs_string = '';
2774        if (count($trs))
2775        {
2776                natcasesort($trs);
2777                foreach ($trs as $tr=>$cn)
2778                {
2779                        $trs_string .= $tr;
2780                }
2781        }
2782       
2783        $return['status'] = 'true';
2784        $return['trs'] = $trs_string;
2785        return $return;
2786        }
2787       
2788        function get_shared_account_data($params)
2789        {
2790                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_shared_accounts'))
2791                {
2792                        $return['status'] = false;
2793                        $return['msg'] = $this->functions->lang('You do not have right to edit an shared accounts') . ".";
2794                        return $return;
2795                }
2796               
2797                $uid = $params['uid'];
2798                //$justthese = array("accountStatus", "phpgwAccountVisible", "cn", "mail", "mailForwardingAddress", "description");
2799                               
2800        $shared_accounts = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=s)(uid=$uid))"));
2801        $entrie = ldap_get_entries($this->ldap, $shared_accounts);
2802               
2803                if ($entrie['count'] != 1)
2804                {
2805                        $return['status'] = 'false';
2806                        $result['msg'] = $this->functions->lang('Problems loading datas') . '.';
2807                }
2808                else
2809                {
2810                        $tmp_user_context = preg_split('/,/', $entrie[0]['dn']);
2811                        $tmp_reverse_user_context = array_reverse($tmp_user_context);
2812                        array_pop($tmp_reverse_user_context);
2813                        $return['user_context'] = implode(",", array_reverse($tmp_reverse_user_context));
2814                       
2815                        $return['status'] = 'true';
2816                        $return['accountStatus']                = $entrie[0]['accountstatus'][0];
2817
2818                        $return['phpgwAccountVisible']  = $entrie[0]['phpgwaccountvisible'][0];
2819                        $return['cn']                   = utf8_decode($entrie[0]['cn'][0]);
2820                        $return['mail']                                 = $entrie[0]['mail'][0];
2821                        $return['description']                  = utf8_decode($entrie[0]['description'][0]);
2822                        $return['dn']                   = utf8_decode($entrie[0]['dn']);
2823                        $return['mailalternateaddress'] = $entrie[0]['mailalternateaddress'];
2824                }
2825               
2826
2827               
2828               
2829                return $return;
2830        }               
2831        function mailforwardingaddress2uidnumber($mail)
2832        {
2833                $justthese = array("uidnumber","cn", "uid");
2834        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=u)(mail=$mail))"), $justthese);
2835        $entrie = ldap_get_entries($this->ldap, $search);
2836                if ($entrie['count'] != 1)
2837                        return false;
2838                else
2839                {
2840                        $return['uidnumber'] = $entrie[0]['uidnumber'][0];
2841                        $return['cn'] = utf8_decode($entrie[0]['cn'][0]);
2842                        $return['uid'] = $entrie[0]['uid'][0];
2843                        return $return;
2844                }
2845        }
2846
2847        function uid2mailforwardingaddress($uid)
2848        {
2849                $justthese = array("mail");
2850        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=u)(uid=$uid))"), $justthese);
2851        $entrie = ldap_get_entries($this->ldap, $search);
2852                if ($entrie['count'] != 1)
2853                        return false;
2854                else
2855                {
2856                        $return['mail'] = $entrie[0]['mail'][0];
2857                        return $return;
2858                }
2859        }
2860       
2861        function delete_institutional_account_data($params)
2862        {
2863                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'remove_institutional_accounts'))
2864                {
2865                        $return['status'] = false;
2866                        $return['msg'] = $this->functions->lang('You do not have right to delete institutional accounts') . ".";
2867                        return $return;
2868                }
2869
2870                $uid = $params['uid'];
2871                $return['status'] = true;
2872                               
2873                $justthese = array("cn");
2874        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], ("(&(phpgwAccountType=i)(uid=$uid))"), $justthese);
2875        $entrie = ldap_get_entries($this->ldap, $search);
2876                if ($entrie['count'] > 1)
2877                {
2878                        $return['status'] = false;
2879                        $return['msg']  = $this->functions->lang('More then one uid was found');
2880                        return $return;
2881                }               
2882                if ($entrie['count'] == 0)
2883                {
2884                        $return['status'] = false;
2885                        $return['msg']  = $this->functions->lang('No uid was found');
2886                        return $return;
2887                }               
2888               
2889                $dn = utf8_decode($entrie[0]['dn']);
2890                if (!@ldap_delete($this->ldap, $dn))
2891                {
2892                        $return['status'] = false;
2893                        $return['msg']  = $this->functions->lang('Error on function') . " ldap_functions->delete_institutional_accounts: ldap_delete";
2894                        $return['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
2895                        return $return;
2896                }
2897
2898        $this->db_functions->write_log('Removed institutional account',$dn);
2899
2900                return $return;
2901        }
2902       
2903        function replace_mail_from_institutional_account($newMail, $oldMail)
2904        {
2905                $filter = "(&(phpgwAccountType=i)(mailforwardingaddress=$oldMail))";
2906                $justthese = array("dn");
2907                $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
2908                $entries = ldap_get_entries($this->ldap, $search);
2909                $result['status'] = true;
2910                for ($i=0; $i<$entries['count']; ++$i)
2911                {
2912                        $attrs['mailforwardingaddress'] = $oldMail;
2913                        $res1 = @ldap_mod_del($this->ldap, $entries[$i]['dn'], $attrs);
2914                        $attrs['mailforwardingaddress'] = $newMail;
2915                        $res2 = @ldap_mod_add($this->ldap, $entries[$i]['dn'], $attrs);
2916               
2917                        if ((!$res1) || (!$res2))
2918                        {
2919                                $result['status'] = false;
2920                                $return['msg']  = $this->functions->lang('Error on function') . " ldap_functions->replace_mail_from_institutional_account.";
2921                        }
2922                }
2923               
2924                return $result;
2925        }
2926        function delete_shared_account_data($params)
2927        {
2928                if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'delete_shared_accounts'))
2929                {
2930                        $return['status'] = false;
2931                        $return['msg'] = $this->functions->lang('You do not have right to delete shared accounts') . ".";
2932                        return $return;
2933                }               
2934                $uid = $params['uid'];
2935                $return['status'] = true;
2936
2937                $justthese = array("cn");
2938        $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], "(&(phpgwAccountType=s)(uid=$uid))", $justthese);
2939
2940        $entrie = ldap_get_entries($this->ldap, $search);
2941       
2942                if ($entrie['count'] > 1)
2943                {
2944                        $return['status'] = false;
2945                        $return['msg']  = $this->functions->lang('More then one uid was found');
2946                        return $return;
2947                }
2948                if ($entrie['count'] == 0)
2949                {
2950                        $return['status'] = false;
2951                        $return['msg']  = $this->functions->lang('No uid was found');
2952                        return $return;
2953                }
2954
2955                $dn = $entrie[0]['dn'];
2956                if (!@ldap_delete($this->ldap, $dn))
2957                {
2958                        $return['status'] = false;
2959                        $return['msg']  = $this->functions->lang('Error on function') . " ldap_functions->delete_shared_accounts: ldap_delete";
2960                        $return['msg'] .= "\n" . $this->functions->lang('Server return') . ': ' . ldap_error($this->ldap);
2961                        return $return;
2962                }
2963
2964                return $return;
2965        }               
2966
2967}
2968?>
Note: See TracBrowser for help on using the repository browser.