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

Revision 5593, 102.3 KB checked in by wmerlotto, 12 years ago (diff)

Ticket #2398 - Compatibilizacao com PHP-5.3 no modulo ExpressoAdmin

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