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

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