source: branches/2.2/reports1_0/inc/class.functions.inc.php @ 3530

Revision 3530, 51.8 KB checked in by brunocosta, 13 years ago (diff)

Ticket #1325 - Adapta buscas LDAP para casos que não existem OUs.

Line 
1<?php
2        /**********************************************************************************\
3        *Expresso Relatório                                                                                           *
4        *by Elvio Rufino da Silva (elviosilva@yahoo.com.br, elviosilva@cepromat.mt.gov.br) *
5        * --------------------------------------------------------------------------------*
6        *  This program is free software; you can redistribute it and/or modify it                *
7        *  under the terms of the GNU General Public License as published by the                  *
8        *  Free Software Foundation; either version 2 of the License, or (at your                 *
9        *  option) any later version.                                                                                                    *
10        **********************************************************************************/
11       
12        include_once('class.db_functions.inc.php');
13        include_once(PHPGW_API_INC.'/class.config.inc.php');
14
15        class functions
16        {
17                var $public_functions = array
18                (
19                        'make_array_acl'                        => True,
20                        'check_acl'                                     => True,
21                        'read_acl'                                      => True,
22                        'exist_account_lid'                     => True,
23                        'exist_email'                           => True,
24                        'array_invert'                          => True,
25                        'Paginate_user'                         => True,
26                        'Paginate_user_logon'           => True,
27                        'get_list_all'                          => True,
28                        'get_groups_list'                       => True,
29                        'get_list_ou_user_logon'        => True,
30                        'show_access_log'                       => True,
31                        'get_sectors_list'                      => True
32                );
33               
34                var $nextmatchs;
35                var $sectors_list = array();
36                var $current_config;
37               
38                function functions()
39                {
40                        $this->db_functions = new db_functions;
41                        $GLOBALS['phpgw']->db = $this->db_functions->db;
42
43                        $c = new config;
44                        $c->read_repository();
45                        $this->current_config = $c->config_data;
46                }
47
48                // Account and type of access. Return: Have access ? (true/false)
49                function check_acl($account_lid, $access)
50                {
51                        $acl = $this->read_acl($account_lid);
52                        $array_acl = $this->make_array_acl($acl['acl']);
53                       
54                        switch($access)
55                        {
56                                case list_users:
57                                        if ($array_acl[acl_add_users] || $array_acl[acl_edit_users] || $array_acl[acl_delete_users] || $array_acl[acl_change_users_password] || $array_acl[acl_change_users_quote] || $array_acl[acl_edit_sambausers_attributes] || $array_acl[acl_view_users] || $array_acl[acl_manipulate_corporative_information] || $array_acl[acl_edit_users_phonenumber] )
58                                                return true;
59                                        break;
60                                case report_users:
61                                        if ($array_acl[acl_change_users_quote] || $array_acl[acl_view_users])
62                                                return true;
63                                        break;
64                                case list_groups:
65                                        if ($array_acl[acl_add_groups] || $array_acl[acl_edit_groups] || $array_acl[acl_delete_groups])
66                                                return true;
67                                        break;
68                                case list_maillists:
69                                        if ($array_acl[acl_add_maillists] || $array_acl[acl_edit_maillists] || $array_acl[acl_delete_maillists])
70                                                return true;
71                                        break;
72                                case list_sectors:
73//                                      if ($array_acl[acl_create_sectors] || $array_acl[acl_edit_sectors] || $array_acl[acl_delete_sectors])
74                                        if ($array_acl[acl_view_users])
75                                                return true;
76                                        break;
77                                case list_computers:
78                                        if ($array_acl[acl_create_computers] || $array_acl[acl_edit_computers] || $array_acl[acl_delete_computers])
79                                                return true;
80                                        break;
81
82                                case display_groups:
83                                        if ( $array_acl[acl_edit_users] || $array_acl[acl_view_users] || ($array_acl[acl_edit_sambausers_attributes] && ($this->current_config['expressoAdmin_samba_support'] == 'true')) )
84                                                return true;
85                                        break;
86                                case display_emailconfig:
87                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
88                                                return true;
89                                        break;
90                                case display_applications:
91                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
92                                                return true;
93                                        break;
94                                case display_emaillists:
95                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
96                                                return true;
97                                        break;
98
99                                case list_institutional_accounts:
100                                        if ($array_acl[acl_add_institutional_accounts] || $array_acl[acl_edit_institutional_accounts] || $array_acl[acl_delete_institutional_accounts])
101                                                return true;
102                                        break;
103
104
105                                default:
106                                        return $array_acl["acl_$access"];
107                        }
108                        return false;
109                }
110
111               
112                // Read acl from db
113                function read_acl($account_lid)
114                {
115                        $acl = $this->db_functions->read_acl($account_lid);
116                       
117                        $result['acl'] = $acl[0]['acl'];
118                        $result['manager_lid'] = $acl[0]['manager_lid'];
119                        $result['raw_context'] = $acl[0]['context'];
120                       
121                        $all_contexts = split("%", $acl[0]['context']);
122                        foreach ($all_contexts as $index=>$context)
123                        {
124                                $result['contexts'][] = $context;
125                                $result['contexts_display'][] = str_replace(", ", ".", ldap_dn2ufn( $context ));
126                        }
127                       
128                        return $result;
129                }
130               
131                function make_array_acl($acl)
132                {
133                        $array_acl_tmp = array();
134                        $tmp = array(           "acl_add_users",
135                                                                "acl_edit_users",
136                                                                "acl_delete_users",
137                                                                "acl_EMPTY1",
138                                                                "acl_add_groups",
139                                                                "acl_edit_groups",
140                                                                "acl_delete_groups",
141                                                                "acl_change_users_password",
142                                                                "acl_add_maillists",
143                                                                "acl_edit_maillists",
144                                                                "acl_delete_maillists",
145                                                                "acl_EMPTY2",
146                                                                "acl_create_sectors",
147                                                                "acl_edit_sectors",
148                                                                "acl_delete_sectors",
149                                                                "acl_edit_sambausers_attributes",
150                                                                "acl_view_global_sessions",
151                                                                "acl_view_logs",
152                                                                "acl_change_users_quote",
153                                                                "acl_set_user_default_password",
154                                                                "acl_create_computers",
155                                                                "acl_edit_computers",
156                                                                "acl_delete_computers",
157                                                                "acl_rename_users",
158                                                                "acl_edit_sambadomains",
159                                                                "acl_view_users",
160                                                                "acl_edit_email_groups",
161                                                                "acl_empty_user_inbox",
162                                                                "acl_manipulate_corporative_information",
163                                                                "acl_edit_users_picture",
164                                                                "acl_edit_scl_email_lists",
165                                                                "acl_edit_users_phonenumber",
166                                                                "acl_add_institutional_accounts",
167                                                                "acl_edit_institutional_accounts",
168                                                                "acl_remove_institutional_accounts"
169                                                                );
170                       
171                        foreach ($tmp as $index => $right)
172                        {
173                                $bin = '';
174                                for ($i=0; $i<$index; $i++)
175                                {
176                                        $bin .= '0';
177                                }
178                                $bin = '1' . $bin;
179                               
180                                $array_acl[$right] = $this->safeBitCheck(bindec($bin), $acl);
181                        }
182                        return $array_acl;
183                }
184               
185                function get_inactive_users($contexts)
186                {
187                        $retorno = array();
188                        $tempUsers = array();
189                        //Pego no LDAP todos os usuários dos contextos em questão.
190                        $usuariosLdap = $this->get_list('accounts','',$contexts);
191                        foreach($usuariosLdap as $usuarioLdap)
192                        {
193                                $tempUsers[$usuarioLdap["account_id"]] = $usuarioLdap["account_lid"];
194                        }
195                        $ids = implode(",",array_keys($tempUsers)); //Consigo a lista de uids daquele contexto para mandar na query para o banco.
196                       
197                        //Pego nas configurações do expresso o número de dias necessários para inatividade.
198                        $timeToExpire = $GLOBALS['phpgw_info']['server']['time_to_account_expires'];
199                       
200                       
201                        $ultimoTsValido = time() - ($timeToExpire * 86400); //O último timestamp válido é dado pelo de agora menos o número de dias para expirar vezes a quantidade de segundos existente em 1 dia.
202                        $query = "select account_id,max(li) as last_login from phpgw_access_log where account_id in (".$ids.") group by account_id having max(li) < ".$ultimoTsValido." order by max(li)";
203
204                        $GLOBALS['phpgw']->db->query($query);
205                        while($GLOBALS['phpgw']->db->next_record())
206                        {
207                                $result = $GLOBALS['phpgw']->db->row();
208                                array_push($retorno,array("uidNumber"=>$result["account_id"],"login"=> $tempUsers[$result["account_id"]],"li"=>$result["last_login"]));
209                        }
210                       
211                        return $retorno;
212                }
213
214                function safeBitCheck($number,$comparison)
215                {
216                $binNumber = base_convert($number,10,2);
217                $binComparison = strrev(base_convert($comparison,10,2));
218                        $str = strlen($binNumber);
219               
220                if ( ($str <= strlen($binComparison)) && ($binComparison{$str-1}==="1") )
221                {
222                                return '1';
223                }
224                        else
225                {
226                                return '0';
227                        }
228                }
229               
230                function get_list_all($type, $query, $contexts,$sizelimit)
231                {
232                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
233                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
234                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
235                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
236                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
237                        ldap_bind($ldap_conn,$dn,$passwd);
238                       
239                        if ($type == 'accounts')
240                        {
241                                $justthese = array("uidnumber", "uid", "cn", "mail");
242                                $filter="(&(phpgwAccountType=u)(|(ou=*".$query."*)(uid=*".$query."*)(sn=*".$query."*)(cn=*".$query."*)(givenName=*".$query."*)(mail=$query*)(mailAlternateAddress=$query*)))";
243                                                               
244                                $tmp = array();
245                                foreach ($contexts as $index=>$context)
246                                {
247                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese, 0, $sizelimit);
248                                        $info = ldap_get_entries($ldap_conn, $search);
249                                       
250                                        for ($i=0; $i < $info['count']; $i++)
251                                        {
252                                                $tmp[$info[$i]['uid'][0]]['account_id']  = $info[$i]['uidnumber'][0];
253                                                $tmp[$info[$i]['uid'][0]]['account_lid'] = $info[$i]['uid'][0];
254                                                $tmp[$info[$i]['uid'][0]]['account_cn']  = $info[$i]['cn'][0];
255                                                $tmp[$info[$i]['uid'][0]]['account_mail']= $info[$i]['mail'][0];
256                                                $sort[] = $info[$i]['uid'][0];
257                                        }
258                                }
259                                ldap_close($ldap_conn);
260                               
261                                if (count($sort))
262                                {
263                                        natcasesort($sort);
264                                        foreach ($sort as $user_uid)
265                                                $return[$user_uid] = $tmp[$user_uid];
266                                }
267                               
268                                return $return;
269                        }
270                        elseif($type == 'groups')
271                        {
272                                $filter="(&(phpgwAccountType=g)(cn=*$query*))";
273                                $justthese = array("gidnumber", "cn", "description");
274                               
275                                $tmp = array();
276                                foreach ($contexts as $index=>$context)
277                                {
278                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
279                                        $info = ldap_get_entries($ldap_conn, $search);
280                                        for ($i=0; $i < $info['count']; $i++)
281                                        {
282                                                $tmp[$info[$i]['cn'][0]]['cn']= $info[$i]['cn'][0];
283                                                $tmp[$info[$i]['cn'][0]]['description']= $info[$i]['description'][0];
284                                                $tmp[$info[$i]['cn'][0]]['gidnumber']= $info[$i]['gidnumber'][0];
285                                                $sort[] = $info[$i]['cn'][0];
286                                        }
287                                }
288                                ldap_close($ldap_conn);
289                               
290                                natcasesort($sort);
291                                foreach ($sort as $group_cn)
292                                        $return[$group_cn] = $tmp[$group_cn];
293                               
294                                return $return;
295                        }
296                        elseif($type == 'maillists')
297                        {
298                                $filter="(&(phpgwAccountType=l)(|(cn=*".$query."*)(uid=*".$query."*)(mail=*".$query."*)))";
299                                $justthese = array("uidnumber", "cn", "uid", "mail");
300
301                                $tmp = array();
302                                foreach ($contexts as $index=>$context)
303                                {
304                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
305                                        $info = ldap_get_entries($ldap_conn, $search);
306                                       
307                                        for ($i=0; $i < $info['count']; $i++)
308                                        {
309                                                $tmp[$info[$i]['uid'][0]]['uid']                = $info[$i]['uid'][0];
310                                                $tmp[$info[$i]['uid'][0]]['name']               = $info[$i]['cn'][0];
311                                                $tmp[$info[$i]['uid'][0]]['uidnumber']  = $info[$i]['uidnumber'][0];
312                                                $tmp[$info[$i]['uid'][0]]['email']              = $info[$i]['mail'][0];
313                                                $sort[] = $info[$i]['uid'][0];
314                                        }
315                                }
316                                ldap_close($ldap_conn);
317                               
318                                natcasesort($sort);
319                                foreach ($sort as $maillist_uid)
320                                        $return[$maillist_uid] = $tmp[$maillist_uid];
321                               
322                                return $return;
323                        }
324                        elseif($type == 'computers')
325                        {
326                                $filter="(&(objectClass=sambaSAMAccount)(|(sambaAcctFlags=[W          ])(sambaAcctFlags=[DW         ])(sambaAcctFlags=[I          ])(sambaAcctFlags=[S          ]))(cn=*".$query."*))";
327                                $justthese = array("cn","uidNumber","description");
328
329                                $tmp = array();
330                                foreach ($contexts as $index=>$context)
331                                {
332                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
333                                        $info = ldap_get_entries($ldap_conn, $search);
334                                        for ($i=0; $i < $info['count']; $i++)
335                                        {
336                                                $tmp[$info[$i]['cn'][0]]['cn']                  = $info[$i]['cn'][0];
337                                                $tmp[$info[$i]['cn'][0]]['uidNumber']   = $info[$i]['uidnumber'][0];
338                                                $tmp[$info[$i]['cn'][0]]['description'] = utf8_decode($info[$i]['description'][0]);
339                                                $sort[] = $info[$i]['cn'][0];
340                                        }
341
342                                }
343                                ldap_close($ldap_conn);
344                               
345                                if (!empty($sort))
346                                {
347                                        natcasesort($sort);
348                                        foreach ($sort as $computer_cn)
349                                                $return[$computer_cn] = $tmp[$computer_cn];
350                                }
351                               
352                                return $return;
353                        }
354                }
355
356                function get_list($type, $query, $contexts)
357                {
358                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
359                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
360                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
361                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
362                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
363                        ldap_bind($ldap_conn,$dn,$passwd);
364                       
365                        if ($type == 'accounts')
366                        {
367                                $justthese = array("uidnumber", "uid", "cn", "mail");
368                                $filter="(&(phpgwAccountType=u)(|(uid=*".$query."*)(sn=*".$query."*)(cn=*".$query."*)(givenName=*".$query."*)(mail=$query*)(mailAlternateAddress=$query*)))";
369
370                                $tmp = array();
371                                foreach ($contexts as $index=>$context)
372                                {
373                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
374                                        $info = ldap_get_entries($ldap_conn, $search);
375                                       
376                                        for ($i=0; $i < $info['count']; $i++)
377                                        {
378                                                $tmp[$info[$i]['uid'][0]]['account_id']  = $info[$i]['uidnumber'][0];
379                                                $tmp[$info[$i]['uid'][0]]['account_lid'] = $info[$i]['uid'][0];
380                                                $tmp[$info[$i]['uid'][0]]['account_cn']  = $info[$i]['cn'][0];
381                                                $tmp[$info[$i]['uid'][0]]['account_mail']= $info[$i]['mail'][0];
382                                                $sort[] = $info[$i]['uid'][0];
383                                        }
384                                }
385                                ldap_close($ldap_conn);
386                               
387                                if (count($sort))
388                                {
389                                        natcasesort($sort);
390                                        foreach ($sort as $user_uid)
391                                                $return[$user_uid] = $tmp[$user_uid];
392                                }
393                               
394                                return $return;
395                        }
396                        elseif($type == 'groups')
397                        {
398                                $filter="(&(phpgwAccountType=g)(cn=*$query*))";
399                                $justthese = array("gidnumber", "cn", "description");
400                               
401                                $tmp = array();
402                                foreach ($contexts as $index=>$context)
403                                {
404                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
405                                        $info = ldap_get_entries($ldap_conn, $search);
406                                        for ($i=0; $i < $info['count']; $i++)
407                                        {
408                                                $tmp[$info[$i]['cn'][0]]['cn']= $info[$i]['cn'][0];
409                                                $tmp[$info[$i]['cn'][0]]['description']= $info[$i]['description'][0];
410                                                $tmp[$info[$i]['cn'][0]]['gidnumber']= $info[$i]['gidnumber'][0];
411                                                $sort[] = $info[$i]['cn'][0];
412                                        }
413                                }
414                                ldap_close($ldap_conn);
415                               
416                                natcasesort($sort);
417                                foreach ($sort as $group_cn)
418                                        $return[$group_cn] = $tmp[$group_cn];
419                               
420                                return $return;
421                        }
422                        elseif($type == 'maillists')
423                        {
424                                $filter="(&(phpgwAccountType=l)(|(cn=*".$query."*)(uid=*".$query."*)(mail=*".$query."*)))";
425                                $justthese = array("uidnumber", "cn", "uid", "mail");
426
427                                $tmp = array();
428                                foreach ($contexts as $index=>$context)
429                                {
430                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
431                                        $info = ldap_get_entries($ldap_conn, $search);
432                                       
433                                        for ($i=0; $i < $info['count']; $i++)
434                                        {
435                                                $tmp[$info[$i]['uid'][0]]['uid']                = $info[$i]['uid'][0];
436                                                $tmp[$info[$i]['uid'][0]]['name']               = $info[$i]['cn'][0];
437                                                $tmp[$info[$i]['uid'][0]]['uidnumber']  = $info[$i]['uidnumber'][0];
438                                                $tmp[$info[$i]['uid'][0]]['email']              = $info[$i]['mail'][0];
439                                                $sort[] = $info[$i]['uid'][0];
440                                        }
441                                }
442                                ldap_close($ldap_conn);
443                               
444                                natcasesort($sort);
445                                foreach ($sort as $maillist_uid)
446                                        $return[$maillist_uid] = $tmp[$maillist_uid];
447                               
448                                return $return;
449                        }
450                        elseif($type == 'computers')
451                        {
452                                $filter="(&(objectClass=sambaSAMAccount)(|(sambaAcctFlags=[W          ])(sambaAcctFlags=[DW         ])(sambaAcctFlags=[I          ])(sambaAcctFlags=[S          ]))(cn=*".$query."*))";
453                                $justthese = array("cn","uidNumber","description");
454
455                                $tmp = array();
456                                foreach ($contexts as $index=>$context)
457                                {
458                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
459                                        $info = ldap_get_entries($ldap_conn, $search);
460                                        for ($i=0; $i < $info['count']; $i++)
461                                        {
462                                                $tmp[$info[$i]['cn'][0]]['cn']                  = $info[$i]['cn'][0];
463                                                $tmp[$info[$i]['cn'][0]]['uidNumber']   = $info[$i]['uidnumber'][0];
464                                                $tmp[$info[$i]['cn'][0]]['description'] = utf8_decode($info[$i]['description'][0]);
465                                                $sort[] = $info[$i]['cn'][0];
466                                        }
467
468                                }
469
470                                ldap_close($ldap_conn);
471                               
472                                if (!empty($sort))
473                                {
474                                        natcasesort($sort);
475                                        foreach ($sort as $computer_cn)
476                                                $return[$computer_cn] = $tmp[$computer_cn];
477                                }
478                               
479                                return $return;
480                        }
481                }
482
483                function get_organizations($context, $selected='', $referral=false, $show_invisible_ou=true, $master=false)
484                {
485                        $s = CreateObject('phpgwapi.sector_search_ldap');
486                        $sectors_info = $s->get_organizations($context, $selected, $referral, $show_invisible_ou, $master);
487                        return $sectors_info;
488                }               
489                               
490                function get_sectors($selected='', $referral=false, $show_invisible_ou=true)
491                {
492                        $s = CreateObject('phpgwapi.sector_search_ldap');
493                        $sectors_info = $s->get_sectors($selected, $referral, $show_invisible_ou);
494                        return $sectors_info;
495                }               
496 
497                // Get list of levels (0).
498                function get_groups_list($contexts,$filtro)
499                {
500                        $a_sectors = array();
501                       
502                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
503                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
504                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
505                       
506                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
507                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
508                        ldap_bind($ldap_conn,$dn,$passwd);
509                       
510                        $justthese = array("dn");
511                        $filter = "(ou=".$filtro.")";
512                       
513                        $systemName = strtolower($GLOBALS['phpgw_info']['server']['system_name']);
514                        if ($systemName != '')
515                                $filter = "(&$filter(phpgwSystem=$systemName))";
516                       
517                        foreach ($contexts as $context)
518                        {
519                                $search=ldap_search($ldap_conn, $context, $filter, $justthese);
520                        $info = ldap_get_entries($ldap_conn, $search);
521
522                        for ($i=0; $i<$info["count"]; $i++)
523                    {
524                        $a_sectors[] = $info[$i]['dn'];
525                    }
526                        }
527               
528                        ldap_close($ldap_conn);
529
530                        // Retiro o count do array info e inverto o array para ordenação.
531                foreach ($a_sectors as $context)
532            {
533                                $array_dn = ldap_explode_dn ( $context, 1 );
534
535                $array_dn_reverse  = array_reverse ( $array_dn, true );
536
537                                // Retirar o indice count do array.
538                                array_pop ( $array_dn_reverse );
539
540                                $inverted_dn[$context] = implode ( "#", $array_dn_reverse );
541                        }
542
543                        // Ordenação
544                        natcasesort($inverted_dn);
545                       
546                        // Construção do select
547                        $level = 0;
548                        $options = array();
549                        foreach ($inverted_dn as $dn=>$invert_ufn)
550                        {
551                $display = '';
552
553                $array_dn_reverse = explode ( "#", $invert_ufn );
554                $array_dn  = array_reverse ( $array_dn_reverse, true );
555                $level = count( $array_dn ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
556
557                if ($level == 0)
558                                {
559                    $display.= ' ';
560                        reset ( $array_dn );
561                    $display .= ' ' . (current ( $array_dn ) );
562                                        $dn = trim(strtolower($dn));
563                                        $options[$dn] = $display;
564                }
565                }
566            return $options;
567                }
568               
569                // Get list of levels (0), value DN
570                function get_groups_list_dn($contexts,$filtro)
571                {
572                        $a_sectors = array();
573                       
574                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
575                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
576                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
577                       
578                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
579                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
580                        ldap_bind($ldap_conn,$dn,$passwd);
581                       
582                        $justthese = array("dn");
583                        $filter = "(ou=".$filtro.")";
584                       
585                        $systemName = strtolower($GLOBALS['phpgw_info']['server']['system_name']);
586                        if ($systemName != '')
587                                $filter = "(&$filter(phpgwSystem=$systemName))";
588                       
589                        foreach ($contexts as $context)
590                        {
591                                $search=ldap_search($ldap_conn, $context, $filter, $justthese);
592                        $info = ldap_get_entries($ldap_conn, $search);
593                        for ($i=0; $i<$info["count"]; $i++)
594                    {
595                        $a_sectors[] = $info[$i]['dn'];
596                    }
597                        }
598               
599                        ldap_close($ldap_conn);
600
601                        // Retiro o count do array info e inverto o array para ordenação.
602                foreach ($a_sectors as $context)
603            {
604                                $array_dn = ldap_explode_dn ( $context, 1 );
605
606                $array_dn_reverse  = array_reverse ( $array_dn, true );
607
608                                // Retirar o indice count do array.
609                                array_pop ( $array_dn_reverse );
610
611                                $inverted_dn[$context] = implode ( "#", $array_dn_reverse );
612                        }
613
614                        // Ordenação
615                        natcasesort($inverted_dn);
616                       
617                        // Construção do select
618                        $level = 0;
619                        $options = array();
620                        foreach ($inverted_dn as $dn=>$invert_ufn)
621                        {
622                $display = '';
623
624                $array_dn_reverse = explode ( "#", $invert_ufn );
625                $array_dn  = array_reverse ( $array_dn_reverse, true );
626                $level = count( $array_dn ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
627
628                if ($level == 0)
629                                {
630                    $display.= ' ';
631                        reset ( $array_dn );
632                    $display .= ' ' . trim(strtolower($dn));
633                                        $dn = trim(strtolower($dn));
634                                        $options[] = $display;
635                }
636                }
637            return $options;
638                }
639
640                // Get list of all levels.
641                function get_sectors_list($contexts,$contextdn)
642                {
643                        $a_sectors = array();
644                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
645                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
646                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
647                       
648                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
649                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
650                        ldap_bind($ldap_conn,$dn,$passwd);
651                       
652                        $justthese = array("ou", "dn");
653                        $filter = "(&(objectClass=organizationalUnit)(|(objectClass=organizationalUnit)))";
654                       
655                        foreach ($contexts as $context)
656                        {
657                                $search=ldap_search($ldap_conn, $contextdn, $filter, $justthese);
658                        $info = ldap_get_entries($ldap_conn, $search);
659                        for ($i=0; $i<$info["count"]; $i++)
660                    {
661                        $a_sectors[] = trim(strtoupper($info[$i]['dn']));
662                    }
663                        }
664
665                        ldap_close($ldap_conn);
666
667                        // Retiro o count do array info e inverto o array para ordenação.
668                foreach ($a_sectors as $context)
669            {
670
671                                $array_dn = ldap_explode_dn ( $context, 1 );
672
673                $array_dn_reverse  = array_reverse ( $array_dn, true );
674
675                                // Retirar o indice count do array.
676                                array_pop ( $array_dn_reverse );
677                                $inverted_dn[$context] = implode ( "#", $array_dn_reverse );
678
679                        }
680
681                        // Ordenação
682                        natcasesort($inverted_dn);
683
684                        // seleciona os setores do grupo escolhido
685                        $level = 0;
686                        $options = array();
687
688                        foreach ($inverted_dn as $dn=>$invert_ufn)
689                        {
690                                $display = '';
691                                $array_dn_completo = '';
692                                $ii = 0;                       
693                               
694                                $array_dn_reverse = explode ( "#", $invert_ufn );
695                                $array_dn  = array_reverse ( $array_dn_reverse, true );
696
697                                $valorgrupo = (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])));
698                                $valorsubgrupo = (count($array_dn)-1);
699                                $level = count( $array_dn ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
700
701                                reset ( $array_dn );
702                               
703                                if ($level > 0)
704                                {
705                                        for ($i=0; $i<$level; $i++)
706                                        {
707                                                $ii = $ii +1;
708                                                $display .= ' --';
709
710                                                if ($ii==1)
711                                                {
712                                                        $array_dn_completo .= $array_dn[$valorgrupo + $ii];                                             
713                                                }
714                                                else
715                                                {
716                                                        $array_dn_completo .= " | ".$array_dn[$valorgrupo + $ii];
717                                                }
718
719                                        }
720                                }
721                                else
722                                {
723//                                      $array_dn_completo .= (current($array_dn));                                                                                     
724                                        $array_dn_completo .= ' ';                                                                                     
725                                }
726
727                                $display .= ' '. (current($array_dn)).'#'.trim(strtolower($dn)).'#'.$array_dn_completo;
728                                $options[] = $display;
729
730                }
731            return $options;
732                }
733
734                function get_list_usersgroups_sector($query, $contexts,$sizelimit)
735                {
736                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
737                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
738                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
739                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
740                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
741                        ldap_bind($ldap_conn,$dn,$passwd);
742
743                        $filter = "(&(phpgwAccountType=g)(cn=*))";
744                        $justthese = array("gidnumber", "cn", "description");
745
746                        $tmp = array();
747                        foreach ($contexts as $index=>$context)
748                        {                               
749                                $search = ldap_search($ldap_conn, $query, $filter, $justthese, 0, $sizelimit);
750                                $info = ldap_get_entries($ldap_conn, $search);                         
751                               
752                                for ($i=0; $i < $info['count']; $i++)
753                                {
754                                        $tmp[$info[$i]['cn'][0]]['id']                          = $info[$i]['gidnumber'][0];
755                                        $tmp[$info[$i]['cn'][0]]['name']                        = $info[$i]['cn'][0];
756                                        $tmp[$info[$i]['cn'][0]]['description']         = $info[$i]['description'][0];
757                                        $sort[] = $info[$i]['cn'][0];
758                                }
759                        }
760                        ldap_close($ldap_conn);
761                       
762                        if (count($sort))
763                        {                       
764                                natcasesort($sort);
765                                foreach ($sort as $usersgroups_gid)
766                                        $return[$usersgroups_gid] = $tmp[$usersgroups_gid];
767                        }
768                       
769                        return $return;
770                }               
771               
772                function get_list_maillists_sector($query, $contexts,$sizelimit)
773                {
774                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
775                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
776                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
777                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
778                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
779                        ldap_bind($ldap_conn,$dn,$passwd);
780
781                        $filter="(&(phpgwAccountType=l)(|(uid=*)))";
782                        $justthese = array("uidnumber", "cn", "uid", "mail");
783
784                        $tmp = array();
785                        foreach ($contexts as $index=>$context)
786                        {
787                                $search = ldap_search($ldap_conn, $query, $filter, $justthese, 0, $sizelimit);
788                                $info = ldap_get_entries($ldap_conn, $search);                         
789                               
790                                for ($i=0; $i < $info['count']; $i++)
791                                {
792                                        $tmp[$info[$i]['uid'][0]]['uid']                = $info[$i]['uid'][0];
793                                        $tmp[$info[$i]['uid'][0]]['name']               = $info[$i]['cn'][0];
794                                        $tmp[$info[$i]['uid'][0]]['uidnumber']  = $info[$i]['uidnumber'][0];
795                                        $tmp[$info[$i]['uid'][0]]['email']              = $info[$i]['mail'][0];
796                                        $sort[] = $info[$i]['uid'][0];
797                                }
798                        }
799                        ldap_close($ldap_conn);
800                       
801                        if (count($sort))
802                        {                       
803                                natcasesort($sort);
804                                foreach ($sort as $maillist_uid)
805                                        $return[$maillist_uid] = $tmp[$maillist_uid];
806                        }
807                       
808                        return $return;
809                }               
810               
811                function get_list_user_sector($query, $contexts,$sizelimit)
812                {
813                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
814                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
815                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
816                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
817                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
818                        ldap_bind($ldap_conn,$dn,$passwd);
819
820                        $filter="(&(phpgwAccountType=u)(|(uid=*)))";
821                        $justthese = array("uidnumber", "uid", "cn", "mail","accountstatus","dn","createtimestamp","telephoneNumber");
822                       
823                        $tmp = array();
824               
825                        foreach ($contexts as $index=>$context)
826                        {
827
828                                $search = ldap_search($ldap_conn, $query, $filter, $justthese, 0, $sizelimit);
829                                $info = ldap_get_entries($ldap_conn, $search);
830
831                                for ($i=0; $i < $info['count']; $i++)
832                                {
833                                        $tmp[$info[$i]['uid'][0]]['account_id']  = $info[$i]['uidnumber'][0];
834                                        $tmp[$info[$i]['uid'][0]]['account_lid'] = $info[$i]['uid'][0];
835                                        $tmp[$info[$i]['uid'][0]]['account_cn']  = $info[$i]['cn'][0];
836                                        $tmp[$info[$i]['uid'][0]]['account_mail']= $info[$i]['mail'][0];
837                                        $tmp[$info[$i]['uid'][0]]['account_phone']= $info[$i]['telephonenumber'][0];
838                                        $tmp[$info[$i]['uid'][0]]['account_accountstatus']= $info[$i]['accountstatus'][0];
839                                        $tmp[$info[$i]['uid'][0]]['createtimestamp']= $info[$i]['createtimestamp'][0];                                 
840                                        $sort[] = $info[$i]['uid'][0];
841                                }
842                        }
843                       
844                        ldap_close($ldap_conn);
845                               
846                        if (count($sort))
847                        {
848                                natcasesort($sort);
849                                foreach ($sort as $user_uid)
850                                        $return[$user_uid] = $tmp[$user_uid];
851                        }
852                               
853                        return $return;
854                }
855
856                function get_list_user_sector_logon($query, $contexts,$sizelimit,$numacesso)
857                {
858                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
859                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
860                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
861                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
862                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
863                        ldap_bind($ldap_conn,$dn,$passwd);
864
865                        $filter="(&(phpgwAccountType=u)(|(uid=*)))";
866                        $justthese = array("uidnumber", "uid", "cn", "mail","accountstatus","dn","createtimestamp");
867                       
868                        $tmp = array();
869               
870                        foreach ($contexts as $index=>$context)
871                        {
872
873                                $field = 'cn';
874                                $search = ldap_search($ldap_conn, $query, $filter, $justthese, 0, $sizelimit);
875                                $info = ldap_get_entries($ldap_conn, $search);
876
877                                for ($i=0; $i < $info['count']; $i++)
878                                {
879                                        $access_log =  $this->show_access_log($info[$i]['uidnumber'][0]);
880
881                                        $access_log_array = explode("#",$access_log);
882
883                                        if ($access_log_array[1] >= $numacesso or $numacesso == $access_log_array[0]) {
884
885                                                $tmp[$info[$i]['uid'][0]]['account_id']  = $info[$i]['uidnumber'][0];
886                                                $tmp[$info[$i]['uid'][0]]['account_lid'] = $info[$i]['uid'][0];
887                                                $tmp[$info[$i]['uid'][0]]['account_cn']  = $info[$i]['cn'][0];
888                                                $tmp[$info[$i]['uid'][0]]['account_mail']= $info[$i]['mail'][0];
889                                                $tmp[$info[$i]['uid'][0]]['account_accountstatus']= $info[$i]['accountstatus'][0];
890                                                $tmp[$info[$i]['uid'][0]]['createtimestamp']= $info[$i]['createtimestamp'][0];                                 
891                                                $sort[] = $info[$i]['uid'][0];
892                                        }
893                                }
894                        }
895
896                        ldap_close($ldap_conn);
897                               
898                        if (count($sort))
899                        {
900                                natcasesort($sort);
901                                foreach ($sort as $user_uid)
902                                        $return[$user_uid] = $tmp[$user_uid];
903                        }
904                               
905                        return $return;
906                }
907               
908                function exist_account_lid($account_lid)
909                {
910                        $conection = $GLOBALS['phpgw']->common->ldapConnect();
911                        $sri = ldap_search($conection, $GLOBALS['phpgw_info']['server']['ldap_context'], "uid=" . $account_lid);
912                        $result = ldap_get_entries($conection, $sri);
913                        return $result['count'];
914                }
915               
916                function exist_email($mail)
917                {
918                        $conection = $GLOBALS['phpgw']->common->ldapConnect();
919                        $sri = ldap_search($conection, $GLOBALS['phpgw_info']['server']['ldap_context'], "mail=" . $mail);
920                        $result = ldap_get_entries($conection, $sri);
921                        ldap_close($conection);
922                       
923                        if ($result['count'] == 0)
924                                return false;
925                        else
926                                return true;
927                }
928               
929                function array_invert($array)
930                {
931                        $result[] = end($array);
932                        while ($item = prev($array))
933                                $result[] = $item;
934                        return $result;
935                }
936               
937                function get_next_id()
938                {
939                        // Busco o ID dos accounts
940                        $query_accounts = "SELECT id FROM phpgw_nextid WHERE appname = 'accounts'";
941                        $GLOBALS['phpgw']->db->query($query_accounts);
942                        while($GLOBALS['phpgw']->db->next_record())
943                        {
944                                $result_accounts[] = $GLOBALS['phpgw']->db->row();
945                        }                       
946                        $accounts_id = $result_accounts[0]['id'];
947                       
948                        // Busco o ID dos groups
949                        $query_groups = "SELECT id FROM phpgw_nextid WHERE appname = 'groups'";
950                        $GLOBALS['phpgw']->db->query($query_groups);
951                        while($GLOBALS['phpgw']->db->next_record())
952                        {
953                                $result_groups[] = $GLOBALS['phpgw']->db->row();
954                        }                       
955                        $groups_id = $result_groups[0]['id'];
956                       
957                        //Retorna o maior dos ID's
958                        if ($accounts_id >= $groups_id)
959                                return $accounts_id;
960                        else
961                                return $groups_id;
962                }
963               
964                function make_list_app($account_lid, $user_applications='', $disabled='')
965                {
966                        // create list of ALL available apps
967                        $availableAppsGLOBALS = $GLOBALS['phpgw_info']['apps'];
968                       
969                        // create list of available apps for the user
970                        $query = "SELECT * FROM phpgw_expressoadmin_apps WHERE manager_lid = '".$account_lid."'";
971                        $GLOBALS['phpgw']->db->query($query);
972                        while($GLOBALS['phpgw']->db->next_record())
973                        {
974                                $availableApps[] = $GLOBALS['phpgw']->db->row();
975                        }
976                       
977                        // Retira alguns modulos
978                        if (count($availableApps))
979                        {
980                                foreach ($availableApps as $key => $value)
981                                {
982                                        if ($value['app'] != 'phpgwapi')
983                                                $tmp[] = $availableApps[$key];
984                                }
985                        }
986                        $availableApps = $tmp;
987                       
988                        // Cria um array com as aplicacoes disponiveis para o manager, com as atributos das aplicacoes.
989                        $availableAppsUser = array();
990                        if (count($availableApps))
991                        {
992                                foreach($availableApps as $app => $title)
993                                {
994                                        if ($availableAppsGLOBALS[$title['app']])
995                                                $availableAppsUser[$title['app']] = $availableAppsGLOBALS[$title['app']];
996                                }
997                        }
998                       
999                        // Loop para criar dinamicamente uma tabela com 3 colunas, cada coluna com um aplicativo e um check box.
1000                        $applications_list = '';
1001                        $app_col1 = '';
1002                        $app_col2 = '';
1003                        $app_col3 = '';
1004                        $total_apps = count($availableAppsUser);
1005                        $i = 0;
1006                        foreach($availableAppsUser as $app => $data)
1007                        {
1008                                // 1 coluna
1009                                if (($i +1) % 3 == 1)
1010                                {
1011                                        $checked = $user_applications[$app] ? 'CHECKED' : '';
1012                                        $app_col1 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
1013                                        $data['title'],$app,$checked, $disabled);
1014                                        if ($i == ($total_apps-1))
1015                                                $applications_list .= sprintf('<tr bgcolor="%s">%s</tr>','#DDDDDD', $app_col1);
1016                                }
1017                               
1018                                // 2 coluna
1019                                if (($i +1) % 3 == 2)
1020                                {
1021                                        $checked = $user_applications[$app] ? 'CHECKED' : '';
1022                                        $app_col2 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
1023                                        $data['title'],$app,$checked, $disabled);
1024                                       
1025                                        if ($i == ($total_apps-1))
1026                                                $applications_list .= sprintf('<tr bgcolor="%s">%s%s</tr>','#DDDDDD', $app_col1,$app_col2);
1027                                }
1028                                // 3 coluna
1029                                if (($i +1) % 3 == 0)
1030                                {
1031                                        $checked = $user_applications[$app] ? 'CHECKED' : '';
1032                                        $app_col3 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
1033                                        $data['title'],$app,$checked, $disabled);
1034                                       
1035                                        // Cria nova linha
1036                                        $applications_list .= sprintf('<tr bgcolor="%s">%s%s%s</tr>','#DDDDDD', $app_col1, $app_col2, $app_col3);                                       
1037                                }
1038                                $i++;
1039                        }
1040                        return $applications_list;
1041                }
1042               
1043                function exist_attribute_in_ldap($dn, $attribute, $value)
1044                {
1045                        $connection = $GLOBALS['phpgw']->common->ldapConnect();
1046                        $search = ldap_search($connection, $dn, $attribute. "=" . $value);
1047                        $result = ldap_get_entries($connection, $search);
1048                        ldap_close($connection);
1049                        //_debug_array($result);
1050                        if ($result['count'] == 0)
1051                                return false;
1052                        else
1053                                return true;   
1054                }
1055               
1056                function getReturnExecuteForm(){
1057                        $response = $_SESSION['response'];
1058                        $_SESSION['response'] = null;
1059                        return $response;
1060                }
1061
1062                function lang($key)
1063                {
1064                        if ($_SESSION['phpgw_info']['expressoAdmin']['lang'][$key])
1065                                return $_SESSION['phpgw_info']['expressoAdmin']['lang'][$key];
1066                        else
1067                                return $key . '*';
1068                }
1069               
1070                function make_lang($ram_lang)
1071                {
1072                        $a_lang = split("_", $ram_lang);
1073                        $a_lang_reverse  = array_reverse ( $a_lang, true );
1074                        array_pop ( $a_lang_reverse );
1075                        $a_lang  = array_reverse ( $a_lang_reverse, true );
1076                        $a_new_lang = implode ( " ", $a_lang );
1077                        return lang($a_new_lang);
1078                }
1079
1080                function make_dinamic_lang($template_obj, $block)
1081                {
1082                        $tpl_vars = $template_obj->get_undefined($block);
1083                        $array_langs = array();
1084                       
1085                        foreach ($tpl_vars as $atribute)
1086                        {
1087                                $lang = strstr($atribute, 'lang_');
1088                                if($lang !== false)
1089                                {
1090                                        //$template_obj->set_var($atribute, $this->make_lang($atribute));
1091                                        $array_langs[$atribute] = $this->make_lang($atribute);
1092                                }
1093                        }
1094                        return $array_langs;
1095                }
1096
1097                function paginate_usersgroups($query, $contexts, $field, $order = 'asc', $page = null, $perPage = null )
1098                {
1099                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
1100                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
1101                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1102                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
1103                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
1104                        ldap_bind($ldap_conn,$dn,$passwd);
1105                       
1106                        $filter="(&(phpgwAccountType=g)(cn=*))";
1107                        $justthese = array("gidnumber", "cn", "description");                                                                           
1108                                                       
1109                        foreach ($contexts as $index=>$context)
1110                        {                               
1111                                $search=ldap_search($ldap_conn, $query, $filter, $justthese);
1112       
1113                                $rConnection = $ldap_conn;
1114                                $rSearch = $search;
1115                                $sOrder = $order;
1116                                $iPage = $page;
1117                                $iPerPage = $perPage;
1118                                $sField = $field;
1119                                               
1120                                $iTotalEntries = ldap_count_entries( $rConnection, $rSearch );
1121                               
1122                                if ( $iPage === null || $iPerPage === null )
1123                                {
1124                                        # fetch all in one page
1125                                        $iStart = 0;
1126                                        $iEnd = $iTotalEntries - 1;
1127                                }
1128                                else
1129                                {
1130                                        # calculate range of page
1131                                        $iFimPage = ( ceil( $iTotalEntries / $iPerPage ) - 1 ) * $iPage;
1132                                       
1133                                        $iStart = ( ceil( ($iPage -1) * $iPerPage ));
1134                                        $iEnd = $iPage * $iPerPage;
1135
1136                                        if ( $sOrder === "desc" )
1137                                        {
1138                                                # revert range
1139                                                $iStart = $iTotalEntries - 1 - $iEnd;
1140                                                $iEnd = $iStart + $iPerPage - 1;
1141                                        }
1142                                }
1143                               
1144                                /********* Importante Mostra o resultado da paginação **********
1145                                var_dump( $iStart . " " . $iEnd );
1146                                ****************** Só descomentar ******************************/
1147                               
1148                                 # fetch entries
1149                            ldap_sort( $rConnection, $rSearch, $sField );
1150
1151                                $aList = array();
1152                                for (
1153                                        $iCurrent = 0, $rEntry = ldap_first_entry( $rConnection, $rSearch );
1154                                        $iCurrent <= $iEnd && is_resource( $rEntry );
1155                                        $iCurrent++, $rEntry = ldap_next_entry( $rConnection, $rEntry )
1156                                        )
1157                                {
1158                                        if ( $iCurrent >= $iStart )
1159                                        {
1160                                                array_push( $aList, ldap_get_attributes( $rConnection, $rEntry ));
1161                                        }
1162                                }
1163                        }
1164
1165                        ldap_close($ldap_conn);
1166
1167                        # if order is desc revert page's entries
1168                        return $sOrder === "desc" ? array_reverse( $aList ) : $aList;
1169                }               
1170               
1171                function paginate_maillists($query, $contexts, $field, $order = 'asc', $page = null, $perPage = null )
1172                {
1173                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
1174                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
1175                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1176                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
1177                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
1178                        ldap_bind($ldap_conn,$dn,$passwd);
1179                       
1180                        $filter="(&(phpgwAccountType=l)(|(uid=*)))";
1181                        $justthese = array("uidnumber", "cn", "uid", "mail");                                                                                   
1182                                                       
1183                        foreach ($contexts as $index=>$context)
1184                        {
1185                                $search=ldap_search($ldap_conn, $query, $filter, $justthese);
1186       
1187                                $rConnection = $ldap_conn;
1188                                $rSearch = $search;
1189                                $sOrder = $order;
1190                                $iPage = $page;
1191                                $iPerPage = $perPage;
1192                                $sField = $field;
1193                                               
1194                                $iTotalEntries = ldap_count_entries( $rConnection, $rSearch );
1195                               
1196                                if ( $iPage === null || $iPerPage === null )
1197                                {
1198                                        # fetch all in one page
1199                                        $iStart = 0;
1200                                        $iEnd = $iTotalEntries - 1;
1201                                }
1202                                else
1203                                {
1204                                        # calculate range of page
1205                                        $iFimPage = ( ceil( $iTotalEntries / $iPerPage ) - 1 ) * $iPage;
1206                                       
1207                                        $iStart = ( ceil( ($iPage -1) * $iPerPage ));
1208                                        $iEnd = $iPage * $iPerPage;
1209
1210                                        if ( $sOrder === "desc" )
1211                                        {
1212                                                # revert range
1213                                                $iStart = $iTotalEntries - 1 - $iEnd;
1214                                                $iEnd = $iStart + $iPerPage - 1;
1215                                        }
1216                                }
1217                               
1218                                /********* Importante Mostra o resultado da paginação **********
1219                                var_dump( $iStart . " " . $iEnd );
1220                                ****************** Só descomentar ******************************/
1221                               
1222                                 # fetch entries
1223                            ldap_sort( $rConnection, $rSearch, $sField );
1224
1225                                $aList = array();
1226                                for (
1227                                        $iCurrent = 0, $rEntry = ldap_first_entry( $rConnection, $rSearch );
1228                                        $iCurrent <= $iEnd && is_resource( $rEntry );
1229                                        $iCurrent++, $rEntry = ldap_next_entry( $rConnection, $rEntry )
1230                                        )
1231                                {
1232                                        if ( $iCurrent >= $iStart )
1233                                        {
1234                                                array_push( $aList, ldap_get_attributes( $rConnection, $rEntry ));
1235                                        }
1236                                }
1237                        }
1238
1239                        ldap_close($ldap_conn);
1240
1241                        # if order is desc revert page's entries
1242                        return $sOrder === "desc" ? array_reverse( $aList ) : $aList;
1243                }               
1244               
1245                function Paginate_user($type, $query, $contexts, $Field, $Order = 'asc', $Page = null, $PerPage = null )
1246
1247                {
1248                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
1249                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
1250                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1251                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
1252                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
1253                        ldap_bind($ldap_conn,$dn,$passwd);
1254                       
1255                        $filter="(&(phpgwAccountType=u)(|(uid=*)))";
1256                        $justthese = array("uidnumber", "uid", "cn", "mail","accountstatus","dn","createtimestamp","telephoneNumber");                                                                                 
1257                                                       
1258                        foreach ($contexts as $index=>$context)
1259                        {
1260                                $search=ldap_search($ldap_conn, $query, $filter, $justthese);
1261       
1262                                $rConnection = $ldap_conn;
1263                                $rSearch = $search;
1264                                $sOrder = $Order;
1265                                $iPage = $Page;
1266                                $iPerPage = $PerPage;
1267                                $sField = $Field;
1268                                               
1269                                $iTotalEntries = ldap_count_entries( $rConnection, $rSearch );
1270
1271                                if ( $iPage === null || $iPerPage === null )
1272                                {
1273                                        # fetch all in one page
1274                                        $iStart = 0;
1275                                        $iEnd = $iTotalEntries - 1;
1276                                }
1277                                else
1278                                {
1279                                        # calculate range of page
1280                                        $iFimPage = ( ceil( $iTotalEntries / $iPerPage ) - 1 ) * $iPage;
1281                                       
1282                                        $iStart = ( ceil( ($iPage -1) * $iPerPage ));
1283                                        $iEnd = $iPage * $iPerPage;
1284
1285                                        if ( $sOrder === "desc" )
1286                                        {
1287                                                # revert range
1288                                                $iStart = $iTotalEntries - 1 - $iEnd;
1289                                                $iEnd = $iStart + $iPerPage - 1;
1290                                        }
1291                                }
1292                               
1293                                /********* Importante Mostra o resultado da paginação **********
1294                                var_dump( $iStart . " " . $iEnd );
1295                                ****************** Só descomentar ******************************/
1296                               
1297                                 # fetch entries
1298                            ldap_sort( $rConnection, $rSearch, $sField );
1299
1300                                $aList = array();
1301                                for (
1302                                        $iCurrent = 0, $rEntry = ldap_first_entry( $rConnection, $rSearch );
1303                                        $iCurrent <= $iEnd && is_resource( $rEntry );
1304                                        $iCurrent++, $rEntry = ldap_next_entry( $rConnection, $rEntry )
1305                                        )
1306                                {
1307                                        if ( $iCurrent >= $iStart )
1308                                        {
1309                                                array_push( $aList, ldap_get_attributes( $rConnection, $rEntry ));
1310                                        }
1311                                }
1312                        }
1313
1314                        ldap_close($ldap_conn);
1315
1316                        # if order is desc revert page's entries
1317                        return $sOrder === "desc" ? array_reverse( $aList ) : $aList;
1318                }
1319
1320                function get_list_ou_user_logon($query,$contexts,$sizelimit)
1321                {
1322                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
1323                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
1324                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1325                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
1326                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
1327                        ldap_bind($ldap_conn,$dn,$passwd);
1328
1329                        $filter="(&(phpgwAccountType=u)(|(uid=*".$query."*)))";
1330                        $justthese = array("ou");                                                                                       
1331                        $tmp = array();
1332               
1333                        foreach ($contexts as $index=>$context)
1334                        {
1335
1336                                $field = 'cn';
1337                                $search=ldap_search($ldap_conn, $context, $filter, $justthese, 0, $sizelimit);
1338                                $info = ldap_get_entries($ldap_conn, $search);
1339
1340                                for ($i=0; $i < $info['count']; $i++)
1341                                {
1342                                        $a_sectors[] = $info[$i]['dn'];
1343                                }
1344                        }
1345                       
1346                        ldap_close($ldap_conn);
1347                               
1348                        // Retiro o count do array info e inverto o array para ordenação.
1349                foreach ($a_sectors as $context)
1350            {
1351                                $array_dn = ldap_explode_dn ( $context, 1 );
1352
1353                $array_dn_reverse  = array_reverse ( $array_dn, true );
1354
1355                                // Retirar o indice count do array.
1356                                array_pop ( $array_dn_reverse );
1357
1358                                $inverted_dn[$context] = implode ( "#", $array_dn_reverse );
1359                        }
1360
1361                        // Ordenação
1362                        natcasesort($inverted_dn);
1363
1364                        // Construção do select
1365                        $level = 0;
1366                        $options = array();
1367                        foreach ($inverted_dn as $dn=>$invert_ufn)
1368                        {
1369                $display = '';
1370
1371                $array_dn_reverse = explode ( "#", $invert_ufn );
1372                $array_dn  = array_reverse ( $array_dn_reverse, true );
1373
1374                $level = count( $array_dn ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
1375
1376                                $display.= ' ';
1377                                reset ( $array_dn );
1378                                $display .= ' ' . ($array_dn[$level]);
1379                                $dn = trim(strtolower($dn));
1380                                $options[$dn] = $display;
1381                }
1382
1383            return $options;
1384                }
1385
1386                function get_list_context_logon($query_user,$contexts,$sizelimit)
1387                {
1388                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
1389                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
1390                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1391                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
1392                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
1393                        ldap_bind($ldap_conn,$dn,$passwd);
1394
1395                        // Le BD para pegar os administradors.
1396                        $query = "SELECT manager_lid,context FROM phpgw_expressoadmin WHERE manager_lid='".$query_user."' ORDER by manager_lid";
1397                        $GLOBALS['phpgw']->db->query($query);
1398                        while($GLOBALS['phpgw']->db->next_record())
1399                        {
1400                                $managers[] = $GLOBALS['phpgw']->db->row();
1401                        }
1402
1403                        // Loop para listar as dn
1404                        if (count($managers))
1405                        {
1406                                foreach($managers as $array_managers)
1407                                {
1408                                        $display = '';
1409                                        $managers_context = "";
1410                                        $a_managers_context = explode("%", $array_managers['context']);
1411
1412                                        // Ordenação
1413                                        natcasesort($a_managers_context);
1414
1415                                        $options = array();
1416                                        $level = 0;
1417                                                                                               
1418                                        foreach ($a_managers_context as $dn=>$invert_ufn)
1419                                        {
1420                                                $dn_explode = explode (",",$invert_ufn);
1421
1422                                                // Construção do select
1423                                                $array_dn  = array_reverse ( $dn_explode, true );
1424
1425                                                $level = count( $dn_explode ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
1426                                                $display = ' ';
1427                                                reset ( $array_dn );
1428//                                              $display = str_replace("ou=", "",($array_dn[$level]));
1429                                                $display = str_replace("ou=", "",($array_dn[0]));
1430                                                $display = str_replace("dc=", "",($display));
1431                                                $dn = trim(strtolower($dn));
1432                                                $options[$dn] = trim(strtoupper($display));
1433                                        }
1434                                }
1435                        }
1436
1437                return $options;
1438                }
1439
1440                function get_list_groups_dn($query_user,$contexts,$sizelimit)
1441                {
1442                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
1443                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
1444                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1445                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
1446                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
1447                        ldap_bind($ldap_conn,$dn,$passwd);
1448
1449                        // Le BD para pegar os administradors.
1450                        $query = "SELECT manager_lid,context FROM phpgw_expressoadmin WHERE manager_lid='".$query_user."' ORDER by manager_lid";
1451                        $GLOBALS['phpgw']->db->query($query);
1452                        while($GLOBALS['phpgw']->db->next_record())
1453                        {
1454                                $managers[] = $GLOBALS['phpgw']->db->row();
1455                        }
1456
1457                        // Loop para listar as dn
1458                        if (count($managers))
1459                        {
1460                                foreach($managers as $array_managers)
1461                                {
1462                                        $display = '';
1463                                        $managers_context = "";
1464                                        $options = explode("%", $array_managers['context']);
1465
1466                                        // Ordenação
1467                                        natcasesort($options);
1468                                }
1469                        }
1470
1471                return $options;
1472                }
1473
1474                function sort_by($field, &$arr, $sorting=SORT_ASC, $case_insensitive=true){
1475                        if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
1476                                if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
1477                                else $strcmp_fn = "strnatcmp";
1478               
1479                                if($sorting==SORT_ASC){
1480                                        $fn = create_function('$a,$b', '
1481                                                if(is_object($a) && is_object($b)){
1482                                                        return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
1483                                                }else if(is_array($a) && is_array($b)){
1484                                                        return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
1485                                                }else return 0;
1486                                        ');
1487                                }else{
1488                                        $fn = create_function('$a,$b', '
1489                                                if(is_object($a) && is_object($b)){
1490                                                        return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
1491                                                }else if(is_array($a) && is_array($b)){
1492                                                        return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
1493                                                }else return 0;
1494                                        ');
1495                                }
1496                                usort($arr, $fn);
1497                                return true;
1498                        }else{
1499                                return false;
1500                        }
1501                }       
1502
1503                function show_access_log($account_id)
1504                {       
1505                        $manager_account_lid = $GLOBALS['phpgw']->accounts->data['account_lid'];
1506                        $tmp = $this->read_acl($manager_account_lid);
1507                        $manager_context = $tmp[0]['context'];
1508                       
1509                        // Verifica se tem acesso a este modulo
1510                        if ((!$this->check_acl($manager_account_lid,'edit_users')) && (!$this->check_acl($manager_account_lid,'change_users_password')))
1511                        {
1512                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/reports1_0/inc/access_denied.php'));
1513                        }
1514
1515                        // Le BD para pegar os [li].
1516                        $query = "select li from phpgw_access_log WHERE account_id=".$account_id." order by li desc LIMIT 1 OFFSET 0";
1517                        $GLOBALS['phpgw']->db->query($query);
1518                        while($GLOBALS['phpgw']->db->next_record())
1519                        {
1520                                $managers[] = $GLOBALS['phpgw']->db->row();
1521                        }
1522
1523                        if (count($managers))
1524                        {
1525                                // contar intervalo
1526                                 $data_atual = date("Y/m/d", time());
1527
1528                                 $data_antes = date("Y/m/d",$managers['0']['li']);
1529                               
1530                                 $datainicio=strtotime("$data_antes"); // Data de Hoje
1531                                 $datafim =strtotime("$data_atual"); // Data no próximo ano
1532                               
1533                                 $rdata =($datafim-$datainicio)/86400; //transformação do timestamp em dias
1534
1535                                $access_li = date("d/m/Y",$managers['0']['li'])."#".$rdata;
1536
1537                                return $access_li;
1538
1539                        }else{
1540
1541                                $access_li = "Nunca logou#0";
1542
1543                                return $access_li;
1544                        }
1545                }
1546
1547                function Paginate_user_logon($type, $query, $contexts, $Field, $Order = 'asc', $Page = null, $PerPage = null, $numacesso)
1548                {
1549                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
1550                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
1551                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
1552                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
1553                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
1554                        ldap_bind($ldap_conn,$dn,$passwd);
1555                       
1556                        $filter="(&(phpgwAccountType=u)(|(uid=*)))";
1557                        $justthese = array("uidnumber", "uid", "cn", "mail","accountstatus","dn","createtimestamp");                                                                                   
1558                                                       
1559                        foreach ($contexts as $index=>$context)
1560                        {
1561                                $search=ldap_search($ldap_conn, $query, $filter, $justthese);
1562       
1563                                $rConnection = $ldap_conn;
1564                                $rSearch = $search;
1565                                $sOrder = $Order;
1566                                $iPage = $Page;
1567                                $iPerPage = $PerPage;
1568                                $sField = $Field;
1569                                               
1570                                $iTotalEntries = ldap_count_entries( $rConnection, $rSearch );
1571
1572                                if ( $iPage === null || $iPerPage === null )
1573                                {
1574                                        # fetch all in one page
1575                                        $iStart = 0;
1576                                        $iEnd = $iTotalEntries - 1;
1577                                }
1578                                else
1579                                {
1580                                        # calculate range of page
1581                                        $iFimPage = ( ceil( $iTotalEntries / $iPerPage ) - 1 ) * $iPage;
1582                                       
1583                                        $iStart = ( ceil( ($iPage -1) * $iPerPage ));
1584                                        $iEnd = $iPage * $iPerPage;
1585
1586                                        if ( $sOrder === "desc" )
1587                                        {
1588                                                # revert range
1589                                                $iStart = $iTotalEntries - 1 - $iEnd;
1590                                                $iEnd = $iStart + $iPerPage - 1;
1591                                        }
1592                                }
1593                               
1594                                /********* Importante Mostra o resultado da paginação **********
1595                                var_dump( $iStart . " " . $iEnd );
1596                                ****************** Só descomentar ******************************/
1597                               
1598                                 # fetch entries
1599                            ldap_sort( $rConnection, $rSearch, $sField );
1600
1601                                $aList = array();
1602                                for (
1603                                        $iCurrent = 0, $rEntry = ldap_first_entry( $rConnection, $rSearch );
1604                                        $iCurrent <= $iEnd && is_resource( $rEntry );
1605                                        $iCurrent++, $rEntry = ldap_next_entry( $rConnection, $rEntry )
1606                                        )
1607                                {
1608                                        if ( $iCurrent >= $iStart )
1609                                        {
1610                                                array_push( $aList, ldap_get_attributes( $rConnection, $rEntry ));
1611                                        }
1612                                }
1613                        }
1614
1615                        ldap_close($ldap_conn);
1616
1617                        # if order is desc revert page's entries
1618                        return $sOrder === "desc" ? array_reverse( $aList ) : $aList;
1619                }
1620        }
1621// ****************** fim classe Functions ***********************
1622?>
Note: See TracBrowser for help on using the repository browser.