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

Revision 5133, 101.5 KB checked in by wmerlotto, 12 years ago (diff)

Ticket #2305 - Enviando alteracoes, desenvolvidas internamente na Prognus, do modulo ExpressoAdmin.

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