source: companies/serpro/mobile/login.php @ 903

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

Importacao inicial do Expresso do Serpro

Line 
1<?php
2
3//Valida a existencia do cookie, antes de grava-lo
4if(isset($_COOKIE['contador']))
5{
6        $valor_cookie = $_COOKIE['contador'];
7        if($_POST['login'] && $_POST['passwd'])
8        {
9                $valor_cookie = $valor_cookie + 1;
10                setcookie("contador", $valor_cookie,0);
11        }
12}
13//Cookie inexistente: tenta gravar um
14else
15{
16        if (setcookie("contador", 1,0))
17                //echo "OK, cookie gravado.";
18                $valor_cookie = 1;
19        else
20               //echo "Nao gravou o cookie";
21               $valor_cookie = "9999"; // forca captcha
22}
23// logout/login, inicia contador novamente.....
24if($_GET['cd']=='1' || $_COOKIE['sessionid'] || $_GET['cd'] == 10)
25{
26        $valor_cookie = 1;
27        setcookie("contador", 1,0);
28}
29//------------------fim do cookie---------------------------
30        //TODO: Trocar name="login" para name="user" no campo username
31        $phpgw_info = array();
32        $submit = False;
33
34        $GLOBALS['phpgw_info']['flags'] = array(
35                'disable_Template_class' => True,
36                'login'                  => True,
37                'currentapp'             => 'login',
38                'currentdir'             => '/mobile',
39                'noheader'               => True
40        );
41
42        include('../header.inc.php');
43        $GLOBALS['sessionid'] = @$_GET['sessionid'] ? $_GET['sessionid'] : @$_COOKIE['sessionid'];
44        if(isset($GLOBALS['sessionid']) && $_GET['cd'] != 10 && $_GET['cd'] != 1)
45                //$GLOBALS['phpgw']->redirect_link($GLOBALS['phpgw_info']['flags']['currentdir'].'/calendar.php');
46                //session_start();
47                $GLOBALS['phpgw']->redirect_link($GLOBALS['phpgw_info']['flags']['currentdir'].'/home.php');
48        if ($GLOBALS['phpgw_info']['server']['use_https'] > 0)  {
49                if ($_SERVER['HTTPS'] != 'on') {
50                        Header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
51                        exit;
52                }
53        }
54
55        $GLOBALS['phpgw']->session = CreateObject('phpgwapi.sessions');
56        //$GLOBALS['phpgw_info']['server']['template_dir'] = PHPGW_SERVER_ROOT.$GLOBALS['phpgw_info']['flags']['currentdir'].'/templates/'.$GLOBALS['phpgw_info']['login_template_set'];
57        $GLOBALS['phpgw_info']['server']['template_dir'] = PHPGW_SERVER_ROOT.$GLOBALS['phpgw_info']['flags']['currentdir'].'/templates/';
58        $tmpl = CreateObject('phpgwapi.Template', $GLOBALS['phpgw_info']['server']['template_dir']);
59        $GLOBALS['phpgw_info']['user']['preferences']['common']['template_set'] = $GLOBALS['phpgw_info']['login_template_set'];
60        $tmpl->set_file(array('login_form' => 'login.tpl'));
61
62        function check_logoutcode($code) {
63                switch($code) {
64                        case 1:
65                                logout();
66                                return lang('You have been successfully logged out');
67
68                        case 2:
69                                return lang('Sorry, your login has expired');
70
71                        case 4:
72                                return lang('Cookies are required to login to this site.');
73
74                        case 5:
75                                return '<font color="FF0000">' . lang('Bad login or password') . '</font>';
76
77                        case 6:
78                                return '<font color="FF0000">' . lang('Your password has expired, and you do not have access to change it') . '</font>';
79
80                        case 98:
81                                return '<font color="FF0000">' . lang('Account expired') . '</font>';
82
83                        case 99:
84                                return '<font color="FF0000">' . lang('Blocked, too many attempts') . '</font>';
85
86                        case 10:
87                                $GLOBALS['phpgw']->session->phpgw_setcookie('sessionid');
88                                $GLOBALS['phpgw']->session->phpgw_setcookie('kp3');
89                                $GLOBALS['phpgw']->session->phpgw_setcookie('domain');
90                                if($GLOBALS['phpgw_info']['server']['sessions_type'] == 'php4')
91                                {
92                                        $GLOBALS['phpgw']->session->phpgw_setcookie(PHPGW_PHPSESSID);
93                                }
94                                return '<font color="#FF0000">' . lang('Your session could not be verified.') . '</font>';
95                        case 11:
96                                return '<font color="FF0000">' . lang('Invalid code') . '</font>';
97
98                        default:
99                                return '&nbsp;';
100                }
101        }
102
103        if($GLOBALS['phpgw_info']['server']['auth_type'] == 'http' && isset($_SERVER['PHP_AUTH_USER'])) {
104                $submit = True;
105                $login  = $_SERVER['PHP_AUTH_USER'];
106                $passwd = $_SERVER['PHP_AUTH_PW'];
107                $passwd_type = 'text';
108        }
109        else {
110                $passwd = $_POST['passwd'];
111                $passwd_type = $_POST['passwd_type'];
112        }
113//-------------------------------------------------- Adicionado para o Captcha -----------------------------------------------
114        if(isset($passwd_type) || $_POST['submitit_x'] || $_POST['submitit_y'] || $submit) {
115                // Primeiro testa o captcha....se houver......
116                if( $GLOBALS['phpgw_info']['server']['captcha']==1)
117                        {
118                        if(isset($_POST['codigo']))
119                                {
120                                if ($_SESSION['CAPTCHAString'] != strtoupper($_POST['codigo']))
121                                        {
122                                        if (isset($_POST['npasswd']))
123                                                {
124                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link($GLOBALS['phpgw_info']['flags']['currentdir'].'/login.php','cd=11&ts=202'));
125                                                }
126                                                else
127                                                {
128                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link($GLOBALS['phpgw_info']['flags']['currentdir'].'/login.php','cd=11'));
129                                                }
130                                        }
131                                unset($_SESSION['CAPTCHAString']);
132                                }
133                        }
134
135                        /*
136                        //VOLTA DO BLOCO ORIGINAL
137                        if(isset($passwd_type) || $_POST['submitit_x'] || $_POST['submitit_y'] || $submit) {
138                        */
139                                if(getenv('REQUEST_METHOD') != 'POST' && $_SERVER['REQUEST_METHOD'] != 'POST' &&
140                                        !isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['SSL_CLIENT_S_DN'])){
141                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link($GLOBALS['phpgw_info']['flags']['currentdir'].'/login.php','cd=5'));
142                                }
143                                if(!$submit)
144                                        $login = $_POST['login'];
145                                $GLOBALS['sessionid'] = $GLOBALS['phpgw']->session->create(strtolower($login),$passwd,$passwd_type,'u');
146                                if(!isset($GLOBALS['sessionid']) || ! $GLOBALS['sessionid']){
147                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] .$GLOBALS['phpgw_info']['flags']['currentdir'].'/login.php?cd=' . $GLOBALS['phpgw']->session->cd_reason);
148                                 }
149                                 else{
150                                        //$GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] .$GLOBALS['phpgw_info']['flags']['currentdir'].'/calendar.php');
151                                         $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] .$GLOBALS['phpgw_info']['flags']['currentdir'].'/home.php');
152                                 }
153                         /*
154
155                         }//If do bloco original
156                >>> Parte usada no Expresso para alteracao de senha no caso de expiracao
157
158                //Faz uma busca inicial por atributos no ldap para que os resultados sejam utilizados pelo restante do programa
159                //Utilizando um diretorio corporativo, o dn do usuario pode estar localizado em qualquer ramo do diretorio
160                //system('echo "Login: bind em ldap" >> /tmp/controle');
161                $common = CreateObject('phpgwapi.common');
162                $ldap_conn = $common->ldapConnect(); //bind como Admin para buscar o atributo de expiracao e o dn do usuario
163                if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
164                        {
165                        $justthese = array($GLOBALS['phpgw_info']['server']['atributoexpiracao']);
166                        }
167                        else
168                        {
169                        $justthese = array("phpgwaccountexpires");
170                        }
171                $filter="(&(phpgwAccountType=u)(uid=".$_POST['user']."))";
172                $ldap_search = ldap_search($ldap_conn, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
173                $ldap_info  = ldap_get_entries($ldap_conn, $ldap_search);
174                ldap_close($ldap_conn);
175                // Testa os cpos de troca de senha, se existem
176                if($_POST['npasswd'] || $_POST['cnpasswd'])
177                        {
178                        // Default number of letters = 8
179                        if (!$GLOBALS['phpgw_info']['server']['num_letters_userpass'])
180                                $GLOBALS['phpgw_info']['server']['num_letters_userpass'] = 8;
181                                // Default number of special letters = 1
182                                if (!$GLOBALS['phpgw_info']['server']['num_special_letters_userpass'])
183                                $GLOBALS['phpgw_info']['server']['num_special_letters_userpass'] = 1;               
184                                if(strlen($_POST['npasswd']) < $GLOBALS['phpgw_info']['server']['num_letters_userpass'])
185                                        {
186                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=205&ts=202'));
187                                        }
188                                // nova senha e confirma nova senha devem ser iguais ...       
189                                if($_POST['npasswd']  != $_POST['cnpasswd'])
190                                        {
191                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=203&ts=202'));
192                                        }
193                                if (!(ereg ("(^[a-zA-Z_.\-\!@#$%&*+=|]*)$", $_POST['npasswd'] ) or
194                                        ereg ("(^[0-9_.\-\!@#$%&*+=|]*)$", $_POST['npasswd'] ) or
195                                        ereg ("(^[a-zA-Z0-9]*)$", $_POST['npasswd'] )  or                           
196                                        ereg ("(^[a-zA-Z0-9_.\-\!@#$%&*+=|]*)$", $_POST['npasswd'] )))
197                                        {                       
198                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=207&ts=202'));
199                                        }       
200                                for ($j=0 ; $j<(strlen($_POST['npasswd'])-2); $j++)     
201                                        {
202                                        if ($_POST['npasswd'][$j]==$_POST['npasswd'][$j+1] && $_POST['npasswd'][$j]==$_POST['npasswd'][$j+2])
203                                                {
204                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=208&ts=202'));
205                                                break;
206                                                }
207                                        }
208                                $similar=false;                         
209                                for ($j=0 ; $j<8; $j++)
210                                        {
211                                                for ($k=0 ; $k<8; $k++)
212                                                        {
213                                                        if (similar_text(substr($_POST['passwd'],$j,3),substr($_POST['npasswd'],$k,3))>2)
214                                                                {
215                                                                $similar=true;
216                                                                }
217                                                        }
218                                        }
219                                // a nova senha e a senha atual nao podem ser "similares" ...           
220                                if ($similar || $_POST['passwd']  == $_POST['npasswd'])
221                                        {
222                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=204&ts=202'));
223                                        }
224                                // complexidade da senha
225                                $passcomplex=0;
226                                if (ereg('[a-zA-Z]',$_POST['npasswd'])) {$passcomplex=$passcomplex+1;}
227                                if (ereg('[0-9]',$_POST['npasswd'])) {$passcomplex=$passcomplex+1;}
228                                if (ereg('[^0-9a-zA-Z]',$_POST['npasswd'])) {$passcomplex=$passcomplex+1;}
229                                if ($passcomplex < 2)
230                                        {
231                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw']->link('/login.php','cd=206&ts=202'));
232                                        }
233                                //Tentando fazer bind com o dn do usuario
234                                $ldap_conn = ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
235                                if (!$ldap_conn)
236                                        {
237                                        printf("<b>Error: Can't bind to LDAP server!");
238                                        die;
239                                        }
240                                $dn=$ldap_info[0]['dn'];
241                                //system('echo "'.ldap_errno($ldap_conn).'" >>/tmp/controle');
242                                //Tenta fazer bind no diretorio, se nao conseguir, verifica se a negacao de autenticacao foi por causa de uma expiracao de senhas
243                                //system('echo "Dn para bind: '.$ldap_info[0]['dn'].'" >>/tmp/controle');
244                                if (!ldap_bind($ldap_conn,$ldap_info[0]['dn'],$_POST['passwd']))
245                                        {
246                                        //Verificando se a negacao de bind foi proveniente de uma expiracao de senha
247                                        //system('echo "NAO conseguiu dar bind" >>/tmp/controle');
248                                        $now=time();
249                                        //Verificando se a senha esta expirada
250                                        $expired=false;
251                                        if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
252                                                {
253                                                //system('echo "Atributo de expiracao configurado." >>/tmp/controle');
254                                                //system('echo "now: '.$now.'" >>/tmp/controle');
255                                                //system('echo "atributo de expiracao: '.strtotime($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0]).'" >>/tmp/controle');
256                                                //if (strtotime($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0])<$now)
257                                //system('echo "chegou" >>/tmp/controle');
258                                if (($ldap_info[0]["phpgwaccountexpires"][0]!="-1")&&(strtotime($ldap_info[0]["phpgwaccountexpires"][0])<$now))
259                                                        {
260                                                        //system('echo "Encontrou atributo expirado" >>/tmp/controle');
261                                                        $expired=true;
262                                                        }
263                                                }
264                                                else
265                                                {
266
267                                                //Se o atributo de expiracao nao estiver configurado pressupoe que eh unixtime (phpgwaccountexpires)
268                                if (($ldap_info[0]["phpgwaccountexpires"][0]!="-1")&&(strtotime($ldap_info[0]["phpgwaccountexpires"][0])<$now))
269                                                        {
270                                                        //system('echo "Encontrou atributo expirado - phpgwaccoutexpires" >>/tmp/controle');
271                                                        $expired=true;
272                                                        }
273                                                }
274                                        if ($expired)
275                                                {
276                                                //A negacao de bind proveio de uma expiracao de senhas.
277                                                //Providencia a troca de senhas e, se configurado, também o ajuste do atributo de expiracao.
278                                                //system('echo "vai chamar o change_password" >>/tmp/controle');
279                                                if($GLOBALS['phpgw']->auth->change_password_user($passwd, $_POST['npasswd'],$dn,true))
280                                                        {
281                                                        //A troca de senhas funcionou
282                                                        //system('echo "Login: troca de senhas OK" >>/tmp/controle');
283                                                        if($GLOBALS['phpgw_info']['server']['diretorioescravo'])
284                                                                {
285                                                                //Tempo necessario para que o slave receba a atualizacao.
286                                                                sleep(1);
287                                                                }
288                                                        $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . './logout.php?cd=209');
289                                                        }
290                                                        else
291                                                        {
292                                                        //Direciona para senha incorreta na tela de troca de senhas
293                                                        //system('echo "Login: troca de senhas PROBLEMA" >>/tmp/controle');
294                                                        $GLOBALS['phpgw']->redirect("" . '/login.php?cd=5&ts=202');
295                                                        }
296                                                }
297                                                else
298                                                {
299                                                //A senha digitada estava incorreta
300                                                $GLOBALS['phpgw']->redirect($GLOBALS['phpgw_info']['server']['webserver_url'] . '/login.php?cd=5&ts=202');
301                                                }
302                                        }
303                                        else
304                                        {
305                                        //Usuario executou autenticacao no diretorio - a expiracao so pode ter vindo de uma politica de expiracao do proprio expresso
306                                        //system('echo "SIM conseguiu dar bind" >>/tmp/controle');
307                                        if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
308                                                {
309                                                //Se a politica de senhas for do Expresso eh necessario verificar se o usuario estah expirado
310                                                $now=time();
311                                                $common1 = CreateObject('phpgwapi.common');
312                                                $ldap_conn1 = $common1->ldapConnect();
313                                                if ($GLOBALS['phpgw_info']['server']['num_days_pwd_validate'])
314                                                        {
315                                                        $aux=$GLOBALS['phpgw_info']['server']['num_days_pwd_validate'];
316                                                        }
317                                                        else
318                                                        {
319                                                        $aux=90;
320                                                        }
321                                                //$entry['phpgwaccountexpires'] = $now + ($aux * 86400);
322                                                if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
323                                                        {
324                                                        if(substr($ldap_info[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0],-1,1) == "Z")
325                                                                {
326                                                                if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
327                                                                        {       
328                                                                        //quando a data de expiracao estah no formato yyyymmddhhmmssZ
329                                                                        $entry[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = strftime("%Y%m%d%H%M%SZ", $now + ($aux * 86400));
330                                                                        }
331                                                                }
332                                                                else
333                                                                {
334                                                                if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
335                                                                        {
336                                                                        //Outro atributo ldap que, assim como o phpgwaccounttype, tambem contem hora em formato unix
337                                                                        $entry[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = $now + ($aux * 86400);
338                                                                        }
339                                                                }
340                                                        }
341                                                        else
342                                                        {
343                                                        //Se a política for no diretorio nao precisa alterar o atributo de expiracao
344                                                        if($GLOBALS['phpgw_info']['server']['politicasenhas']=='expresso')
345                                                                {
346                                                                $entry['phpgwaccountexpires'] = $now + ($aux * 86400);
347                                                                }
348                                                        }
349                                                ldap_mod_replace($ldap_conn1,$ldap_info[0]['dn'], $entry);
350                                                }
351                        }
352                        Fim da parte usada para alteracao de senha no ExpressoMail
353                        */
354
355        }//Fim do IF do Captcha
356//-------------------------------------------------Fim - Adicionado para o Captcha - Fim----------------------------------------------
357        elseif ($_GET['lang'])  {
358                $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $_GET['lang'];
359        }
360        elseif(!isset($_COOKIE['last_loginid']) || !$prefs->account_id) {
361                list($lang) = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
362                $GLOBALS['phpgw_info']['user']['preferences']['common']['lang'] = $lang;
363        }
364
365        $tmpl->set_var('cd',check_logoutcode($_GET['cd']));
366        $tmpl->set_var('charset',$GLOBALS['phpgw']->translation->charset());
367        $tmpl->set_var('cookie',$last_loginid);
368        //$tmpl->set_var('lang_username',lang('username'));
369        $tmpl->set_var('cd',check_logoutcode($_GET['cd']));
370        $tmpl->set_var('lang_password',lang('password'));
371        $tmpl->set_var('lang_login',lang('login'));
372
373//---------------------------------Insercao do captcha.php---------------------
374if ($_GET['cd'] == '202' || $_GET['cd'] == '98' || $_GET['ts']=='202' || $_GET['cdx']=='202')
375{
376        $tmpl->set_var('cdx','202');
377}   
378// Alterado para utilizar o certificado digital...
379// if(!$GLOBALS['certificado']->apresentado)
380// {
381        $tmpl->set_var('lang_username',lang('username'));
382        $tmpl->set_var('CPF','<input name="user" size="18">');
383        if($GLOBALS['phpgw_info']['server']['captcha'])
384        {
385                if ($valor_cookie > $GLOBALS['phpgw_info']['server']['num_badlogin'])
386                {
387                        $tmpl->set_var('captcha','<tr border="1"><td>&nbsp;</td><td  nowrap width="155" class="codigoLabel">&nbsp;&nbsp;&nbsp;<img src="./seguranca/captcha.php" title="'.lang('Security code').'" alt="'.lang('Security code').'" width="70"  ></td></tr><tr><td align="right">'.lang('Code').'-></td><td width="105"><input name="codigo" type="text" size="15"  title="'.lang('Type the security code').'"></td> </tr>');
388                }
389        }
390// }
391/* else
392{
393        $tmpl->set_var('nome','<b>'.lang('Certificate owner').':</b> '.$GLOBALS['certificado']->dados['NOME']);
394        $tmpl->set_var('CPF','<input type="hidden" name="user" size="18" value="'.$GLOBALS['certificado']->dados['CPF'].'" READONLY>');
395}*/
396//-------------------------Fim da insercao do captcha.php-------------------------
397
398        $tmpl->set_var('website_title', $GLOBALS['phpgw_info']['server']['site_title']);
399        $tmpl->set_var('template_set',$GLOBALS['phpgw_info']['login_template_set']);
400        $tmpl->set_var('language_select','');
401        $tmpl->set_var($var);
402        $tmpl->set_block('login_form','language_select');
403        $tmpl->pfp('loginout','login_form');
404
405        function logout(){
406                $verified = $GLOBALS['phpgw']->session->verify();
407                if ($verified)
408                {
409                        if (file_exists($GLOBALS['phpgw_info']['server']['temp_dir'] . SEP . $GLOBALS['sessionid']))
410                        {
411                                $dh = opendir($GLOBALS['phpgw_info']['server']['temp_dir'] . SEP . $GLOBALS['sessionid']);
412                                while ($file = readdir($dh))
413                                {
414                                        if ($file != '.' && $file != '..')
415                                        {
416                                                unlink($GLOBALS['phpgw_info']['server']['temp_dir'] . SEP . $GLOBALS['sessionid'] . SEP . $file);
417                                        }
418                                }
419                                rmdir($GLOBALS['phpgw_info']['server']['temp_dir'] . SEP . $GLOBALS['sessionid']);
420                        }
421                        $GLOBALS['phpgw']->hooks->process('logout');
422                        $GLOBALS['phpgw']->session->destroy($GLOBALS['sessionid'],$GLOBALS['kp3']);
423                }
424        }
425?>
Note: See TracBrowser for help on using the repository browser.