source: companies/serpro/doc-expressolivre/scripts/distribuicao/arquivos-parceiros/login.php @ 903

Revision 903, 37.0 KB checked in by niltonneto, 15 years ago (diff)

Importacao inicial do Expresso do Serpro

Line 
1<?php
2        //Valida a existencia do cookie, antes de grava-lo
3if(isset($_COOKIE['contador']))
4        {
5        $valor_cookie = $_COOKIE['contador'];
6        if($_GET['cd']=='5')
7                {
8                $valor_cookie = $valor_cookie + 1;
9                setcookie("contador", $valor_cookie,0);
10                }
11        }
12        //Cookie inexistente: tenta gravar um
13        else   
14        {
15        if (setcookie("contador", 1,0))
16                //echo "OK, cookie gravado.";
17                $valor_cookie = 1;
18                else
19                //echo "Nao gravou o cookie";
20                $valor_cookie = "9999"; // forca captcha
21        }
22// logout, inicia contador novamente..... 
23if($_GET['cd']=='1')
24        {
25        $valor_cookie = 1;
26        setcookie("contador", 1,0);
27        }
28        /**************************************************************************\
29        * eGroupWare login                                                         *
30        * http://www.egroupware.org                                                *
31        * Originaly written by Dan Kuykendall <seek3r@phpgroupware.org>            *
32        *                      Joseph Engo    <jengo@phpgroupware.org>             *
33        * --------------------------------------------                             *
34        *  This program is free software; you can redistribute it and/or modify it *
35        *  under the terms of the GNU General Public License as published by the   *
36        *  Free Software Foundation; either version 2 of the License, or (at your  *
37        *  option) any later version.                                              *
38        \**************************************************************************/
39
40$phpgw_info = array();
41$submit = False; // set to some initial value
42$GLOBALS['phpgw_info']['flags'] = array(
43        'disable_Template_class' => True,
44        'login'                  => True,
45        'currentapp'             => 'login',
46        'noheader'               => True
47);
48if(file_exists('./header.inc.php'))
49        {
50        include('./header.inc.php');
51        if ($GLOBALS['phpgw_info']['server']['use_https'] > 0)
52                {
53                if ($_SERVER['HTTPS'] != 'on')
54                        {
55                        Header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
56                        exit;
57                        }
58                if($GLOBALS['phpgw_info']['server']['certificado']==1)
59                        {
60                        require_once('./seguranca/certificado.php');                     
61                        $GLOBALS['certificado'] = new certificado;
62                        }
63                }
64        if(function_exists('CreateObject'))
65                {
66                $GLOBALS['phpgw']->session = CreateObject('phpgwapi.sessions');
67                }
68                else
69                {
70                Header('Location: setup/index.php');
71                exit;
72                }
73        }
74        else
75        {
76        Header('Location: setup/index.php');
77        exit;
78        }
79$GLOBALS['phpgw_info']['login_template_set'] = 'serpro';
80$GLOBALS['phpgw_info']['server']['template_dir'] = PHPGW_SERVER_ROOT . '/phpgwapi/templates/' . $GLOBALS['phpgw_info']['login_template_set'];
81$tmpl = CreateObject('phpgwapi.Template', $GLOBALS['phpgw_info']['server']['template_dir']);
82// read the images from the login-template-set, not the (maybe not even set) users template-set
83$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set'] = $GLOBALS['phpgw_info']['login_template_set'];
84// This is used for system downtime, to prevent new logins.
85if($GLOBALS['phpgw_info']['server']['deny_all_logins'])
86        {
87        $deny_msg=lang('Oops! You caught us in the middle of system maintainance.<br/>
88        Please, check back with us shortly.');
89        $tmpl->set_file(array
90        (
91                'login_form' => 'login_denylogin.tpl'
92        ));
93        $tmpl->set_var('template_set','default');
94        $tmpl->set_var('deny_msg',$deny_msg);
95        $tmpl->pfp('loginout','login_form');
96        exit;
97        }
98$tmpl->set_file(array('login_form' => 'login.tpl'));
99// !! NOTE !!
100// Do NOT and I repeat, do NOT touch ANYTHING to do with lang in this file.
101// If there is a problem, tell me and I will fix it. (jengo)
102// whoooo scaring
103
104if($GLOBALS['phpgw_info']['server']['usecookies'] == True)
105        {
106        $GLOBALS['phpgw']->session->phpgw_setcookie('serverID', '1024');
107        //GLOBALS['phpgw']->session->phpgw_setcookie('eGroupWareLoginTime', time());
108        }
109
110/*
111        if($_GET['cd'] != 10 && $GLOBALS['phpgw_info']['server']['usecookies'] == False)
112        {
113                $GLOBALS['phpgw']->session->setcookie('sessionid');
114                $GLOBALS['phpgw']->session->setcookie('kp3');
115                $GLOBALS['phpgw']->session->setcookie('domain');
116        }
117*/
118
119/* This is not working yet because I need to figure out a way to clear the $cd =1
120        if(isset($_SERVER['PHP_AUTH_USER']) && $_GET['cd'] == '1')
121        {
122                Header('HTTP/1.0 401 Unauthorized');
123                Header('WWW-Authenticate: Basic realm="phpGroupWare"');
124                echo 'You have to re-authentificate yourself';
125                exit;
126        }
127*/
128
129function check_logoutcode($code)
130        {
131                switch($code)
132                {
133                        case 1:
134                                return lang('You have been successfully logged out');
135                                break;
136                        case 2:
137                                return lang('Sorry, your login has expired');
138                                break;
139                        case 4:
140                                return lang('Cookies are required to login to this site.');
141                                break;
142                        case 5:
143                                return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
144                                break;
145                        case 200:
146                                return '<font color="FF0000">' . lang('Invalid code') . '</font>';
147                                break;                         
148                        case 202:
149                                return '<font color="FF0000">' . lang('Account is expired') . '</font>';
150                                break; 
151                        case 203:
152                                return '<font color="FF0000">' . lang('New Password and Confirm Password doesnt are equal') . '</font>';
153                                break;         
154                        case 204:
155                                return '<font color="FF0000">' . lang('New Password and Current Password are similar') . '</font>';
156                                break;
157                        case 205:
158                                return '<font color="FF0000">' . lang('Your password must contain %1 or more letters', $GLOBALS['phpgw_info']['server']['num_letters_userpass']) . '</font>';
159                                break;
160                        case 206:
161                                return '<font color="FF0000">' . lang('Your password is very simple, use numbers, uppercase, lowercase and special characters') . '</font>';
162                                break;
163                        case 207:
164                                return '<font color="FF0000">' . lang('Your password contains characters not allowed') . '</font>';
165                                break; 
166                        case 208:
167                                return '<font color="FF0000">' . lang('New password with more than three consecutives equals caracteres') . '</font>';
168                                break;                                         
169                        case 209:
170                                return '<font color="0000FF">' . lang('password has been updated') . '</font>';
171                                break;                         
172                        case 98:
173                                return '<font color="FF0000">' . lang('Account is expired') . '</font>';
174                                break;
175                        case 99:
176                                return '<font color="FF0000">' . lang('Blocked, too many attempts') . '</font>';
177                                break;
178                        case 10:
179                                $GLOBALS['phpgw']->session->phpgw_setcookie('sessionid');
180                                $GLOBALS['phpgw']->session->phpgw_setcookie('kp3');
181                                $GLOBALS['phpgw']->session->phpgw_setcookie('domain');
182
183                                //fix for bug php4 expired sessions bug
184                                if($GLOBALS['phpgw_info']['server']['sessions_type'] == 'php4')
185                                {
186                                        $GLOBALS['phpgw']->session->phpgw_setcookie(PHPGW_PHPSESSID);
187                                }
188
189                                return '<font color="#FF0000">' . lang('Your session could not be verified.') . '</font>';
190                                break;
191                        default:
192                                return '&nbsp;';
193                }
194        }
195       
196        /* Program starts here */
197
198
199if($GLOBALS['phpgw_info']['server']['auth_type'] == 'http' && isset($_SERVER['PHP_AUTH_USER']))
200        {
201        $submit = True;
202        $login  = $_SERVER['PHP_AUTH_USER'];
203        $passwd = $_SERVER['PHP_AUTH_PW'];
204        $passwd_type = 'text';
205        }
206        else
207        {
208        $passwd = $_POST['passwd'];
209        $passwd_type = $_POST['passwd_type'];
210        }
211
212        # Apache + mod_ssl style SSL certificate authentication
213        # Certificate (chain) verification occurs inside mod_ssl
214        //$GLOBALS['phpgw_info']['server']['auth_type'] = 'sqlssl';
215
216if($GLOBALS['phpgw_info']['server']['auth_type'] == 'sqlssl' && isset($_SERVER['SSL_CLIENT_S_DN']) && !isset($_GET['cd']))
217        {
218                # an X.509 subject looks like:
219                # /CN=john.doe/OU=Department/O=Company/C=xx/Email=john@comapy.tld/L=City/
220                # the username is deliberately lowercase, to ease LDAP integration
221                $sslattribs = explode('/',$_SERVER['SSL_CLIENT_S_DN']);
222                # skip the part in front of the first '/' (nothing)
223                //$sslattributes['Email'] = $GLOBALS['certificado']->dados['email'];
224        while($sslattrib = next($sslattribs))
225                {
226                list($key,$val) = explode('=',$sslattrib);
227                $sslattributes[$key] = $val;
228                }
229        if(isset($sslattributes['Email']))
230                {
231                $submit = True;
232                # login will be set here if the user logged out and uses a different username with
233                # the same SSL-certificate.
234                if(!isset($_POST['login'])&&isset($sslattributes['Email']))
235                        {
236                        $login = $sslattributes['Email'];
237                        # not checked against the database, but delivered to authentication module
238                        $passwd = $_SERVER['SSL_CLIENT_S_DN'];
239                        }
240                }
241        unset($key);
242        unset($val);
243        unset($sslattributes);
244        }
245$ldap_info="";
246if(isset($passwd_type) || $_POST['submitit_x'] || $_POST['submitit_y'] || $submit)
247        {
248        // Primeiro testa o captcha....se houver......
249        if( $GLOBALS['phpgw_info']['server']['captcha']==1)
250                {
251                if(isset($_POST['codigo']))
252                        {
253                        if ($_SESSION['CAPTCHAString'] != strtoupper($_POST['codigo']))
254                                {
255                                if (isset($_POST['npasswd']))
256                                        {
257                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=200&ts=202'));
258                                        }
259                                        else
260                                        {
261                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=200'));
262                                        }
263                                }
264                        unset($_SESSION['CAPTCHAString']);
265                        }
266                }
267        //Faz uma busca inicial por atributos no ldap para que os resultados sejam utilizados pelo restante do programa
268        //Utilizando um diretorio corporativo, o dn do usuario pode estar localizado em qualquer ramo do diretorio
269        //system('echo "Login: bind em ldap" >> /tmp/controle');
270        $common = CreateObject('phpgwapi.common');
271        $ldap_conn = $common->ldapConnect(); //bind como Admin para buscar o atributo de expiracao e o dn do usuario
272        if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
273                {
274                $justthese = array($GLOBALS['phpgw_info']['server']['atributoexpiracao']);
275                }
276                else
277                {
278                $justthese = array("phpgwaccountexpires");
279                }
280        $filter="(&(phpgwAccountType=u)(uid=".$_POST['user']."))";
281        $ldap_search = ldap_search($ldap_conn, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
282        $ldap_info  = ldap_get_entries($ldap_conn, $ldap_search);
283        ldap_close($ldap_conn);
284        // Testa os cpos de troca de senha, se existem
285        if($_POST['npasswd'] || $_POST['cnpasswd'])
286                {
287                // Default number of letters = 8
288                if (!$GLOBALS['phpgw_info']['server']['num_letters_userpass'])
289                        $GLOBALS['phpgw_info']['server']['num_letters_userpass'] = 8;
290                        // Default number of special letters = 1
291                        if (!$GLOBALS['phpgw_info']['server']['num_special_letters_userpass'])
292                        $GLOBALS['phpgw_info']['server']['num_special_letters_userpass'] = 1;               
293                        if(strlen($_POST['npasswd']) < $GLOBALS['phpgw_info']['server']['num_letters_userpass'])
294                                {
295                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=205&ts=202'));
296                                }
297                        // nova senha e confirma nova senha devem ser iguais ...       
298                        if($_POST['npasswd']  != $_POST['cnpasswd'])
299                                {
300                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=203&ts=202'));
301                                }
302                        if (!(ereg ("(^[a-zA-Z_.\-\!@#$%&*+=|]*)$", $_POST['npasswd'] ) or
303                                ereg ("(^[0-9_.\-\!@#$%&*+=|]*)$", $_POST['npasswd'] ) or
304                                ereg ("(^[a-zA-Z0-9]*)$", $_POST['npasswd'] )  or                           
305                                ereg ("(^[a-zA-Z0-9_.\-\!@#$%&*+=|]*)$", $_POST['npasswd'] )))
306                                {                       
307                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=207&ts=202'));
308                                }       
309                        for ($j=0 ; $j<(strlen($_POST['npasswd'])-2); $j++)     
310                                {
311                                if ($_POST['npasswd'][$j]==$_POST['npasswd'][$j+1] && $_POST['npasswd'][$j]==$_POST['npasswd'][$j+2])
312                                        {
313                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=208&ts=202'));
314                                        break;
315                                        }
316                                }
317                        $similar=false;                         
318                        for ($j=0 ; $j<8; $j++)
319                                {
320                                        for ($k=0 ; $k<8; $k++)
321                                                {
322                                                if (similar_text(substr($_POST['passwd'],$j,3),substr($_POST['npasswd'],$k,3))>2)
323                                                        {
324                                                        $similar=true;
325                                                        }
326                                                }
327                                }
328                        // a nova senha e a senha atual nao podem ser "similares" ...           
329                        if ($similar || $_POST['passwd']  == $_POST['npasswd'])
330                                {
331                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=204&ts=202'));
332                                }
333                        // complexidade da senha
334                        $passcomplex=0;
335                        if (ereg('[a-zA-Z]',$_POST['npasswd'])) {$passcomplex=$passcomplex+1;}
336                        if (ereg('[0-9]',$_POST['npasswd'])) {$passcomplex=$passcomplex+1;}
337                        if (ereg('[^0-9a-zA-Z]',$_POST['npasswd'])) {$passcomplex=$passcomplex+1;}
338                        if ($passcomplex < 2)
339                                {
340                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=206&ts=202'));
341                                }
342                        //Tentando fazer bind com o dn do usuario
343                        $ldap_conn = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
344                        if (!$ldap_conn)
345                                {
346                                printf("<b>Error: Can't bind to LDAP server!");
347                                die;
348                                }
349                        $dn=$ldap_info[0]['dn'];
350                        //system('echo "'.ldap_errno($ldap_conn).'" >>/tmp/controle');
351                        //Tenta fazer bind no diretorio, se nao conseguir, verifica se a negacao de autenticacao foi por causa de uma expiracao de senhas
352                        //system('echo "Dn para bind: '.$ldap_info[0]['dn'].'" >>/tmp/controle');
353                        if (!ldap_bind($ldap_conn,$ldap_info[0]['dn'],$_POST['passwd']))
354                                {
355                                //Verificando se a negacao de bind foi proveniente de uma expiracao de senha
356                                //system('echo "NAO conseguiu dar bind" >>/tmp/controle');
357                                $now=time();
358                                //Verificando se a senha esta expirada
359                                $expired=false;
360                                if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
361                                        {
362                                        //system('echo "Atributo de expiracao configurado." >>/tmp/controle');
363                                        //system('echo "now: '.$now.'" >>/tmp/controle');
364                                        //system('echo "atributo de expiracao: '.strtotime($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0]).'" >>/tmp/controle');
365                                        //if (strtotime($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0])<$now)
366                        system('echo "chegou" >>/tmp/controle');
367                        if (($ldap_info[0]["phpgwaccountexpires"][0]!="-1")&&(strtotime($ldap_info[0]["phpgwaccountexpires"][0])<$now))
368                                                {
369                                                //system('echo "Encontrou atributo expirado" >>/tmp/controle');
370                                                $expired=true;
371                                                }
372                                        }
373                                        else
374                                        {
375
376                                        //Se o atributo de expiracao nao estiver configurado pressupoe que eh unixtime (phpgwaccountexpires)
377                        if (($ldap_info[0]["phpgwaccountexpires"][0]!="-1")&&(strtotime($ldap_info[0]["phpgwaccountexpires"][0])<$now))
378                                                {
379                                                //system('echo "Encontrou atributo expirado - phpgwaccoutexpires" >>/tmp/controle');
380                                                $expired=true;
381                                                }
382                                        }
383                                if ($expired)
384                                        {
385                                        //A negacao de bind proveio de uma expiracao de senhas.
386                                        //Providencia a troca de senhas e, se configurado, também o ajuste do atributo de expiracao.
387                                        //system('echo "vai chamar o change_password" >>/tmp/controle');
388                                        if($GLOBALS['phpgw']->auth->change_password_user($passwd, $_POST['npasswd'],$dn,true))
389                                                {
390                                                //A troca de senhas funcionou
391                                                //system('echo "Login: troca de senhas OK" >>/tmp/controle');
392                                                if($GLOBALS['phpgw_info']['server']['diretorioescravo'])
393                                                        {
394                                                        //Tempo necessario para que o slave receba a atualizacao.
395                                                        sleep(1);
396                                                        }
397                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/logout.php?cd=209');
398                                                }
399                                                else
400                                                {
401                                                //Direciona para senha incorreta na tela de troca de senhas
402                                                //system('echo "Login: troca de senhas PROBLEMA" >>/tmp/controle');
403                                                $GLOBALS['phpgw']->redirect("" . '/login.php?cd=5&ts=202');
404                                                }
405                                        }
406                                        else
407                                        {
408                                        //A senha digitada estava incorreta
409                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=5&ts=202');
410                                        }
411                                }
412                                else
413                                {
414                                //Usuario executou autenticacao no diretorio - a expiracao so pode ter vindo de uma politica de expiracao do proprio expresso
415                                //system('echo "SIM conseguiu dar bind" >>/tmp/controle');
416                                if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
417                                        {
418                                        //Se a politica de senhas for do Expresso eh necessario verificar se o usuario estah expirado
419                                        $now=time();
420                                        $common1 = CreateObject('phpgwapi.common');
421                                        $ldap_conn1 = $common1->ldapConnect();
422                                        if ($GLOBALS['phpgw_info']['server']['num_days_pwd_validate'])
423                                                {
424                                                $aux=$GLOBALS['phpgw_info']['server']['num_days_pwd_validate'];
425                                                }
426                                                else
427                                                {
428                                                $aux=90;
429                                                }
430                                        //$entry['phpgwaccountexpires'] = $now + ($aux * 86400);
431                                        if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
432                                                {
433                                                if(substr($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0],-1,1) == "Z")
434                                                        {
435                                                        if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
436                                                                {       
437                                                                //quando a data de expiracao estah no formato yyyymmddhhmmssZ
438                                                                $entry[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = strftime("%Y%m%d%H%M%SZ", $now + ($aux * 86400));
439                                                                }
440                                                        }
441                                                        else
442                                                        {
443                                                        if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
444                                                                {
445                                                                //Outro atributo ldap que, assim como o phpgwaccounttype, tambem contem hora em formato unix
446                                                                $entry[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = $now + ($aux * 86400);
447                                                                }
448                                                        }
449                                                }
450                                                else
451                                                {
452                                                //Se a política for no diretorio nao precisa alterar o atributo de expiracao
453                                                if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
454                                                        {
455                                                        $entry['phpgwaccountexpires'] = $now + ($aux * 86400);
456                                                        }
457                                                }
458                                        ldap_mod_replace($ldap_conn1,$ldap_info[0]['dn'], $entry);
459                                        }
460                                }
461                }
462       
463        if ($ldap_info['count'] != 0)
464                {
465                $_POST['login'] = $_POST['user'];
466                }
467        ldap_close($ldap_conn);
468        if(getenv('REQUEST_METHOD') != 'POST' && $_SERVER['REQUEST_METHOD'] != 'POST' &&
469                        !isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['SSL_CLIENT_S_DN']))
470                {
471                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=5'));
472                }
473        if($submit == false)
474                {
475                $login = $_POST['login'];
476                }
477        if(strstr($login,'@') === False && isset($_POST['logindomain']))
478                {
479                $login .= '@' . $_POST['logindomain'];
480                }
481                elseif(!isset($GLOBALS['phpgw_domain'][$GLOBALS['phpgw_info']['user']['domain']]))
482                        {
483                        $login .= '@'.$GLOBALS['phpgw_info']['server']['default_domain'];
484                        }
485        //--------------------------------------------------------------------------------------------------
486        //LOGIN
487        //--------------------------------------------------------------------------------------------------
488        //echo "Usuario ==> ".$login."    senha ==> ".$passwd;
489        //system('echo "Login: tentou criar sessao" >> /tmp/controle');
490        //Tantando criar a sessao
491        $GLOBALS['sessionid'] = $GLOBALS['phpgw']->session->create(strtolower($login),$passwd,$passwd_type,'u');
492        if(!isset($GLOBALS['sessionid']) || ! $GLOBALS['sessionid'])
493                {
494                //A sessao nao pode ser criada. Verificando quais os possiveis motivos
495                //system('echo "Nao tem sessao" >> /tmp/controle');
496                if ($GLOBALS['phpgw']->session->cd_reason == 99)
497                        {
498                        //fazendo o redirecionamento para o caso de bloqueio de por excesso de tentativas erradas
499                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=' . $GLOBALS['phpgw']->session->cd_reason.'&ts=99');     
500                        }
501                        else
502                        {
503                        //Verifica se o codigo de erro ldap 49, que o session traduz para cd_reason=5, é proveniente de uma expiracao de senhas. Neste caso, mesmo se o usuário digitar a senha errada, devolve-se a informacao de expiracao. O código de erro  "5" também é retornado quando não é encontrado o usuário na base ldap
504                        if ($GLOBALS['phpgw']->session->cd_reason == 5)
505                                {
506                                //system('echo "Retornou erro 49" >>/tmp/controle');
507                                //Buscando o atributo de expiracao no ldap
508                                $lc = $common->ldapConnect();
509                                if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
510                                        {
511                                        $justthese = array("uid",$GLOBALS['phpgw_info']['server']['atributoexpiracao']);
512                                        }
513                                $filter="(&(phpgwAccountType=u)(uid=".$_POST['user']."))";
514                                $ldap_search = ldap_search($lc, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
515                                $ldap_info = ldap_get_entries($lc, $ldap_search);
516                                ldap_close($lc);
517                                //Verificando se a senha está expirada
518                                if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
519                                        {
520                                        //Analisa a expiracao atraves do tempo da maquina
521                                        $now=time();
522                                        //Se o atributo de expiracao nao existir pode ser por causa da nao existencia do usuario no ldap
523                                        //Verifica o tipo do formato do tempo de expiracao para concluir se a senha está expirada ou não.
524                                        if (($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0])&&(substr($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0],-1,1) == "Z"))
525                                                {
526                                                if (strtotime($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0] < $now))
527                                                        {
528                                                        //Senha do usuario estah expirada, pressupoe-se que colocou a senha certa, pois o erro do ldap eh o mesmo (49)
529                                                        //system('echo "Detectou expiracao de senhas: " >>/tmp/controle');
530                                                        if(isset($GLOBALS['phpgw_info']['server']['webserver_url']))
531                                                                {
532                                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=98&ts=98');
533                                                                }
534                                                                else
535                                                                {
536                                                                //Entra aqui em duas ocasioes - quando expirado:
537                                                                        //login errado na tela sem troca de senhas
538                                                                        //troca de senhas com a senha atual errada
539                                                                if($_POST['npasswd'])
540                                                                        {
541                                                                        //Nao logou porque o usuario estah com a senha expirada - troca de senhas
542                                                                        //Pode ter errado a senha também.
543                                                                        //system('echo "NAO Achou a url - tela troca de senhas: " >>/tmp/controle');
544                                                                        $GLOBALS['phpgw']->redirect_link("" . '/logout.php?cd=5&ts=5');
545                                                                        }
546                                                                        else
547                                                                        {
548                                                                        //Nao logou porque o usuario estah com a senha expirada - tela inicial
549                                                                        //Para o caso de usuario que tenta se logar na tela inicial com a senha expirada
550                                                                        //system('echo "NAO Achou a url - tela inicial: " >>/tmp/controle'); //funciona
551                                                                        $GLOBALS['phpgw']->redirect_link("" . '/login.php?cd=98&ts=98'); //funciona
552                                                                        }
553                                                                }
554                                                        }
555                                                        else
556                                                        {
557                                                        //senha do usuario nao estah expirada e, como o ldap deu login invalido, ocorreu erro de senha
558                                                        //system('echo "NAO estah expirado: " >>/tmp/controle');
559                                                        $GLOBALS['phpgw']->redirect_link("" . '/login.php?cd=5&ts=5');
560                                                        }
561                                                }
562                                                else
563                                                {
564                                                //Caso do atributo de expiracao de senhas estar no formato unixtime
565                                                if (($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0])&&($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0] < $now)&&($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0]!="-1"))
566                                                        {
567                                                        //Senha do usuario estah expirada, pressupoe-se que colocou a senha certa, pois o erro do ldap eh o mesmo (49)
568                                                        //system('echo "Detectou expiracao de senhas: " >>/tmp/controle');
569                                                        if(isset($GLOBALS['phpgw_info']['server']['webserver_url']))
570                                                                {
571                                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=98&ts=98');
572                                                                }
573                                                                else
574                                                                {
575                                                                //Entra aqui em duas ocasioes - quando expirado:
576                                                                        //login errado na tela sem troca de senhas
577                                                                        //troca de senhas com a senha atual errada
578                                                                if($_POST['npasswd'])
579                                                                        {
580                                                                        //Nao logou porque o usuario estah com a senha expirada - troca de senhas
581                                                                        //Pode ter errado a senha também.
582                                                                        //system('echo "NAO Achou a url - tela troca de senhas: " >>/tmp/controle');
583                                                                        $GLOBALS['phpgw']->redirect_link("" . '/logout.php?cd=5&ts=5');
584                                                                        }
585                                                                        else
586                                                                        {
587                                                                        //Nao logou porque o usuario estah com a senha expirada - tela inicial
588                                                                        //Para o caso de usuario que tenta se logar na tela inicial com a senha expirada
589                                                                        //system('echo "NAO Achou a url - tela inicial: " >>/tmp/controle'); //funciona
590                                                                        $GLOBALS['phpgw']->redirect_link("" . '/login.php?cd=98&ts=98'); //funciona
591                                                                        }
592                                                                }
593                                                        }
594                                                        else
595                                                        {
596                                                        //senha do usuario nao estah expirada e, como o ldap deu login invalido, ocorreu erro de senha
597                                                        //system('echo "NAO estah expirado: " >>/tmp/controle');
598                                                        $GLOBALS['phpgw']->redirect_link("" . '/login.php?cd=5&ts=5');
599                                                        }
600                                                }
601                                        }
602                                }
603                                else
604                                {
605                                if ($GLOBALS['phpgw']->session->cd_reason == 99)
606                                        {
607                                        //fazendo o redirecionamento para o caso de bloqueio de por excesso de tentativas erradas
608                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=' . $GLOBALS['phpgw']->session->cd_reason.'&ts=99');     
609                                        }
610                                        else
611                                        {
612                                        // trocasenha soh vai existir qdo o form for gerado via chamada anterior com com "cd=202"
613                                        if($_POST['cdx']=='202' )
614                                                {
615                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=' . $GLOBALS['phpgw']->session->cd_reason.'&ts=202');
616                                                }
617                                                else
618                                                {
619                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=' . $GLOBALS['phpgw']->session->cd_reason);
620                                                }
621                                        }
622                                }
623                        }
624                }
625                else
626                {
627                //Realiza a troca de senhas caso a política seja local, ou seja, caso o diretorio continue autenticando o usuario com a senha expirada.
628                //system('echo "Encontrou número de sessao" >> /tmp/controle');
629                // Atencao: se existir o cpo "npasswd"  providencia a troca da senha do usuario....
630                if($_POST['npasswd'])
631                        {
632                        //system('echo "entrou no change" >> /tmp/controle');
633                        //$GLOBALS['phpgw']->auth->change_password($passwd, $_POST['npasswd']);
634                        if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
635                                {
636                                $GLOBALS['phpgw']->auth->change_password_user($passwd, $_POST['npasswd'],$dn,false);
637                                }
638                                else
639                                {
640                                $GLOBALS['phpgw']->auth->change_password_user($passwd, $_POST['npasswd'],$dn,true);
641                                }
642                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/logout.php?cd=209');
643                        }
644                if ($_POST['lang'] && preg_match('/^[a-z]{2}(-[a-z]{2}){0,1}$/',$_POST['lang']) &&
645                        $_POST['lang'] != $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'])
646                        {
647                        $GLOBALS['phpgw']->preferences->add('common','lang',$_POST['lang'],'session');
648                        }
649                if(!$GLOBALS['phpgw_info']['server']['disable_autoload_langfiles'])
650                        {
651                        $GLOBALS['phpgw']->translation->autoload_changed_langfiles();
652                        }
653                $forward = isset($_GET['phpgw_forward']) ? urldecode($_GET['phpgw_forward']) : @$_POST['phpgw_forward'];
654                if (!$forward)
655                        {
656                        $extra_vars['cd'] = 'yes';
657                        $forward = '/home.php';
658                        }
659                else
660                        {
661                        list($forward,$extra_vars) = explode('?',$forward,2);
662                        }
663                if ($GLOBALS['phpgw_info']['server']['use_https'] != 2)
664                        {
665                        $forward = 'http://'.$_SERVER['HTTP_HOST'].($GLOBALS['phpgw']->link($forward.'?cd=yes'));
666                        echo "<script language='Javascript1.3'>location.href='".$forward."'</script>";
667                        }
668                else
669                        {
670                        $GLOBALS['phpgw']->redirect_link($forward,$extra_vars);
671                        }
672                }
673        }
674        else
675        {
676        // !!! DONT CHANGE THESE LINES !!!
677        // If there is something wrong with this code TELL ME!
678        // Commenting out the code will not fix it. (jengo)
679        if(isset($_COOKIE['last_loginid']))
680                {
681                $accounts = CreateObject('phpgwapi.accounts');
682                $prefs = CreateObject('phpgwapi.preferences', $accounts->name2id($_COOKIE['last_loginid']));
683
684                if($prefs->account_id)
685                        {
686                        $GLOBALS['phpgw_info']['user']['preferences'] = $prefs->read_repository();
687                        }
688                }
689        if ($_GET['lang'])
690                {
691                $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $_GET['lang'];
692                }
693        elseif(!isset($_COOKIE['last_loginid']) || !$prefs->account_id)
694                {
695                // If the lastloginid cookies isn't set, we will default to the first language,
696                // the users browser accepts.
697                list($lang) = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
698                /*
699                if(strlen($lang) > 2)
700                {
701                        $lang = substr($lang,0,2);
702                       
703                }
704                */
705                $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $lang;
706                }
707        #print 'LANG:' . $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] . '<br>';
708        $GLOBALS['phpgw']->translation->init(); // this will set the language according to the (new) set prefs
709        $GLOBALS['phpgw']->translation->add_app('login');
710        $GLOBALS['phpgw']->translation->add_app('loginscreen');
711        if(lang('loginscreen_message') == 'loginscreen_message*')
712                {
713                $GLOBALS['phpgw']->translation->add_app('loginscreen','en');    // trying the en one
714                }
715        if(lang('loginscreen_message') != 'loginscreen_message*')
716                {
717                $tmpl->set_var('lang_message',stripslashes(lang('loginscreen_message')));
718                }
719        }
720if($GLOBALS['phpgw_info']['server']['use_prefix_organization'])
721        {
722        $organization_select = "<tr><td width=\"66\" class=\"loginLabel\">";
723        $organization_select .= lang("organization").":</td>";
724        $organization_select .="<td width=\"135\">";                                                                                   
725        $organization_select .="<select name=\"organization\">\n";             
726        $obj_organization = CreateObject('phpgwapi.sector_search_ldap');
727        $organizations = $obj_organization->organization_search($GLOBALS['phpgw_info']['server']['ldap_context']);
728        for ($i=0; $i<count($organizations); $i++)
729                {
730                $tmp_array[strtolower($organizations[$i])] = $organizations[$i];       
731                }
732        $arrayOrganization = $tmp_array;               
733        ksort($arrayOrganization);
734        foreach($arrayOrganization as $organization_name => $organization_vars)
735                {
736                $organization_select .= '<option value="' . $organization_name . '"';
737                if($organization_name == $_COOKIE['last_organization'])
738                        {
739                        $organization_select .= ' selected';
740                        }
741                $organization_select .= '>' . $organization_vars . "</option>\n";
742                }
743        $organization_select .= "</select>\n";
744        $organization_select .="</td><td>&nbsp;</td></tr>";
745        $tmpl->set_var('select_organization',$organization_select);
746        }
747$domain_select = '&nbsp;';
748$last_loginid = $_COOKIE['last_loginid'];
749if($GLOBALS['phpgw_info']['server']['show_domain_selectbox'])
750        {
751        $domain_select = "<select name=\"logindomain\">\n";
752        foreach($GLOBALS['phpgw_domain'] as $domain_name => $domain_vars)
753                {
754                $domain_select .= '<option value="' . $domain_name . '"';
755                if($domain_name == $_COOKIE['last_domain'])
756                        {
757                        $domain_select .= ' selected';
758                        }
759                $domain_select .= '>' . $domain_name . "</option>\n";
760                }
761        $domain_select .= "</select>\n";
762        }
763        elseif($last_loginid !== '')
764                {
765                reset($GLOBALS['phpgw_domain']);
766                list($default_domain) = each($GLOBALS['phpgw_domain']);
767                if($_COOKIE['last_domain'] != $default_domain && !empty($_COOKIE['last_domain']))
768                        {
769                        $last_loginid .= '@' . $_COOKIE['last_domain'];
770                        }
771                }
772$tmpl->set_var('select_domain',$domain_select);
773foreach($_GET as $name => $value)
774        {
775        if(ereg('phpgw_',$name))
776                {
777                $extra_vars .= '&' . $name . '=' . urlencode($value);
778                }
779        }
780if($extra_vars)
781        {
782        $extra_vars = '?' . substr($extra_vars,1);
783        }
784
785        /********************************************************\
786        * Check is the registration app is installed, activated  *
787        * And if the register link must be placed                *
788        \********************************************************/
789       
790$cnf_reg = createobject('phpgwapi.config','registration');
791$cnf_reg->read_repository();
792$config_reg = $cnf_reg->config_data;
793
794if($config_reg[enable_registration]=='True' && $config_reg[register_link]=='True')
795        {
796        $reg_link='&nbsp;<a href="registration/">'.lang('Not a user yet? Register now').'</a><br/>';
797        }
798
799$GLOBALS['phpgw_info']['server']['template_set'] = $GLOBALS['phpgw_info']['login_template_set'];
800$tmpl->set_var('register_link',$reg_link);
801$tmpl->set_var('charset',$GLOBALS['phpgw']->translation->charset());
802$tmpl->set_var('login_url', $GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php' . $extra_vars);
803$tmpl->set_var('registration_url',$GLOBALS['phpgw_info']['server']['webserver_url'] . '/registration/');
804$tmpl->set_var('version',$GLOBALS['phpgw_info']['server']['versions']['phpgwapi']);
805$tmpl->set_var('cd',check_logoutcode($_GET['cd']));
806$tmpl->set_var('cookie',$last_loginid);
807$tmpl->set_var('lang_password',lang('password'));
808$tmpl->set_var('lang_login',lang('login'));
809if ($_GET['cd'] == '202' || $_GET['cd'] == '98' || $_GET['ts']=='202' || $_GET['cdx']=='202')
810        {
811        $tmpl->set_var('cdx','202');
812        }   
813// Alterado para utilizar o certificado digital...
814if(!$GLOBALS['certificado']->apresentado)
815        {
816        $tmpl->set_var('lang_username',lang('username'));
817        $tmpl->set_var('CPF','<input name="user" size="18">');
818        if($GLOBALS['phpgw_info']['server']['captcha'])
819                {
820                if($valor_cookie > $GLOBALS['phpgw_info']['server']['num_badlogin'])
821                        {
822                        $tmpl->set_var('captcha','<tr border="1"><td  nowrap width="155" class="codigoLabel" ><img src="./seguranca/captcha.php" title="'.lang('Security code').'" alt="'.lang('Security code').'" width="75"  ><b>&nbsp;&nbsp;---------></b></td> <td width="105"><input name="codigo" type="text" size="18"  title="'.lang('Type the security code').'"></td> </tr>');
823                        }
824                }
825        }
826        else
827        {
828        $tmpl->set_var('nome','<b>'.lang('Certificate owner').':</b> '.$GLOBALS['certificado']->dados['NOME']);
829        $tmpl->set_var('CPF','<input type="hidden" name="user" size="18" value="'.$GLOBALS['certificado']->dados['CPF'].'" READONLY>');
830        }
831if ($_GET['cd'] == '202' || $_GET['cd'] == '98'  || $_GET['ts']=='202' || $_GET['cdx']=='202')
832        {
833        $tmpl->set_var('trocasenha','<tr>
834                                                <td width="140" class="loginLabel" >'.lang('New Password').'</td>
835                                                <td width="105"><input name="npasswd" type="password" size="18" ><br></td>
836                                                </tr>
837                                                        <tr>
838                                                <td width="155" class="loginLabel" >'.lang('Confirm New Password').'</td>
839                                                <td width="105"><input name="cnpasswd" type="password" size="18" ><br></td>
840                                                        </tr>');
841        }
842$tmpl->set_var('website_title', $GLOBALS['phpgw_info']['server']['site_title']);
843$tmpl->set_var('template_set',$GLOBALS['phpgw_info']['login_template_set']);
844$tmpl->set_var('bg_color',($GLOBALS['phpgw_info']['server']['login_bg_color']?$GLOBALS['phpgw_info']['server']['login_bg_color']:'FFFFFF'));
845$tmpl->set_var('login_caixa_bg_color',($GLOBALS['phpgw_info']['server']['login_caixa_bg_color']?$GLOBALS['phpgw_info']['server']['login_caixa_bg_color']:'FFFFFF'));
846$tmpl->set_var('bg_color_title',($GLOBALS['phpgw_info']['server']['login_bg_color_title']?$GLOBALS['phpgw_info']['server']['login_bg_color_title']:'486591'));
847if (substr($GLOBALS['phpgw_info']['server']['login_logo_file'],0,4) == 'http')
848        {
849        $var['logo_file'] = $GLOBALS['phpgw_info']['server']['login_logo_file'];
850        }
851else
852        {
853        $var['logo_file'] = $GLOBALS['phpgw']->common->image('phpgwapi',$GLOBALS['phpgw_info']['server']['login_logo_file']?$GLOBALS['phpgw_info']['server']['login_logo_file']:'');
854        }
855       
856        if (substr($GLOBALS['phpgw_info']['server']['imagem_de_fundo'],0,4) == 'http')
857        {
858        $var['imagem_de_fundo'] = $GLOBALS['phpgw_info']['server']['imagem_de_fundo'];
859        }
860else
861        {
862        #$var['imagem_de_fundo'] = $GLOBALS['phpgw']->common->image('phpgwapi',$GLOBALS['phpgw_info']['server']['imagem_de_fundo']?$GLOBALS['phpgw_info']['server']['imagem_de_fundo']:'back.jpg');
863        $var['imagem_de_fundo'] = $GLOBALS['phpgw']->common->image('phpgwapi',$GLOBALS['phpgw_info']['server']['imagem_de_fundo']);     
864        }
865$var['imagem_de_fundo_exibicao'] = ($GLOBALS['phpgw_info']['server']['imagem_de_fundo_exibicao'] != ''?$GLOBALS['phpgw_info']['server']['imagem_de_fundo_exibicao']:"background-repeat:repeat-x; overflow:auto;overflow-x:hidden;");   
866$var['logo_url'] = $GLOBALS['phpgw_info']['server']['login_logo_url']?$GLOBALS['phpgw_info']['server']['login_logo_url']:'http://www.eGroupWare.org';
867if (substr($var['logo_url'],0,4) != 'http')
868        {
869        $var['logo_url'] = 'http://'.$var['logo_url'];
870        }
871$var['logo_title'] = $GLOBALS['phpgw_info']['server']['login_logo_title']?$GLOBALS['phpgw_info']['server']['login_logo_title']:'www.eGroupWare.org';
872
873 // {logo_imagem}
874//  <a href="{logo_url}" title="{logo_title}" style="text-decoration: none;" target="_blank"><img src="{logo_file}"  border="0" style="margin-top: 5px; witdh: 300px; height: 200px;"/></a>
875if($var['logo_file'] == '')
876{
877  $var['logo_imagem'] = '';
878}
879else
880{
881  $var['logo_imagem'] = '<a href="'.$var['logo_url'].'" title="'.$var['logo_title'].'" style="text-decoration: none;" target="_blank"><img src="'.$var['logo_file'].'"  border="0" style="margin-top: 5px; witdh: 300px; height: 200px;"/></a>';
882}
883$tmpl->set_var($var);
884if (@$GLOBALS['phpgw_info']['server']['login_show_language_selection'])
885        {
886        $select_lang = '<select name="lang" onchange="'."location.href=location.href+(location.search?'&':'?')+'lang='+this.value".'">';
887        $langs = $GLOBALS['phpgw']->translation->get_installed_langs();
888        uasort($langs,'strcasecmp');
889        foreach ($langs as $key => $name)       // if we have a translation use it
890                {
891                $select_lang .= "\n\t".'<option value="'.$key.'"'.($key == $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] ? ' selected="1"' : '').'>'.$name.'</option>';
892                }
893        $select_lang .= "\n</select>\n";
894        $tmpl->set_var(array(
895                'lang_language' => lang('Language'),
896                'select_language' => $select_lang,
897        ));
898        }
899        else
900        {
901        $tmpl->set_block('login_form','language_select');
902        $tmpl->set_var('language_select','');
903        }
904$tmpl->set_var('autocomplete', ($GLOBALS['phpgw_info']['server']['autocomplete_login'] ? 'autocomplete="off"' : ''));
905$tmpl->set_var('vserpro','<font color="#9a9a9a" face="Verdana, Arial, Helvetica, sans-serif" size="1">V - '.$GLOBALS['phpgw_info']['server']['versions']['header'].'-'.$GLOBALS['phpgw_info']['server']['versao-Serpro'].'</font>');
906$tmpl->pfp('loginout','login_form');
907?>
Note: See TracBrowser for help on using the repository browser.