source: branches/2.2/expressoAdmin1_2/inc/class.functions.inc.php @ 3887

Revision 3887, 36.9 KB checked in by eduardoalex, 13 years ago (diff)

Ticket #1250 - Adição do controle de quotas por OU

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2        /**********************************************************************************\
3        * Expresso Administração                                                                                              *
4        * by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.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                );
26               
27                var $nextmatchs;
28                var $sectors_list = array();
29                var $current_config;
30               
31                function functions()
32                {
33                        $this->db_functions = new db_functions;
34                        $GLOBALS['phpgw']->db = $this->db_functions->db;
35                       
36                        //$c = CreateObject('phpgwapi.config','expressoAdmin1_2');
37                        $c = new config;
38                        $c->read_repository();
39                        $this->current_config = $c->config_data;
40                }
41               
42                // Account and type of access. Return: Have access ? (true/false)
43                function check_acl($account_lid, $access)
44                {
45                        $acl = $this->read_acl($account_lid);
46                        $array_acl = $this->make_array_acl($acl['acl']);
47                       
48                        switch($access)
49                        {
50                                case list_users:
51                                        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] )
52                                                return true;
53                                        break;
54                                case list_groups:
55                                        if ($array_acl[acl_add_groups] || $array_acl[acl_edit_groups] || $array_acl[acl_delete_groups])
56                                                return true;
57                                        break;
58                                case list_maillists:
59                                        if ($array_acl[acl_add_maillists] || $array_acl[acl_edit_maillists] || $array_acl[acl_delete_maillists])
60                                                return true;
61                                        break;
62                                case list_sectors:
63                                        if ($array_acl[acl_create_sectors] || $array_acl[acl_edit_sectors] || $array_acl[acl_delete_sectors])
64                                                return true;
65                                        break;
66                                case list_computers:
67                                        if ($array_acl[acl_create_computers] || $array_acl[acl_edit_computers] || $array_acl[acl_delete_computers])
68                                                return true;
69                                        break;
70
71                                case display_groups:
72                                        if ( $array_acl[acl_edit_users] || $array_acl[acl_view_users] || ($array_acl[acl_edit_sambausers_attributes] && ($this->current_config['expressoAdmin_samba_support'] == 'true')) )
73                                                return true;
74                                        break;
75                                case display_emailconfig:
76                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
77                                                return true;
78                                        break;
79                                case display_applications:
80                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
81                                                return true;
82                                        break;
83                                case display_emaillists:
84                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
85                                                return true;
86                                        break;
87
88                                case list_institutional_accounts:
89                                        if ($array_acl[acl_add_institutional_accounts] || $array_acl[acl_edit_institutional_accounts] || $array_acl[acl_delete_institutional_accounts])
90                                                return true;
91                                        break;
92                                case list_shared_accounts:
93                                        if ($array_acl[acl_add_shared_accounts] || $array_acl[acl_edit_shared_accounts] || $array_acl[acl_delete_shared_accounts])
94                                                return true;
95                                        break;
96
97
98                                default:
99                                        return $array_acl["acl_$access"];
100                        }
101                        return false;
102                }
103
104                /* OLD FUNCTION
105                function check_acl($account_lid, $access)
106                {
107                        $acl = $this->read_acl($account_lid);
108                        $array_acl = $this->make_array_acl($acl['acl']);
109                       
110                        //What access ?? In the IF, verify if have access.
111                        switch($access)
112                        {
113                                case list_users:
114                                        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])
115                                                return true;
116                                        break;
117                                case add_users:
118                                        if ($array_acl[acl_add_users])
119                                                return true;
120                                        break;
121                                case edit_users:
122                                        if ($array_acl[acl_edit_users])
123                                                return true;
124                                        break;
125                                case delete_users:
126                                        if ($array_acl[acl_delete_users])
127                                                return true;
128                                        break;
129                                case rename_users:
130                                        if ($array_acl[acl_rename_users])
131                                                return true;
132                                        break;
133                                case view_users:
134                                        if ($array_acl[acl_view_users])
135                                                return true;
136                                        break;
137                                case edit_users_picture:
138                                        if ($array_acl[acl_edit_users_picture])
139                                                return true;
140                                        break;
141                                case manipulate_corporative_information:
142                                        if ($array_acl[acl_manipulate_corporative_information])
143                                                return true;
144                                        break;
145                                case change_users_password:
146                                        if ($array_acl[acl_change_users_password])
147                                                return true;
148                                        break;
149                                case change_users_quote:
150                                        if ($array_acl[acl_change_users_quote])
151                                                return true;
152                                        break;
153                                case set_user_default_password:
154                                        if ($array_acl[acl_set_user_default_password])
155                                                return true;
156                                        break;
157                                case empty_user_inbox:
158                                        if (($array_acl[acl_empty_user_inbox]) && ($array_acl[acl_edit_users]))
159                                                return true;
160                                        break;
161                                case edit_sambausers_attributes:                                case list_maillists:
162                                        if ($array_acl[acl_add_maillists] || $array_acl[acl_edit_maillists] || $array_acl[acl_delete_maillists])
163                                                return true;
164                                        break;
165
166                                        if ($array_acl[acl_edit_sambausers_attributes])
167                                                return true;
168                                        break;
169                                case edit_sambadomains:
170                                        if ($array_acl[acl_edit_sambadomains])
171                                                return true;
172                                        break;
173                               
174                                case list_groups:
175                                        if ($array_acl[acl_add_groups] || $array_acl[acl_edit_groups] || $array_acl[acl_delete_groups])
176                                                return true;
177                                        break;
178                                case add_groups:
179                                        if ($array_acl[acl_add_groups])
180                                                return true;
181                                        break;
182                                case edit_groups:
183                                        if ($array_acl[acl_edit_groups])
184                                                return true;
185                                        break;
186                                case delete_groups:
187                                        if ($array_acl[acl_delete_groups])
188                                                return true;
189                                        break;
190                                case edit_email_groups:
191                                        if ($array_acl[acl_edit_email_groups])
192                                                return true;
193                                        break;
194                               
195                                case list_maillists:
196                                        if ($array_acl[acl_add_maillists] || $array_acl[acl_edit_maillists] || $array_acl[acl_delete_maillists])
197                                                return true;
198                                        break;
199                                case add_maillists:
200                                        if ($array_acl[acl_add_maillists])
201                                                return true;
202                                        break;
203                                case edit_maillists:
204                                        if ($array_acl[acl_edit_maillists])
205                                                return true;
206                                        break;
207                                case delete_maillists:
208                                        if ($array_acl[acl_delete_maillists])
209                                                return true;
210                                        break;
211
212                                case list_sectors:
213                                        if ($array_acl[acl_create_sectors] || $array_acl[acl_edit_sectors] || $array_acl[acl_delete_sectors])
214                                                return true;
215                                        break;
216                                case create_sectors:
217                                        if ($array_acl[acl_create_sectors])
218                                                return true;
219                                        break;
220                                case edit_sectors:
221                                        if ($array_acl[acl_edit_sectors])
222                                                return true;
223                                        break;
224                                case delete_sectors:
225                                        if ($array_acl[acl_delete_sectors])
226                                                return true;
227                                        break;
228
229                                case view_global_sessions:
230                                        if ($array_acl[acl_view_global_sessions])
231                                                return true;
232                                        break;
233
234                                case list_computers:
235                                        if ($array_acl[acl_create_computers] || $array_acl[acl_edit_computers] || $array_acl[acl_delete_computers])
236                                                return true;
237                                        break;
238                                case create_computers:
239                                        if ($array_acl[acl_create_computers])
240                                                return true;
241                                        break;
242                                case edit_computers:
243                                        if ($array_acl[acl_edit_computers])
244                                                return true;
245                                        break;
246                                case delete_computers:
247                                        if ($array_acl[acl_delete_computers])
248                                                return true;
249                                        break;
250
251                                case view_logs:
252                                        if ($array_acl[acl_view_logs])
253                                                return true;
254                                        break;
255                       
256                                case display_groups:
257                                        if ( $array_acl[acl_edit_users] || $array_acl[acl_view_users] || ($array_acl[acl_edit_sambausers_attributes] && ($this->current_config['expressoAdmin_samba_support'] == 'true')) )
258                                                return true;
259                                        break;
260                                case display_emailconfig:
261                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
262                                                return true;
263                                        break;
264                                case display_applications:
265                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
266                                                return true;
267                                        break;
268                                case display_emaillists:
269                                        if ($array_acl[acl_edit_users] || $array_acl[acl_view_users])
270                                                return true;
271                                        break;
272
273                                default:
274                                        return $array_acl["acl_$access"];
275                        }
276                        return false;
277                }
278                */
279               
280                // Read acl from db
281                function read_acl($account_lid)
282                {
283                        $acl = $this->db_functions->read_acl($account_lid);
284                       
285                        $result['acl'] = $acl[0]['acl'];
286                        $result['manager_lid'] = $acl[0]['manager_lid'];
287                        $result['raw_context'] = $acl[0]['context'];
288                       
289                        $all_contexts = split("%", $acl[0]['context']);
290                        foreach ($all_contexts as $index=>$context)
291                        {
292                                $result['contexts'][] = $context;
293                                $result['contexts_display'][] = str_replace(", ", ".", ldap_dn2ufn( $context ));
294                        }
295                       
296                        return $result;
297                }
298               
299                // Make a array read humam
300                // Last acl:    2.147.483.648 -> edit users phonephone
301                // Last acl:    4.294.967.296 -> add institutional accounts
302                // Last acl:    8.589.934.592 -> edit institutional accounts
303                // Last acl:   17.179.869.184 -> remove institutional accounts
304                // Last acl:   34.359.738.368 -> add share accounts
305                // Last acl:   68.719.476.736 -> edit share accounts
306                // Last acl:  137.438.953.472 -> delete share accounts
307                // Last acl:  274.877.906.944 -> edit share accounts acl
308                // Last acl:  549.755.813.888 -> edit quota share quote
309                // Last acl:  1.099.511.627.776 -> empty share accounts inbox
310
311                function make_array_acl($acl)
312                {
313                        $array_acl_tmp = array();
314                        $tmp = array(           "acl_add_users",
315                                                                "acl_edit_users",
316                                                                "acl_delete_users",
317                                                                "acl_EMPTY1",
318                                                                "acl_add_groups",
319                                                                "acl_edit_groups",
320                                                                "acl_delete_groups",
321                                                                "acl_change_users_password",
322                                                                "acl_add_maillists",
323                                                                "acl_edit_maillists",
324                                                                "acl_delete_maillists",
325                                                                "acl_EMPTY2",
326                                                                "acl_create_sectors",
327                                                                "acl_edit_sectors",
328                                                                "acl_delete_sectors",
329                                                                "acl_edit_sambausers_attributes",
330                                                                "acl_view_global_sessions",
331                                                                "acl_view_logs",
332                                                                "acl_change_users_quote",
333                                                                "acl_set_user_default_password",
334                                                                "acl_create_computers",
335                                                                "acl_edit_computers",
336                                                                "acl_delete_computers",
337                                                                "acl_rename_users",
338                                                                "acl_edit_sambadomains",
339                                                                "acl_view_users",
340                                                                "acl_edit_email_groups",
341                                                                "acl_empty_user_inbox",
342                                                                "acl_manipulate_corporative_information",
343                                                                "acl_edit_users_picture",
344                                                                "acl_edit_scl_email_lists",
345                                                                "acl_edit_users_phonenumber",
346                                                                "acl_add_institutional_accounts",
347                                                                "acl_edit_institutional_accounts",
348                                                                "acl_remove_institutional_accounts",
349                                                                "acl_add_shared_accounts",
350                                                                "acl_edit_shared_accounts",
351                                                                "acl_delete_shared_accounts",
352                                                                "acl_edit_shared_accounts_acl",
353                                                                "acl_edit_shared_accounts_quote",
354                                                                "acl_empty_shared_accounts_inbox"
355                                                                );
356
357                        foreach ($tmp as $index => $right)
358                        {
359                                $bin = '';
360                                for ($i=0; $i<$index; $i++)
361                                {
362                                        $bin .= '0';
363                                }
364                                $bin = '1' . $bin;
365                               
366                                $array_acl[$right] = $this->safeBitCheck(bindec($bin), $acl);
367                        }
368                        return $array_acl;
369                }
370               
371                function get_inactive_users($contexts) {
372                        $retorno = array();
373                        $tempUsers = array();
374                        //Pego no LDAP todos os usuários dos contextos em questão.
375                        $usuariosLdap = $this->get_list('accounts','',$contexts);
376                        foreach($usuariosLdap as $usuarioLdap) {
377                                $tempUsers[$usuarioLdap["account_id"]] = $usuarioLdap["account_lid"];
378                        }
379                        $ids = implode(",",array_keys($tempUsers)); //Consigo a lista de uids daquele contexto para mandar na query para o banco.
380                       
381                        //Pego nas configurações do expresso o número de dias necessários para inatividade.
382                        $timeToExpire = $GLOBALS['phpgw_info']['server']['time_to_account_expires'];
383                       
384                       
385                        $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.
386                        $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)";
387
388                        $GLOBALS['phpgw']->db->query($query);
389                        while($GLOBALS['phpgw']->db->next_record())
390                        {
391                                $result = $GLOBALS['phpgw']->db->row();
392                                array_push($retorno,array("uidNumber"=>$result["account_id"],"login"=> $tempUsers[$result["account_id"]],"li"=>$result["last_login"]));
393                        }
394                       
395                        return $retorno;
396                }
397
398                function safeBitCheck($number,$comparison)
399                {
400                $binNumber = base_convert($number,10,2);
401                $binComparison = strrev(base_convert($comparison,10,2));
402                        $str = strlen($binNumber);
403               
404                if ( ($str <= strlen($binComparison)) && ($binComparison{$str-1}==="1") )
405                        return '1';
406                else
407                        return '0';
408                }
409               
410                function get_list($type, $query, $contexts)
411                {
412                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
413                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
414                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
415                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
416                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
417                        ldap_bind($ldap_conn,$dn,$passwd);
418                       
419                        if ($type == 'accounts')
420                        {
421                                $justthese = array("uidnumber", "uid", "cn", "mail");
422                                $filter="(&(phpgwAccountType=u)(|(uid=*".$query."*)(sn=*".$query."*)(cn=*".$query."*)(givenName=*".$query."*)(mail=$query*)(mailAlternateAddress=$query*)))";
423                                $filter = preg_replace("/\*\*/","*",$filter); //Caso a query venha vazia, inibir a montagem do filtro com ** pois algumas versões do php mais recentes não corrigem isso no ldap_search
424                                $tmp = array();
425                                foreach ($contexts as $index=>$context)
426                                {
427                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
428                                        $info = ldap_get_entries($ldap_conn, $search);
429                                       
430                                        for ($i=0; $i < $info['count']; $i++)
431                                        {
432                                                $tmp[$info[$i]['uid'][0]]['account_id']  = $info[$i]['uidnumber'][0];
433                                                $tmp[$info[$i]['uid'][0]]['account_lid'] = $info[$i]['uid'][0];
434                                                $tmp[$info[$i]['uid'][0]]['account_cn']  = $info[$i]['cn'][0];
435                                                $tmp[$info[$i]['uid'][0]]['account_mail']= $info[$i]['mail'][0];
436                                                $sort[] = $info[$i]['uid'][0];
437                                        }
438                                }
439                                ldap_close($ldap_conn);
440                               
441                                if (count($sort))
442                                {
443                                        natcasesort($sort);
444                                        foreach ($sort as $user_uid)
445                                                $return[$user_uid] = $tmp[$user_uid];
446                                }
447                               
448                                return $return;
449                        }
450                        elseif($type == 'groups')
451                        {
452                                $filter="(&(phpgwAccountType=g)(cn=*$query*))";
453                                $justthese = array("gidnumber", "cn", "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]]['description']= $info[$i]['description'][0];
464                                                $tmp[$info[$i]['cn'][0]]['gidnumber']= $info[$i]['gidnumber'][0];
465                                                $sort[] = $info[$i]['cn'][0];
466                                        }
467                                }
468                                ldap_close($ldap_conn);
469                               
470                                natcasesort($sort);
471                                foreach ($sort as $group_cn)
472                                        $return[$group_cn] = $tmp[$group_cn];
473                               
474                                return $return;
475                        }
476                        elseif($type == 'maillists')
477                        {
478                                $filter="(&(phpgwAccountType=l)(|(cn=*".$query."*)(uid=*".$query."*)(mail=*".$query."*)))";
479                                $justthese = array("uidnumber", "cn", "uid", "mail");
480
481                                $tmp = array();
482                                foreach ($contexts as $index=>$context)
483                                {
484                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
485                                        $info = ldap_get_entries($ldap_conn, $search);
486                                       
487                                        for ($i=0; $i < $info['count']; $i++)
488                                        {
489                                                $tmp[$info[$i]['uid'][0]]['uid']                = $info[$i]['uid'][0];
490                                                $tmp[$info[$i]['uid'][0]]['name']               = $info[$i]['cn'][0];
491                                                $tmp[$info[$i]['uid'][0]]['uidnumber']  = $info[$i]['uidnumber'][0];
492                                                $tmp[$info[$i]['uid'][0]]['email']              = $info[$i]['mail'][0];
493                                                $sort[] = $info[$i]['uid'][0];
494                                        }
495                                }
496                                ldap_close($ldap_conn);
497                               
498                                natcasesort($sort);
499                                foreach ($sort as $maillist_uid)
500                                        $return[$maillist_uid] = $tmp[$maillist_uid];
501                               
502                                return $return;
503                        }
504                        elseif($type == 'computers')
505                        {
506                                $filter="(&(objectClass=sambaSAMAccount)(|(sambaAcctFlags=[W          ])(sambaAcctFlags=[DW         ])(sambaAcctFlags=[I          ])(sambaAcctFlags=[S          ]))(cn=*".$query."*))";
507                                $justthese = array("cn","uidNumber","description");
508
509                                $tmp = array();
510                                foreach ($contexts as $index=>$context)
511                                {
512                                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
513                                        $info = ldap_get_entries($ldap_conn, $search);
514                                        for ($i=0; $i < $info['count']; $i++)
515                                        {
516                                                $tmp[$info[$i]['cn'][0]]['cn']                  = $info[$i]['cn'][0];
517                                                $tmp[$info[$i]['cn'][0]]['uidNumber']   = $info[$i]['uidnumber'][0];
518                                                $tmp[$info[$i]['cn'][0]]['description'] = utf8_decode($info[$i]['description'][0]);
519                                                $sort[] = $info[$i]['cn'][0];
520                                        }
521
522                                }
523                                ldap_close($ldap_conn);
524                               
525                                if (!empty($sort))
526                                {
527                                        natcasesort($sort);
528                                        foreach ($sort as $computer_cn)
529                                                $return[$computer_cn] = $tmp[$computer_cn];
530                                }
531                               
532                                return $return;
533                        }
534                }
535               
536                function get_organizations($context, $selected='', $referral=false, $show_invisible_ou=true, $master=false)
537                {
538                        $s = CreateObject('phpgwapi.sector_search_ldap');
539                        $sectors_info = $s->get_organizations($context, $selected, $referral, $show_invisible_ou, $master);
540                        return $sectors_info;
541                }
542               
543                /*
544                        Funciona de maneira similar ao get_sectors_list, porém retorna a propria OU do contexto
545                        e monta o array de retorno de forma diferente, necessário para algumas mudanças implementadas
546                        no método admin.uisectors.list_sectors.
547                */
548                function get_organizations2($contexts, $selected='', $referral=false, $show_invisible_ou=true) {               
549
550                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
551                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
552                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
553                                               
554                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
555                       
556                        if ($referral)
557                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 1);
558                        else
559                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
560                       
561                        ldap_bind($ldap_conn,$dn,$passwd);
562                       
563                        $justthese = array("dn","diskQuota","usersQuota","actualDiskQuota");
564                        $filter = "(objectClass=organizationalUnit)";
565                        foreach ($contexts as $context) {
566                                $search=ldap_search($ldap_conn, $context, $filter, $justthese);
567                               
568                                ldap_sort($ldap_conn, $search, "ou");
569                                $info = ldap_get_entries($ldap_conn, $search);
570                                ldap_close($ldap_conn);
571       
572                                // Retiro o count do array info e inverto o array para ordenaçãoo.
573                                for ($i=0; $i<$info["count"]; $i++)
574                                {
575                                        $dn = $info[$i]["dn"];
576                                       
577                                        // Necessário, pq em uma busca com ldapsearch objectClass=organizationalUnit, traz tb o próprio ou.
578                                        //if (strtolower($dn) == $context)
579                                                //continue;
580       
581                                        $array_dn = ldap_explode_dn ( $dn, 1 );
582       
583                                        $array_dn_reverse  = array_reverse ( $array_dn, true );
584       
585                                        // Retirar o indice count do array.
586                                        array_pop ( $array_dn_reverse );
587       
588                                        $inverted_dn[implode ( "#", $array_dn_reverse )] = $info[$i];
589                                }
590                        }
591                        // Ordenação por chave
592                        ksort($inverted_dn);                   
593                       
594                        // Construção do select
595                        $level = 0;
596                        $options = array();
597                        foreach ($inverted_dn as $dn=>$info_ou)
598                        {
599                $display = '';
600                                $info_retorno = array();
601                $array_dn_reverse = explode ( "#", $dn );
602                $array_dn  = array_reverse ( $array_dn_reverse, true );
603
604                $level = count( $array_dn ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
605
606                if ($level == 0)
607                        $display .= '+';
608                else
609                {
610                                        for ($i=0; $i<$level; $i++)
611                                                $display .= '---';
612                }
613
614                reset ( $array_dn );
615                $display .= ' ' . (current ( $array_dn ) );
616                               
617                                $info_retorno['display'] = $display;
618                                $info_retorno['dn'] = $info_ou['dn'];
619                                $info_retorno['diskquota'] = $info_ou['diskquota'][0];
620                                $info_retorno['usersquota'] = $info_ou['usersquota'][0];
621//                              $info_retorno['actualdiskquota'] = round($this->get_actual_disk_usage($info_ou['dn']),2);//$info_ou['actualdiskquota'][0];
622//                              $info_retorno['actualnumusers'] = $this->get_num_users($info_ou['dn']);
623                               
624                                array_push($options,$info_retorno);
625                               
626                }
627                        return $options;
628                }       
629               
630                function get_info($context, $referral = false) {
631                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
632                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
633                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
634                       
635                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
636                       
637                        if ($referral)
638                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 1);
639                        else
640                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
641                       
642                        ldap_bind($ldap_conn,$dn,$passwd);
643                       
644                        $filter="(objectClass=organizationalUnit)";
645                        $search=ldap_search($ldap_conn, $context, $filter);
646                        $result = ldap_get_entries($ldap_conn, $search);
647                        return $result;
648                               
649                }
650
651                function get_num_users($context,$selected='', $referral=false, $show_invisible_ou=true) {
652                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
653                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
654                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
655                       
656                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
657                       
658                        if ($referral)
659                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 1);
660                        else
661                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
662                       
663                        ldap_bind($ldap_conn,$dn,$passwd);
664                       
665                        $justthese = array("dn");
666                        $filter = "(objectClass=inetOrgPerson)";
667                        $search=ldap_search($ldap_conn, $context, $filter, $justthese);
668               
669                $retorno = ldap_count_entries($ldap_conn, $search);
670                        ldap_close($ldap_conn);
671                       
672                        return $retorno;
673                }
674               
675                //Checa se existe quota para mais um usuï¿œrio no setor... se existir retorna true, senï¿œo false.             
676                function existe_quota_usuario($setor) {
677                        $num_users = $this->get_num_users($setor['dn']);
678                        //return $num_users . " --- " . $setor['usersquota'][0]
679                        if(($num_users>=$setor['usersquota'][0]) && ($setor['usersquota'][0]!=-1)) {
680                                return false;
681                        }
682                        return true;
683                }
684               
685                //Checa se existe quota em disco para mais um usuário no setor... se existir retorna true, senão false.
686                function existe_quota_disco($setor,$quota_novo_usuario) {
687                        settype($quota_novo_usuario,"float");           
688                        $quota_novo_usuario /= 1024; //A quota vêm da interface em megabytes, deve se tornar gigabyte.
689
690                        $nova_quota = $this->get_actual_disk_usage($setor['dn']) + $quota_novo_usuario;
691                        if(( $nova_quota >= $setor['diskquota'][0] ) && ($setor['diskquota'][0] != -1)) {
692                                return false;
693                        }
694                        return true;
695                }
696               
697                function has_file_disk_quota($home_directory,$quota) {
698                        $uid = substr($home_directory,strpos($home_directory,"/home/")+6);
699                        $context = $this->get_ou_context_from_uid($uid);
700                       
701                        $sector = $this->get_info($context);
702                        $new_quota = $this->get_actual_disk_usage($sector[0]['dn'],'FileManager',$uid) + $quota;
703                        if(( $new_quota > $sector[0]['filemanagerquota'][0] ) && ($sector[0]['filemanagerquota'][0] != -1)) {
704                                return false;
705                        }
706                        return true;
707                }
708               
709                function get_ou_context_from_uid($uid,$referral = false) {
710                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
711                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
712                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
713                        $context = $GLOBALS['phpgw_info']['server']['ldap_context'];
714                       
715                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
716                       
717                        if ($referral)
718                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 1);
719                        else
720                                ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
721                       
722                        ldap_bind($ldap_conn,$dn,$passwd);
723                        $filter="(&(objectClass=phpgwAccount)(uid=$uid))";
724                        $search=ldap_search($ldap_conn, $context, $filter);
725                        $result = ldap_get_entries($ldap_conn, $search);
726                       
727                        if($result['count']>0){
728                                $dn = $result[0]['dn'];
729                                return substr($dn,strpos($dn,$uid.",")+strlen($uid.","));
730                        }
731                        else
732                                return false;
733                }
734               
735                // Soma as quotas de todos os usuï¿œrios daquele contexto.
736                function get_actual_disk_usage($context,$app='expressoMail',$user=null) {
737                        $quota_usada=0;
738                        $contexts = array($context);
739                        $usuarios = $this->get_list('accounts', '', $contexts);
740
741                        if($app=='expressoMail') {
742                                $imap_functions = new imap_functions();
743                                foreach($usuarios as $usuario) {
744                                        $temp = $imap_functions->get_user_info($usuario['account_lid']);
745                                        if($temp['mailquota'] != -1) //Usuï¿œrio sem cota nï¿œo conta...
746                                                $quota_usada += ($temp['mailquota'] / 1024);
747                                }
748                        }
749                        else if($app=='FileManager'){ //FileManager
750                                $uids = '';
751                                foreach($usuarios as $usuario) {
752                                        if($usuario['account_lid']!=$user)
753                                                $uids.="'/home/".$usuario['account_lid']."',";
754                                }
755                                $uids.="'a'"; //hack the last comma
756                                $query = "select 1 as num,sum(quota_size) as quota from phpgw_vfs_quota where directory in ($uids) group by num";
757                                $GLOBALS['phpgw']->db->query($query);
758                                if($GLOBALS['phpgw']->db->next_record())
759                                {
760                                        $result = $GLOBALS['phpgw']->db->row();
761                                        $quota_usada = $result["quota"];
762                                }                       
763                        }
764                        return $quota_usada;
765                }
766
767                function get_sectors($selected='', $referral=false, $show_invisible_ou=true)
768                {
769                        $s = CreateObject('phpgwapi.sector_search_ldap');
770                        $sectors_info = $s->get_sectors($selected, $referral, $show_invisible_ou);
771                        return $sectors_info;
772                }               
773 
774                // Get list of all levels, this function is used for sectors module.
775                function get_sectors_list($contexts)
776                {
777                        $a_sectors = array();
778                       
779                        $dn                     = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
780                        $passwd         = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
781                        $ldap_conn      = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
782                       
783                        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
784                        ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
785                        ldap_bind($ldap_conn,$dn,$passwd);
786                       
787                        $justthese = array("dn");
788                        $filter = "(objectClass=organizationalUnit)";
789                       
790                        $systemName = strtolower($GLOBALS['phpgw_info']['server']['system_name']);
791                        if ($systemName != '')
792                                $filter = "(&$filter(phpgwSystem=$systemName))";
793                       
794                        foreach ($contexts as $context)
795                        {
796                                $search=ldap_search($ldap_conn, $context, $filter, $justthese);
797                        $info = ldap_get_entries($ldap_conn, $search);
798                        for ($i=0; $i<$info["count"]; $i++)
799                    {
800                        $a_sectors[] = $info[$i]['dn'];
801                    }
802                        }
803               
804                        ldap_close($ldap_conn);
805
806                        // Retiro o count do array info e inverto o array para ordenação.
807                foreach ($a_sectors as $context)
808            {
809                                $array_dn = ldap_explode_dn ( $context, 1 );
810
811                $array_dn_reverse  = array_reverse ( $array_dn, true );
812
813                                // Retirar o indice count do array.
814                                array_pop ( $array_dn_reverse );
815
816                                $inverted_dn[$context] = implode ( "#", $array_dn_reverse );
817                        }
818
819                        // Ordenação
820                        natcasesort($inverted_dn);
821                       
822                        // Construção do select
823                        $level = 0;
824                        $options = array();
825                        foreach ($inverted_dn as $dn=>$invert_ufn)
826                        {
827                $display = '';
828
829                $array_dn_reverse = explode ( "#", $invert_ufn );
830                $array_dn  = array_reverse ( $array_dn_reverse, true );
831
832                $level = count( $array_dn ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
833
834                if ($level == 0)
835                        $display .= '+';
836                else
837                {
838                                        for ($i=0; $i<$level; $i++)
839                                                $display .= '---';
840                }
841
842                reset ( $array_dn );
843                $display .= ' ' . (current ( $array_dn ) );
844                               
845                                $dn = trim(strtolower($dn));
846                                $options[$dn] = $display;
847                }
848            return $options;
849                }
850               
851                function exist_account_lid($account_lid)
852                {
853                        $conection = $GLOBALS['phpgw']->common->ldapConnect();
854                        $sri = ldap_search($conection, $GLOBALS['phpgw_info']['server']['ldap_context'], "uid=" . $account_lid);
855                        $result = ldap_get_entries($conection, $sri);
856                        return $result['count'];
857                }
858               
859                function exist_email($mail)
860                {
861                        $conection = $GLOBALS['phpgw']->common->ldapConnect();
862                        $sri = ldap_search($conection, $GLOBALS['phpgw_info']['server']['ldap_context'], "mail=" . $mail);
863                        $result = ldap_get_entries($conection, $sri);
864                        ldap_close($conection);
865                       
866                        if ($result['count'] == 0)
867                                return false;
868                        else
869                                return true;
870                }
871               
872                function array_invert($array)
873                {
874                        $result[] = end($array);
875                        while ($item = prev($array))
876                                $result[] = $item;
877                        return $result;
878                }
879               
880                function get_next_id()
881                {
882                        // Busco o ID dos accounts
883                        $query_accounts = "SELECT id FROM phpgw_nextid WHERE appname = 'accounts'";
884                        $GLOBALS['phpgw']->db->query($query_accounts);
885                        while($GLOBALS['phpgw']->db->next_record())
886                        {
887                                $result_accounts[] = $GLOBALS['phpgw']->db->row();
888                        }                       
889                        $accounts_id = $result_accounts[0]['id'];
890                       
891                        // Busco o ID dos groups
892                        $query_groups = "SELECT id FROM phpgw_nextid WHERE appname = 'groups'";
893                        $GLOBALS['phpgw']->db->query($query_groups);
894                        while($GLOBALS['phpgw']->db->next_record())
895                        {
896                                $result_groups[] = $GLOBALS['phpgw']->db->row();
897                        }                       
898                        $groups_id = $result_groups[0]['id'];
899                       
900                        //Retorna o maior dos ID's
901                        if ($accounts_id >= $groups_id)
902                                return $accounts_id;
903                        else
904                                return $groups_id;
905                }
906                function make_list_personal_data_fields($account_lid, $acl = '')
907                {
908                        // Sem restrição nenhuma na edição dos campos pessoais  => $acl=0;
909                        // Com restrição apenas na edição do Tel. Comercial     => $acl=1;
910                        // Com restrição apenas na edição do Tel. Celular               => $acl=2;
911                        // Com restrição na edição do Tel. Comercial e Celular  => $acl=3;                     
912                        // Com restricao apenas na edicao do Tel. Residencial   => $acl=4;
913                        // ....
914                        // Com restricao de edição em todos os campos pessoais  => $acl=7;
915                       
916                        $personal_data_fields = array( 
917                                        array("text" => lang("%1 telephone number", lang("Commercial")) , "acl" => 1),
918                                        array("text" => lang("%1 telephone number", lang("Mobile"))             , "acl" => 2),
919                                        array("text" => lang("%1 telephone number", lang("Home Phone"))         , "acl" => 4),
920                                        array("text" => lang("Birthday")                                                                , "acl" => 8));
921                        $list_personal_data = "<tr>";
922                                               
923                        foreach($personal_data_fields as $i => $data_field)     {
924                                $checked = ($data_field['acl'] & $acl) ? "CHECKED" : "";
925                                $list_personal_data .= "<td align=right bgcolor='#DDDDDD'>{$data_field['text']}</td>".
926                                "<td bgcolor='#DDDDDD' width='10'><input type='checkbox' name='acl_block_personal_data[]'".
927                                " value='{$data_field['acl']}' $checked></td>";
928                        }
929                        $list_personal_data .= "</tr>";
930                        return $list_personal_data;
931                }
932               
933                function make_list_app($account_lid, $user_applications='', $disabled='')
934                {
935                        // create list of ALL available apps
936                        $availableAppsGLOBALS = $GLOBALS['phpgw_info']['apps'];
937                       
938                        // create list of available apps for the user
939                        $query = "SELECT * FROM phpgw_expressoadmin_apps WHERE manager_lid = '".$account_lid."'";
940                        $GLOBALS['phpgw']->db->query($query);
941                        while($GLOBALS['phpgw']->db->next_record())
942                        {
943                                $availableApps[] = $GLOBALS['phpgw']->db->row();
944                        }
945                       
946                        // Retira alguns modulos
947                        if (count($availableApps))
948                        {
949                                foreach ($availableApps as $key => $value)
950                                {
951                                        if ($value['app'] != 'phpgwapi')
952                                                $tmp[] = $availableApps[$key];
953                                }
954                        }
955                        $availableApps = $tmp;
956                       
957                        // Cria um array com as aplicacoes disponiveis para o manager, com as atributos das aplicacoes.
958                        $availableAppsUser = array();
959                        if (count($availableApps))
960                        {
961                                foreach($availableApps as $app => $title)
962                                {
963                                        if ($availableAppsGLOBALS[$title['app']])
964                                                $availableAppsUser[$title['app']] = $availableAppsGLOBALS[$title['app']];
965                                }
966                        }
967                       
968                        // Loop para criar dinamicamente uma tabela com 3 colunas, cada coluna com um aplicativo e um check box.
969                        $applications_list = '';
970                        $app_col1 = '';
971                        $app_col2 = '';
972                        $app_col3 = '';
973                        $total_apps = count($availableAppsUser);
974                        $i = 0;
975                        foreach($availableAppsUser as $app => $data)
976                        {
977                                // 1 coluna
978                                if (($i +1) % 3 == 1)
979                                {
980                                        $checked = $user_applications[$app] ? 'CHECKED' : '';
981                                        $app_col1 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
982                                        $data['title'],$app,$checked, $disabled);
983                                        if ($i == ($total_apps-1))
984                                                $applications_list .= sprintf('<tr bgcolor="%s">%s</tr>','#DDDDDD', $app_col1);
985                                }
986                               
987                                // 2 coluna
988                                if (($i +1) % 3 == 2)
989                                {
990                                        $checked = $user_applications[$app] ? 'CHECKED' : '';
991                                        $app_col2 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
992                                        $data['title'],$app,$checked, $disabled);
993                                       
994                                        if ($i == ($total_apps-1))
995                                                $applications_list .= sprintf('<tr bgcolor="%s">%s%s</tr>','#DDDDDD', $app_col1,$app_col2);
996                                }
997                                // 3 coluna
998                                if (($i +1) % 3 == 0)
999                                {
1000                                        $checked = $user_applications[$app] ? 'CHECKED' : '';
1001                                        $app_col3 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
1002                                        $data['title'],$app,$checked, $disabled);
1003                                       
1004                                        // Cria nova linha
1005                                        $applications_list .= sprintf('<tr bgcolor="%s">%s%s%s</tr>','#DDDDDD', $app_col1, $app_col2, $app_col3);                                       
1006                                }
1007                                $i++;
1008                        }
1009                        return $applications_list;
1010                }
1011               
1012                function exist_attribute_in_ldap($dn, $attribute, $value)
1013                {
1014                        $connection = $GLOBALS['phpgw']->common->ldapConnect();
1015                        $search = ldap_search($connection, $dn, $attribute. "=" . $value);
1016                        $result = ldap_get_entries($connection, $search);
1017                        ldap_close($connection);
1018                        //_debug_array($result);
1019                        if ($result['count'] == 0)
1020                                return false;
1021                        else
1022                                return true;   
1023                }
1024               
1025                function getReturnExecuteForm(){
1026                        $response = $_SESSION['response'];
1027                        $_SESSION['response'] = null;
1028                        return $response;
1029                }
1030
1031                function lang($key)
1032                {
1033                        if ($_SESSION['phpgw_info']['expressoAdmin']['lang'][$key])
1034                                return $_SESSION['phpgw_info']['expressoAdmin']['lang'][$key];
1035                        else
1036                                return $key . '*';
1037                }
1038               
1039               
1040                function checkCPF($cpf)
1041                {
1042                        $nulos = array("12345678909","11111111111","22222222222","33333333333",
1043                               "44444444444","55555555555","66666666666","77777777777",
1044                           "88888888888","99999999999","00000000000");
1045
1046                        /* formato do CPF */
1047                        if (!(ereg("^[0-9]{3}[.][0-9]{3}[.][0-9]{3}[-][0-9]{2}$",$cpf)))
1048                                return false;
1049
1050                        /* Retira todos os caracteres que nao sejam 0-9 */
1051                        $cpf = ereg_replace("[^0-9]", "", $cpf);
1052
1053                        /*Retorna falso se houver letras no cpf */
1054                        if (!(ereg("[0-9]",$cpf)))
1055                        return false;
1056
1057                        /* Retorna falso se o cpf for nulo */
1058                        if( in_array($cpf, $nulos) )
1059                        return false;
1060
1061                        /*Calcula o penúltimo dígito verificador*/
1062                        $acum=0;
1063                        for($i=0; $i<9; $i++)
1064                        {
1065                                $acum+= $cpf[$i]*(10-$i);
1066                        }
1067
1068                        $x=$acum % 11;
1069                        $acum = ($x>1) ? (11 - $x) : 0;
1070                        /* Retorna falso se o digito calculado eh diferente do passado na string */
1071                        if ($acum != $cpf[9]){
1072                                return false;
1073                        }
1074                        /*Calcula o último dígito verificador*/
1075                        $acum=0;
1076                        for ($i=0; $i<10; $i++)
1077                        {
1078                                $acum+= $cpf[$i]*(11-$i);
1079                        }
1080
1081                        $x=$acum % 11;
1082                        $acum = ($x > 1) ? (11-$x) : 0;
1083                        /* Retorna falso se o digito calculado eh diferente do passado na string */
1084                        if ( $acum != $cpf[10])
1085                        {
1086                                return false;
1087                        }
1088                        /* Retorna verdadeiro se o cpf eh valido */
1089                        return true;
1090                }
1091               
1092                function make_lang($ram_lang)
1093                {
1094                        $a_lang = split("_", $ram_lang);
1095                        $a_lang_reverse  = array_reverse ( $a_lang, true );
1096                        array_pop ( $a_lang_reverse );
1097                        $a_lang  = array_reverse ( $a_lang_reverse, true );
1098                        $a_new_lang = implode ( " ", $a_lang );
1099                        return lang($a_new_lang);
1100                }
1101
1102                function make_dinamic_lang($template_obj, $block)
1103                {
1104                        $tpl_vars = $template_obj->get_undefined($block);
1105                        $array_langs = array();
1106                       
1107                        foreach ($tpl_vars as $atribute)
1108                        {
1109                                $lang = strstr($atribute, 'lang_');
1110                                if($lang !== false)
1111                                {
1112                                        //$template_obj->set_var($atribute, $this->make_lang($atribute));
1113                                        $array_langs[$atribute] = $this->make_lang($atribute);
1114                                }
1115                        }
1116                        return $array_langs;
1117                }
1118        }
1119       
1120        class sectors_object
1121        {
1122                var $sector_name;
1123                var $sector_context;
1124                var $sector_level;
1125                var $sector_leaf;
1126                var $sectors_list = array();
1127                var $level;
1128               
1129                function sectors_object($sector_name, $sector_context, $sector_level, $sector_leaf)
1130                {
1131                        $this->sector_name = $sector_name;
1132                        $this->sector_context = $sector_context;
1133                        $this->sector_level = $sector_level;
1134                        $this->sector_leaf = $sector_leaf;
1135                }
1136        }       
Note: See TracBrowser for help on using the repository browser.