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

Revision 7673, 102.8 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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