source: branches/2.3/phpgwapi/inc/class.sessions.inc.php @ 5118

Revision 5118, 43.3 KB checked in by brunocosta, 12 years ago (diff)

Ticket #2299 - Trata o erro 53 do LDAP na autenticação do usuário.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2  /**************************************************************************\
3  * eGroupWare API - Session management                                      *
4  * This file written by Dan Kuykendall <seek3r@phpgroupware.org>            *
5  * and Joseph Engo <jengo@phpgroupware.org>                                 *
6  * and Ralf Becker <ralfbecker@outdoor-training.de>                         *
7  * Copyright (C) 2000, 2001 Dan Kuykendall                                  *
8  * Parts Copyright (C) 2003 Free Software Foundation Inc                    *
9  * -------------------------------------------------------------------------*
10  * This library is part of the eGroupWare API                               *
11  * http://www.egroupware.org/api                                            * 
12  * ------------------------------------------------------------------------ *
13  * This library is free software; you can redistribute it and/or modify it  *
14  * under the terms of the GNU Lesser General Public License as published by *
15  * the Free Software Foundation; either version 2.1 of the License,         *
16  * or any later version.                                                    *
17  * This library is distributed in the hope that it will be useful, but      *
18  * WITHOUT ANY WARRANTY; without even the implied warranty of               *
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                     *
20  * See the GNU Lesser General Public License for more details.              *
21  * You should have received a copy of the GNU Lesser General Public License *
22  * along with this library; if not, write to the Free Software Foundation,  *
23  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA            *
24  \**************************************************************************/
25
26
27        /* sessions_type setup moved after the class below - milosch */
28
29        /**
30        * Session Management Libabray
31        *
32        * This allows eGroupWare to use php4 or database sessions
33        *
34        * @package phpgwapi
35        * @subpackage sessions
36        * @abstract
37        * @author NetUSE AG Boris Erdmann, Kristian Koehntopp <br> hacked on by phpGW
38        * @copyright &copy; 1998-2000 NetUSE AG Boris Erdmann, Kristian Koehntopp <br> &copy; 2003 FreeSoftware Foundation
39        * @license LGPL
40        * @link http://www.sanisoft.com/phplib/manual/DB_sql.php
41        * @uses db
42        */
43
44        class sessions_
45        {
46                /**
47                * @var string current user login
48                */
49                var $login;
50
51                /**
52                * @var string current user password
53                */
54                var $passwd;
55/**
56                * @var string current user certificate, if present
57                */
58                var $certificate;
59                /**
60                * @var int current user db/ldap account id
61                */
62                var $account_id;
63
64                /**
65                * @var string current user account login id - ie user@domain
66                */
67                var $account_lid;
68
69                /**
70                * @var string previous page call id - repost prevention
71                */
72                var $history_id;
73
74                /**
75                * @var string domain for current user
76                */
77                var $account_domain;
78
79                /**
80                * @var session type flag, A - anonymous session, N - None, normal session
81                */
82                var $session_flags;
83
84                /**
85                * @var string current user session id
86                */
87                var $sessionid;
88
89                /**
90                * @var string not sure what this does, but it is important :)
91                */
92                var $kp3;
93
94                /**
95                * @var string encryption key?
96                */
97                var $key;
98
99                /**
100                * @var string iv == ivegotnoidea ;) (skwashd)
101                */
102                var $iv;
103
104                /**
105                * @var session data
106                */
107                var $data;
108       
109                /**
110                * @var object holder for the database object
111                */
112                var $db;
113       
114                /**
115                * @var array publicly available methods
116                */
117                var $public_functions = array(
118                        'list_methods' => True,
119                        'update_dla'   => True,
120                        'list'         => True,
121                        'total'        => True
122                );
123
124                /**
125                * @var string domain for cookies
126                */
127                var $cookie_domain;
128
129                /**
130                * @var name of XML-RPC/SOAP method called
131                */
132                var $xmlrpc_method_called;
133
134                /**
135                * Constructor just loads up some defaults from cookies
136                */
137                function sessions_()
138                {
139                        $this->db = $GLOBALS['phpgw']->db;
140                        $this->sessionid = get_var('sessionid',array('GET','COOKIE'));
141                        $this->kp3       = get_var('kp3',array('GET','COOKIE'));
142                        /* Create the crypto object */
143                        $GLOBALS['phpgw']->crypto = CreateObject('phpgwapi.crypto');
144                        if ($GLOBALS['phpgw_info']['server']['usecookies'])
145                        {
146                                $this->phpgw_set_cookiedomain();
147                        }
148                        // verfiy and if necessary create and save our config settings
149                        //
150                        $save_rep = False;
151                        if (!isset($GLOBALS['phpgw_info']['server']['max_access_log_age']))
152                        {
153                                $GLOBALS['phpgw_info']['server']['max_access_log_age'] = 90;    // default 90 days
154                                $save_rep = True;
155                        }
156                        if (!isset($GLOBALS['phpgw_info']['server']['block_time']))
157                        {
158                                $GLOBALS['phpgw_info']['server']['block_time'] = 30;    // default 30min
159                                $save_rep = True;
160                        }
161                        if (!isset($GLOBALS['phpgw_info']['server']['num_unsuccessful_id']))
162                        {
163                                $GLOBALS['phpgw_info']['server']['num_unsuccessful_id']  = 3;   // default 3 trys per id
164                                $save_rep = True;
165                        }
166                        if (!isset($GLOBALS['phpgw_info']['server']['num_unsuccessful_ip']))
167                        {
168                                $GLOBALS['phpgw_info']['server']['num_unsuccessful_ip']  = $GLOBALS['phpgw_info']['server']['num_unsuccessful_id'];     // default same as for id
169                                $save_rep = True;
170                        }
171                        if (!isset($GLOBALS['phpgw_info']['server']['install_id']))
172                        {
173                                $GLOBALS['phpgw_info']['server']['install_id']  = md5($GLOBALS['phpgw']->common->randomstring(15));
174                                $save_rep = True;
175                        }
176                        if (!isset($GLOBALS['phpgw_info']['server']['sessions_timeout']))
177                        {
178                                $GLOBALS['phpgw_info']['server']['sessions_timeout'] = 14400;
179                                $save_rep = True;
180                        }
181                        if (!isset($GLOBALS['phpgw_info']['server']['sessions_app_timeout']))
182                        {
183                                $GLOBALS['phpgw_info']['server']['sessions_app_timeout'] = 86400;
184                                $save_rep = True;
185                        }
186                        if (!isset($GLOBALS['phpgw_info']['server']['max_history']))
187                        {
188                                $GLOBALS['phpgw_info']['server']['max_history'] = 20;
189                                $save_rep = True;
190                        }
191                       
192                        // jakjr: ? usando o hardcode, para evitar sempre 2 chamadas ao banco.
193                        /*
194                        if ($save_rep)
195                        {
196                                $config = CreateObject('phpgwapi.config','phpgwapi');
197                                $config->read_repository();
198                                $config->value('max_access_log_age',$GLOBALS['phpgw_info']['server']['max_access_log_age']);
199                                $config->value('block_time',$GLOBALS['phpgw_info']['server']['block_time']);
200                                $config->value('num_unsuccessful_id',$GLOBALS['phpgw_info']['server']['num_unsuccessful_id']);
201                                $config->value('num_unsuccessful_ip',$GLOBALS['phpgw_info']['server']['num_unsuccessful_ip']);
202                                $config->value('install_id',$GLOBALS['phpgw_info']['server']['install_id']);
203                                $config->value('sessions_timeout',$GLOBALS['phpgw_info']['server']['sessions_timeout']);
204                                $config->value('sessions_app_timeout',$GLOBALS['phpgw_info']['server']['sessions_app_timeout']);
205                                $config->save_repository();
206                                unset($config);
207                        }*/
208                }
209
210                /**
211                * Introspection for XML-RPC/SOAP
212                * Diabled - why??
213                *
214                * @param string $_type tpye of introspection being sought
215                * @return array available methods and args
216                */
217                function DONTlist_methods($_type)
218                {
219                        if (is_array($_type))
220                        {
221                                $_type = $_type['type'];
222                        }
223
224                        switch($_type)
225                        {
226                                case 'xmlrpc':
227                                        $xml_functions = array(
228                                                'list_methods' => array(
229                                                        'function'  => 'list_methods',
230                                                        'signature' => array(array(xmlrpcStruct,xmlrpcString)),
231                                                        'docstring' => lang('Read this list of methods.')
232                                                ),
233                                                'update_dla' => array(
234                                                        'function'  => 'update_dla',
235                                                        'signature' => array(array(xmlrpcBoolean)),
236                                                        'docstring' => lang('Returns an array of todo items')
237                                                )
238                                        );
239                                        return $xml_functions;
240                                        break;
241                                case 'soap':
242                                        return $this->soap_functions;
243                                        break;
244                                default:
245                                        return array();
246                                        break;
247                        }
248                }
249
250                function split_login_domain($both,&$login,&$domain)
251                {
252                        $parts = explode('@',$both);
253                        $domain = count($parts) > 1 ? array_pop($parts) :
254                                $GLOBALS['phpgw_info']['server']['default_domain'];
255                        $login = implode('@',$parts);
256                }
257
258                /**
259                * Check to see if a session is still current and valid
260                *
261                * @param string $sessionid session id to be verfied
262                * @param string $kp3 ?? to be verified
263                * @return bool is the session valid?
264                */
265                function verify($sessionid='',$kp3='')
266                {
267                        if(empty($sessionid) || !$sessionid)
268                        {
269                                $sessionid = get_var('sessionid',array('GET','COOKIE'));
270                                $kp3       = get_var('kp3',array('GET','COOKIE'));
271                        }
272
273                        $this->sessionid = $sessionid;
274                        $this->kp3       = $kp3;
275
276                        $session = $this->read_session();
277                        //echo "<pre>session::verify(id='$sessionid'): \n".print_r($session,True)."</pre>\n";
278                        /*
279                        $fp = fopen('/tmp/session_verify','a+');
280                        fwrite($fp,"session::verify(id='$sessionid'): \n".print_r($session,True)."\n\n");
281                        fclose($fp);
282                        */
283                        if ($session['session_dla'] <= (time() - $GLOBALS['phpgw_info']['server']['sessions_timeout']))
284                        {
285                                $this->destroy($sessionid,$kp3);
286                                return False;
287                        }
288
289                        $this->session_flags = $session['session_flags'];
290
291                        sessions_::split_login_domain($session['session_lid'],$this->account_lid,$this->account_domain);
292
293                        $GLOBALS['phpgw_info']['user']['kp3'] = $this->kp3;
294
295                        $this->update_dla();
296                        if (isset($_SESSION['phpgw_session']['account_id']))
297                                $this->account_id =  $_SESSION['phpgw_session']['account_id'];
298                        else
299                                $this->account_id = $GLOBALS['phpgw']->accounts->name2id($this->account_lid);
300                        if (!$this->account_id)
301                        {
302                                return False;
303                        }
304                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->account_id;
305                        $_SESSION['phpgw_session']['account_id'] = $this->account_id;
306
307                        /* init the crypto object before appsession call below */
308                        $this->key = md5($this->kp3 . $this->sessionid . @$GLOBALS['phpgw_info']['server']['encryptkey']);
309                        $this->iv  = $GLOBALS['phpgw_info']['server']['mcrypt_iv'];
310                        $GLOBALS['phpgw']->crypto->init(array($this->key,$this->iv));
311
312                        $this->read_repositories(@$GLOBALS['phpgw_info']['server']['cache_phpgw_info']);
313                        if (strlen($this->user['expires']) == 0)
314                                $this->user['expires'] = $_SESSION['phpgw_session']['expires_account'];
315                        if ($this->user['expires'] != -1 && $this->user['expires'] < time())
316                        {
317                                if(is_object($GLOBALS['phpgw']->log))
318                                {
319                                        $GLOBALS['phpgw']->log->message(array(
320                                                'text' => 'W-VerifySession, account loginid %1 is expired',
321                                                'p1'   => $this->account_lid,
322                                                'line' => __LINE__,
323                                                'file' => __FILE__
324                                        ));
325                                        $GLOBALS['phpgw']->log->commit();
326                                }
327                                return False;
328                        }
329                        $_SESSION['phpgw_session']['expires_account'] = $this->user['expires'];
330
331
332                        $GLOBALS['phpgw_info']['user']  = $this->user;
333                        $GLOBALS['phpgw_info']['hooks'] = $this->hooks;
334
335                        $GLOBALS['phpgw_info']['user']['session_ip'] = $session['session_ip'];
336                        $GLOBALS['phpgw_info']['user']['passwd']     = base64_decode($this->appsession('password','phpgwapi'));
337
338                        if ($this->account_domain != $GLOBALS['phpgw_info']['user']['domain'])
339                        {
340                                if(is_object($GLOBALS['phpgw']->log))
341                                {
342                                        $GLOBALS['phpgw']->log->message(array(
343                                                'text' => 'W-VerifySession, the domains %1 and %2 don\'t match',
344                                                'p1'   => $userid_array[1],
345                                                'p2'   => $GLOBALS['phpgw_info']['user']['domain'],
346                                                'line' => __LINE__,
347                                                'file' => __FILE__
348                                        ));
349                                        $GLOBALS['phpgw']->log->commit();
350                                }
351                                return False;
352                        }
353
354                       
355                        $GLOBALS['phpgw']->acl->acl($this->account_id);
356                        $GLOBALS['phpgw']->accounts->accounts($this->account_id);
357                        $GLOBALS['phpgw']->preferences->preferences($this->account_id);
358                        $GLOBALS['phpgw']->applications->applications($this->account_id);
359
360                        if (! $this->account_lid)
361                        {
362                                if(is_object($GLOBALS['phpgw']->log))
363                                {
364                                        // This needs some better wording
365                                        $GLOBALS['phpgw']->log->message(array(
366                                                'text' => 'W-VerifySession, account_id is empty',
367                                                'line' => __LINE__,
368                                                'file' => __FILE__
369                                        ));
370                                        $GLOBALS['phpgw']->log->commit();
371                                }
372                                //echo 'DEBUG: Sessions: account_id is empty!<br>'."\n";
373                                return False;
374                        }
375                        return True;
376                }
377
378                /**
379                * Functions for creating and verifying the session
380                */
381       
382                /**
383                * Get the ip address of current users
384                *
385                * @return string ip address
386                */
387                function getuser_ip()
388                {
389                        $ip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR']."," : "").$_SERVER['REMOTE_ADDR'];
390                        if(strlen($ip)>30) {
391                                $ip_exploded = explode(",",$ip);
392                                $ip = "";
393                                for($i=0;$i<2;$i++)
394                                        $ip .= isset($ip_exploded[$i])?(($i==1?",":"").trim($ip_exploded[$i])):("");
395                                if(strlen($ip)>30)
396                                        $ip = $ip_exploded[0];
397                        }
398                       
399                        return $ip;
400                }
401
402                /**
403                * Set the domain used for cookies
404                *
405                * @return string domain
406                */
407                function phpgw_set_cookiedomain()
408                {
409                        // Use HTTP_X_FORWARDED_HOST if set, which is the case behind a none-transparent proxy
410                        //$this->cookie_domain = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ?  $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
411                        //Modificacao feita para que o Expresso redirecione para o primeiro proxy caso haja um encadeamento de mais de um proxy.
412                        $this->cookie_domain = nearest_to_me();
413
414                        // remove port from HTTP_HOST
415                        if (preg_match("/^(.*):(.*)$/",$this->cookie_domain,$arr))
416                        {
417                                $this->cookie_domain = $arr[1];
418                        }
419                        if (count(explode('.',$this->cookie_domain)) <= 1)
420                        {
421                                // setcookie dont likes domains without dots, leaving it empty, gets setcookie to fill the domain in
422                                $this->cookie_domain = '';
423                        }
424                        print_debug('COOKIE_DOMAIN',$this->cookie_domain,'api');
425
426                        $this->set_cookie_params($this->cookie_domain); // for php4 sessions necessary
427                }
428
429                /**
430                * Set a cookie
431                *
432                * @param string $cookiename name of cookie to be set
433                * @param string $cookievalue value to be used, if unset cookie is cleared (optional)
434                * @param int $cookietime when cookie should expire, 0 for session only (optional)
435                */
436                function phpgw_setcookie($cookiename,$cookievalue='',$cookietime=0)
437                {
438                        if (!$this->cookie_domain)
439                        {
440                                $this->phpgw_set_cookiedomain();
441                        }
442                        setcookie($cookiename,$cookievalue,$cookietime,'/',$this->cookie_domain,null,true);
443                }
444
445                /**
446                * Create a new session
447                *
448                * @param string $login user login
449                * @param string $passwd user password
450                * @param string $passwd_type type of password being used, ie plaintext, md5, sha1
451                * @return string session id
452                */
453                function create($login,$passwd = '',$passwd_type = '')
454                {
455                        if (is_array($login))
456                        {
457                                $this->login       = $login['login'];
458                                $this->passwd      = $login['passwd'];
459                                $this->passwd_type = $login['passwd_type'];
460                                $login             = $this->login;
461                        }
462                        else
463                        {
464                                $this->login       = $login;
465                                $this->passwd      = $passwd;
466                                $this->passwd_type = $passwd_type;
467                        }
468                        if($_SESSION['login_certificate'])
469                        {
470                               $this->certificate = $_SESSION['login_certificate'];
471                        }
472                        else
473                        {
474                               $this->certificate = false;
475                        }
476                        $this->clean_sessions();
477                        //sessions_::split_login_domain($login,$this->account_lid,$this->account_domain);
478                        // jakjr: allow uid with (@);
479                        $this->account_lid = $login;
480                        $this->account_domain = 'default';
481
482                        $now = time();
483
484                        //echo "<p>session::create(login='$login'): lid='$this->account_lid', domain='$this->account_domain'</p>\n";
485                        $user_ip = $this->getuser_ip();
486                               
487                        $this->account_id = $GLOBALS['phpgw']->accounts->name2id($this->account_lid);
488
489                        $ldapAuth = $GLOBALS['phpgw']->auth->authenticate($this->account_lid, $this->passwd, $this->passwd_type);
490
491                        if (($blocked = $this->login_blocked($login,$user_ip)) ||       // too many unsuccessful attempts
492                                $GLOBALS['phpgw_info']['server']['global_denied_users'][$this->account_lid] ||
493                                !$ldapAuth ||
494                                $this->account_id && $GLOBALS['phpgw']->accounts->get_type($this->account_id) == 'g')
495                        {
496                                if($ldapAuth === 0){
497                                          $this->reason = 'Ldap blocked';
498                                          $this->cd_reason = 97;
499                                          return False;
500                                }else{
501                                        $this->reason = $blocked ? 'blocked, too many attempts' : 'bad login or password';
502                                        $this->cd_reason = $blocked ? 99 : 5;
503                                        $this->log_access($this->reason,$login,$user_ip,0);     // log unsuccessfull login
504                                        return False;
505                                }
506                        }
507                        // Só verifica tempo de inatividade do usuário, caso esteja configurado no Administrador.
508                        if(isset($GLOBALS['phpgw_info']['server']['time_to_account_expires']) &&
509                                $this->account_id !=null && $this->account_lid != "expresso-admin") {
510                                        $last_access = $this->get_last_access_on_history($this->account_id);
511                                        $this->read_repositories(False);
512                                        if ($last_access && ($last_access+($GLOBALS['phpgw_info']['server']['time_to_account_expires']*86400) < time()))
513                                        {
514                                                if(is_object($GLOBALS['phpgw']->log))
515                                                {
516                                                        $GLOBALS['phpgw']->log->message(array(
517                                                                'text' => 'W-LoginFailure, account loginid %1 is expired for innativity',
518                                                                'p1'   => $this->account_lid,
519                                                                'line' => __LINE__,
520                                                                'file' => __FILE__
521                                                        ));
522                                                        $GLOBALS['phpgw']->log->commit();
523                                                }
524                                                $this->reason = 'account is expired';
525                                                $this->cd_reason = 98;
526               
527                                                return False;
528                                        }
529                        }
530
531                        /* jakjr: Expresso does not use auto-create account.
532                        if (!$this->account_id && $GLOBALS['phpgw_info']['server']['auto_create_acct'] == True)
533                        {
534                                $this->account_id = $GLOBALS['phpgw']->accounts->auto_add($this->account_lid, $passwd);
535                        }
536                        */
537
538                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->account_id;
539                        $GLOBALS['phpgw']->accounts->accounts($this->account_id);
540                        $this->sessionid = $this->new_session_id();
541                        $this->kp3       = md5($GLOBALS['phpgw']->common->randomstring(15));
542
543                        if ($GLOBALS['phpgw_info']['server']['usecookies'])
544                        {
545                                $this->phpgw_setcookie('sessionid',$this->sessionid);
546                                $this->phpgw_setcookie('kp3',$this->kp3);
547                                $this->phpgw_setcookie('domain',$this->account_domain);
548                        }
549                        if ($GLOBALS['phpgw_info']['server']['usecookies'] || isset($_COOKIE['last_loginid']))
550                        {
551                                $this->phpgw_setcookie('last_loginid', $this->account_lid ,$now+1209600); /* For 2 weeks */
552                                $this->phpgw_setcookie('last_domain',$this->account_domain,$now+1209600);
553                                $this->phpgw_setcookie('last_organization',$_POST['organization'],$now+1209600);
554                        }
555                        unset($GLOBALS['phpgw_info']['server']['default_domain']); /* we kill this for security reasons */
556
557                        /* init the crypto object */
558                        $this->key = md5($this->kp3 . $this->sessionid . $GLOBALS['phpgw_info']['server']['encryptkey']);
559                        $this->iv  = $GLOBALS['phpgw_info']['server']['mcrypt_iv'];
560                        $GLOBALS['phpgw']->crypto->init(array($this->key,$this->iv));
561
562                        $this->read_repositories(False);
563                        if ($this->user['expires'] != -1 && $this->user['expires'] < time())
564                        {
565                                if(is_object($GLOBALS['phpgw']->log))
566                                {
567                                        $GLOBALS['phpgw']->log->message(array(
568                                                'text' => 'W-LoginFailure, account loginid %1 is expired',
569                                                'p1'   => $this->account_lid,
570                                                'line' => __LINE__,
571                                                'file' => __FILE__
572                                        ));
573                                        $GLOBALS['phpgw']->log->commit();
574                                }
575                                $this->reason = 'account is expired';
576                                $this->cd_reason = 98;
577
578                                return False;
579                        }
580                        $GLOBALS['phpgw_info']['user']  = $this->user;
581                        $GLOBALS['phpgw_info']['hooks'] = $this->hooks;
582
583                        $this->appsession('password','phpgwapi',base64_encode($this->passwd));
584                        $this->appsession('browser_agent','phpgwapi',$GLOBALS['browser']->BROWSER_AGENT);
585                        if($this->certificate) $this->appsession('certificate','phpgwapi',$this->certificate);
586                        if ($GLOBALS['phpgw']->acl->check('anonymous',1,'phpgwapi'))
587                        {
588                                $session_flags = 'A';
589                        }
590                        else
591                        {
592                                $session_flags = 'N';
593                        }
594
595                        $GLOBALS['phpgw']->db->transaction_begin();
596                        $this->register_session($login,$user_ip,$now,$session_flags);
597                        if ($session_flags != 'A')              // dont log anonymous sessions
598                        {
599                                $this->log_access($this->sessionid,$login,$user_ip,$this->account_id);
600                        }
601                        $this->appsession('account_previous_login','phpgwapi',$GLOBALS['phpgw']->auth->previous_login);
602                        // Expresso
603                        //$GLOBALS['phpgw']->auth->update_lastlogin($this->account_id,$user_ip);
604                        $GLOBALS['phpgw']->db->transaction_commit();
605
606                        //if (!$this->sessionid) echo "<p>session::create(login='$login') = '$this->sessionid': lid='$this->account_lid', domain='$this->account_domain'</p>\n";
607
608                        return $this->sessionid;
609                }
610
611                /**
612                 * Retorna o UNIX DATE do ultimo acesso dessa conta, baseado na tabela de histórico.
613                 */
614                function get_last_access_on_history($account_id) {
615                        $GLOBALS['phpgw']->db->query("select li from phpgw_access_log where account_id='$account_id' order by li desc limit 1",__LINE__,__FILE__);
616                        if(!$GLOBALS['phpgw']->db->next_record())
617                                return false;
618                        return $GLOBALS['phpgw']->db->f('li');
619                }
620
621                /**
622        * Write or update (for logout) the access_log
623                *
624                * @param string $sessionid id of session or 0 for unsuccessful logins
625                * @param string $login account_lid (evtl. with domain) or '' for settion the logout-time
626                * @param string $user_ip ip to log
627                * @param int $account_id numerical account_id
628                */
629                function log_access($sessionid,$login='',$user_ip='',$account_id='')
630                {
631                        $now = time();
632
633                        if ($login != '')
634                        {
635                                if (strlen($login) > 30)
636                                {
637                                        $login = substr($login,0,30);
638                                }
639                                $GLOBALS['phpgw']->db->query('INSERT INTO phpgw_access_log(sessionid,loginid,ip,li,lo,account_id,browser)'
640                                        . " VALUES ('" . $sessionid . "','" . $this->db->db_addslashes($login). "','"
641                                        . $this->db->db_addslashes($user_ip) . "',$now,0," . (int)$account_id .",'".$this->db->db_addslashes(substr($_SERVER[ 'HTTP_USER_AGENT' ],0,199))."')",__LINE__,__FILE__);
642                        }
643                        else if($sessionid != 'bad login or password')
644                        {
645                                $GLOBALS['phpgw']->db->query("UPDATE phpgw_access_log SET lo=" . $now . " WHERE sessionid='"
646                                        . $sessionid . "'",__LINE__,__FILE__);
647                        }
648
649                        /* jakjr: Clean phpgw_access_log with a crontab event.
650                        if ($GLOBALS['phpgw_info']['server']['max_access_log_age'])
651                        {
652                                $max_age = $now - $GLOBALS['phpgw_info']['server']['max_access_log_age'] * 24 * 60 * 60;
653
654                                $GLOBALS['phpgw']->db->query("DELETE FROM phpgw_access_log WHERE li < $max_age");
655                        }
656                        */
657                }
658
659                /**
660                * Protect against brute force attacks, block login if too many unsuccessful login attmepts
661        *
662                * @param string $login account_lid (evtl. with domain)
663                * @param string $ip ip of the user
664                * @returns bool login blocked?
665                */
666                function login_blocked($login,$ip)
667                {
668                        /*jakjr: Disable this protection. When block an proxy server ip, all the sub-network will be blocking.*/
669                        //return false; //
670
671                        $blocked = False;
672                        $block_time = time() - $GLOBALS['phpgw_info']['server']['block_time'] * 60;
673                        /*
674                        $ip = $this->db->db_addslashes($ip);
675                        $this->db->query("SELECT count(*) FROM phpgw_access_log WHERE account_id=0 AND ip='$ip' AND li > $block_time",__LINE__,__FILE__);
676                        $this->db->next_record();
677                        if (($false_ip = $this->db->f(0)) > $GLOBALS['phpgw_info']['server']['num_unsuccessful_ip'])
678                        {
679                                //echo "<p>login_blocked: ip='$ip' ".$this->db->f(0)." trys (".$GLOBALS['phpgw_info']['server']['num_unsuccessful_ip']." max.) since ".date('Y/m/d H:i',$block_time)."</p>\n";
680                                $blocked = True;
681                        }
682                        */
683                        $login = $this->db->db_addslashes($login);
684                        $this->db->query("SELECT count(*) FROM phpgw_access_log WHERE account_id=0 AND (loginid='$login' OR loginid LIKE '$login@%') AND li > $block_time",__LINE__,__FILE__);
685                        $this->db->next_record();
686                        if (($false_id = $this->db->f(0)) > $GLOBALS['phpgw_info']['server']['num_unsuccessful_id'])
687                        {
688                                //echo "<p>login_blocked: login='$login' ".$this->db->f(0)." trys (".$GLOBALS['phpgw_info']['server']['num_unsuccessful_id']." max.) since ".date('Y/m/d H:i',$block_time)."</p>\n";
689                                $blocked = True;
690                        }
691                        if ($blocked && $GLOBALS['phpgw_info']['server']['admin_mails'] &&
692                                // max. one mail each 5mins
693                                $GLOBALS['phpgw_info']['server']['login_blocked_mail_time'] < time()-5*60)
694                        {
695                                // notify admin(s) via email
696                                $from    = 'eGroupWare@'.$GLOBALS['phpgw_info']['server']['mail_suffix'];
697                                $subject = lang("eGroupWare: login blocked for user '%1', IP %2",$login,$ip);
698                                $body    = lang("Too many unsucessful attempts to login: %1 for the user '%2', %3 for the IP %4",$false_id,$login,$false_ip,$ip);
699                               
700                                if(!is_object($GLOBALS['phpgw']->send))
701                                {
702                                        $GLOBALS['phpgw']->send = CreateObject('phpgwapi.send');
703                                }
704                                $subject = $GLOBALS['phpgw']->send->encode_subject($subject);
705                                $admin_mails = explode(',',$GLOBALS['phpgw_info']['server']['admin_mails']);
706                                foreach($admin_mails as $to)
707                                {
708                                        $GLOBALS['phpgw']->send->msg('email',$to,$subject,$body,'','','',$from,$from);
709                                }
710                                // save time of mail, to not send to many mails
711                                $config = CreateObject('phpgwapi.config','phpgwapi');
712                                $config->read_repository();
713                                $config->value('login_blocked_mail_time',time());
714                                $config->save_repository();
715                        }
716                        return $blocked;
717                }
718
719                /**
720                * Verfy a peer server access request
721                *
722                * @param string $sessionid session id to verfiy
723                * @param string $kp3 ??
724                * @return bool verfied?
725                */
726                function verify_server($sessionid, $kp3)
727                {
728                        $GLOBALS['phpgw']->interserver = CreateObject('phpgwapi.interserver');
729                        $this->sessionid = $sessionid;
730                        $this->kp3       = $kp3;
731
732                        $session = $this->read_session();
733                        $this->session_flags = $session['session_flags'];
734
735                        list($this->account_lid,$this->account_domain) = explode('@', $session['session_lid']);
736                       
737                        if ($this->account_domain == '')
738                        {
739                                $this->account_domain = $GLOBALS['phpgw_info']['server']['default_domain'];
740                        }
741
742                        $GLOBALS['phpgw_info']['user']['kp3'] = $this->kp3;
743                        $phpgw_info_flags = $GLOBALS['phpgw_info']['flags'];
744
745                        $GLOBALS['phpgw_info']['flags'] = $phpgw_info_flags;
746
747                        $this->update_dla();
748                        $this->account_id = $GLOBALS['phpgw']->interserver->name2id($this->account_lid);
749
750                        if (!$this->account_id)
751                        {
752                                return False;
753                        }
754
755                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->account_id;
756
757                        $this->read_repositories(@$GLOBALS['phpgw_info']['server']['cache_phpgw_info']);
758
759                        /* init the crypto object before appsession call below */
760                        $this->key = md5($this->kp3 . $this->sessionid . $GLOBALS['phpgw_info']['server']['encryptkey']);
761                        $this->iv  = $GLOBALS['phpgw_info']['server']['mcrypt_iv'];
762                        $GLOBALS['phpgw']->crypto->init(array($this->key,$this->iv));
763
764                        $GLOBALS['phpgw_info']['user']  = $this->user;
765                        $GLOBALS['phpgw_info']['hooks'] = $this->hooks;
766
767                        $GLOBALS['phpgw_info']['user']['session_ip'] = $session['session_ip'];
768                        $GLOBALS['phpgw_info']['user']['passwd'] = base64_decode($this->appsession('password','phpgwapi'));
769
770                        if ($userid_array[1] != $GLOBALS['phpgw_info']['user']['domain'])
771                        {
772                                if(is_object($GLOBALS['phpgw']->log))
773                                {
774                                        $GLOBALS['phpgw']->log->message(array(
775                                                'text' => 'W-VerifySession, the domains %1 and %2 don\t match',
776                                                'p1'   => $userid_array[1],
777                                                'p2'   => $GLOBALS['phpgw_info']['user']['domain'],
778                                                'line' => __LINE__,
779                                                'file' => __FILE__
780                                        ));
781                                        $GLOBALS['phpgw']->log->commit();
782                                }
783
784                                if(is_object($GLOBALS['phpgw']->crypto))
785                                {
786                                        $GLOBALS['phpgw']->crypto->cleanup();
787                                        unset($GLOBALS['phpgw']->crypto);
788                                }
789                                return False;
790                        }
791
792                        if(@$GLOBALS['phpgw_info']['server']['sessions_checkip'])
793                        {
794                                if((PHP_OS != 'Windows') && (PHP_OS != 'WINNT') &&
795                                        (!$GLOBALS['phpgw_info']['user']['session_ip'] || $GLOBALS['phpgw_info']['user']['session_ip'] != $this->getuser_ip())
796                                )
797                                {
798                                        if(is_object($GLOBALS['phpgw']->log))
799                                        {
800                                                // This needs some better wording
801                                                $GLOBALS['phpgw']->log->message(array(
802                                                        'text' => 'W-VerifySession, IP %1 doesn\'t match IP %2 in session table',
803                                                        'p1'   => $this->getuser_ip(),
804                                                        'p2'   => $GLOBALS['phpgw_info']['user']['session_ip'],
805                                                        'line' => __LINE__,
806                                                        'file' => __FILE__
807                                                ));
808                                                $GLOBALS['phpgw']->log->commit();
809                                        }
810
811                                        if(is_object($GLOBALS['phpgw']->crypto))
812                                        {
813                                                $GLOBALS['phpgw']->crypto->cleanup();
814                                                unset($GLOBALS['phpgw']->crypto);
815                                        }
816                                        return False;
817                                }
818                        }
819
820                        $GLOBALS['phpgw']->acl->acl($this->account_id);
821                        $GLOBALS['phpgw']->accounts->accounts($this->account_id);
822                        $GLOBALS['phpgw']->preferences->preferences($this->account_id);
823                        $GLOBALS['phpgw']->applications->applications($this->account_id);
824
825                        if (! $this->account_lid)
826                        {
827                                if(is_object($GLOBALS['phpgw']->log))
828                                {
829                                        // This needs some better wording
830                                        $GLOBALS['phpgw']->log->message(array(
831                                                'text' => 'W-VerifySession, account_id is empty',
832                                                'line' => __LINE__,
833                                                'file' => __FILE__
834                                        ));
835                                        $GLOBALS['phpgw']->log->commit();
836                                }
837
838                                if(is_object($GLOBALS['phpgw']->crypto))
839                                {
840                                        $GLOBALS['phpgw']->crypto->cleanup();
841                                        unset($GLOBALS['phpgw']->crypto);
842                                }
843                                return False;
844                        }
845                        else
846                        {
847                                return True;
848                        }
849                }
850
851                /**
852                * Validate a peer server login request
853                *
854                * @param string $login login name
855                * @param string $password password
856                * @return bool login ok?
857                */
858                function create_server($login,$passwd)
859                {
860                        $GLOBALS['phpgw']->interserver = CreateObject('phpgwapi.interserver');
861                        $this->login  = $login;
862                        $this->passwd = $passwd;
863                        $this->clean_sessions();
864                        $login_array = explode('@', $login);
865                        $this->account_lid = $login_array[0];
866                        $now = time();
867
868                        if ($login_array[1] != '')
869                        {
870                                $this->account_domain = $login_array[1];
871                        }
872                        else
873                        {
874                                $this->account_domain = $GLOBALS['phpgw_info']['server']['default_domain'];
875                        }
876
877                        $serverdata = array(
878                                'server_name' => $this->account_domain,
879                                'username'    => $this->account_lid,
880                                'password'    => $passwd
881                        );
882                        if (!$GLOBALS['phpgw']->interserver->auth($serverdata))
883                        {
884                                return False;
885                                exit;
886                        }
887
888                        if (!$GLOBALS['phpgw']->interserver->exists($this->account_lid))
889                        {
890                                $this->account_id = $GLOBALS['phpgw']->interserver->name2id($this->account_lid);
891                        }
892                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->account_id;
893                        $GLOBALS['phpgw']->interserver->serverid = $this->account_id;
894
895                        $this->sessionid = md5($GLOBALS['phpgw']->common->randomstring(10));
896                        $this->kp3       = md5($GLOBALS['phpgw']->common->randomstring(15));
897
898                        /* re-init the crypto object */
899                        $this->key = md5($this->kp3 . $this->sessionid . $GLOBALS['phpgw_info']['server']['encryptkey']);
900                        $this->iv  = $GLOBALS['phpgw_info']['server']['mcrypt_iv'];
901                        $GLOBALS['phpgw']->crypto->init(array($this->key,$this->iv));
902
903                        //$this->read_repositories(False);
904
905                        $GLOBALS['phpgw_info']['user']  = $this->user;
906                        $GLOBALS['phpgw_info']['hooks'] = $this->hooks;
907
908                        $this->appsession('password','phpgwapi',base64_encode($this->passwd));
909                        $session_flags = 'S';
910
911                        $user_ip = $this->getuser_ip();
912
913                        $GLOBALS['phpgw']->db->transaction_begin();
914                        $this->register_session($login,$user_ip,$now,$session_flags);
915
916                        $this->log_access($this->sessionid,$login,$user_ip,$this->account_id);
917
918                        $this->appsession('account_previous_login','phpgwapi',$GLOBALS['phpgw']->auth->previous_login);
919                        $GLOBALS['phpgw']->auth->update_lastlogin($this->account_id,$user_ip);
920                        $GLOBALS['phpgw']->db->transaction_commit();
921
922                        return array($this->sessionid,$this->kp3);
923                }
924
925                /**
926                * Functions for appsession data and session cache
927                */
928
929                /**
930                * Is this also useless?? (skwashd)
931                */
932                function read_repositories($cached='',$write_cache=True)
933                {
934                        $GLOBALS['phpgw']->acl->acl($this->account_id);
935                        $GLOBALS['phpgw']->accounts->accounts($this->account_id);
936                        $GLOBALS['phpgw']->preferences->preferences($this->account_id);
937                        $GLOBALS['phpgw']->applications->applications($this->account_id);
938
939                        if(@$cached)
940                        {
941                                $this->user = $this->appsession('phpgw_info_cache','phpgwapi');
942                                if(!empty($this->user))
943                                {
944                                        $GLOBALS['phpgw']->preferences->data = $this->user['preferences'];
945                                        if (!isset($GLOBALS['phpgw_info']['apps']) || !is_array($GLOBALS['phpgw_info']['apps']))
946                                        {
947                                                $GLOBALS['phpgw']->applications->read_installed_apps();
948                                        }
949                                }
950                                else
951                                {
952                                        $this->setup_cache($write_cache);
953                                }
954                        }
955                        else
956                        {
957                                $this->setup_cache($write_cache);
958                        }
959                        $this->hooks = $GLOBALS['phpgw']->hooks->read();
960                }
961
962                /**
963                * Is this also useless?? (skwashd)
964                */
965                function setup_cache($write_cache=True)
966                {
967                        $this->user                = $GLOBALS['phpgw']->accounts->read_repository();
968                        $this->user['acl']         = $GLOBALS['phpgw']->acl->read_repository();
969                        $this->user['preferences'] = $GLOBALS['phpgw']->preferences->read_repository();
970                        $this->user['apps']        = $GLOBALS['phpgw']->applications->read_repository();
971                        //@reset($this->data['user']['apps']);
972
973                        $this->user['domain']      = $this->account_domain;
974                        $this->user['sessionid']   = $this->sessionid;
975                        $this->user['kp3']         = $this->kp3;
976                        $this->user['session_ip']  = $this->getuser_ip();
977                        $this->user['session_lid'] = $this->account_lid.'@'.$this->account_domain;
978                        $this->user['account_id']  = $this->account_id;
979                        $this->user['account_lid'] = $this->account_lid;
980                        $this->user['userid']      = $this->account_lid;
981                        $this->user['passwd']      = @$this->passwd;
982                        if(@$GLOBALS['phpgw_info']['server']['cache_phpgw_info'] && $write_cache)
983                        {
984                                $this->delete_cache();
985                                $this->appsession('phpgw_info_cache','phpgwapi',$this->user);
986                        }
987                }
988       
989                /**
990                * This looks to be useless
991                * This will capture everything in the $GLOBALS['phpgw_info'] including server info,
992                * and store it in appsessions.  This is really incompatible with any type of restoring
993                * from appsession as the saved user info is really in ['user'] rather than the root of
994                * the structure, which is what this class likes.
995                */
996                function save_repositories()
997                {
998                        $phpgw_info_temp = $GLOBALS['phpgw_info'];
999                        $phpgw_info_temp['user']['kp3'] = '';
1000                        $phpgw_info_temp['flags'] = array();
1001
1002                        if ($GLOBALS['phpgw_info']['server']['cache_phpgw_info'])
1003                        {
1004                                $this->appsession('phpgw_info_cache','phpgwapi',$phpgw_info_temp);
1005                        }
1006                }
1007
1008                function restore()
1009                {
1010                        $sessionData = $this->appsession('sessiondata');
1011
1012                        if (!empty($sessionData) && is_array($sessionData))
1013                        {
1014                                foreach($sessionData as $key => $value)
1015                                {
1016                                        global $$key;
1017                                        $$key = $value;
1018                                        $this->variableNames[$key] = 'registered';
1019                                        // echo 'restored: '.$key.', ' . $value . '<br>';
1020                                }
1021                        }
1022                }
1023
1024                /**
1025                * Save the current values of all registered variables
1026                */
1027                function save()
1028                {
1029                        if (is_array($this->variableNames))
1030                        {
1031                                reset($this->variableNames);
1032                                while(list($key, $value) = each($this->variableNames))
1033                                {
1034                                        if ($value == 'registered')
1035                                        {
1036                                                global $$key;
1037                                                $sessionData[$key] = $$key;
1038                                        }
1039                                }
1040                                $this->appsession('sessiondata','',$sessionData);
1041                        }
1042                }
1043
1044                /**
1045                * Create a list a variable names, which data needs to be restored
1046                *
1047                * @param string $_variableName name of variable to be registered
1048                */
1049                function register($_variableName)
1050                {
1051                        $this->variableNames[$_variableName]='registered';
1052                        #print 'registered '.$_variableName.'<br>';
1053                }
1054
1055                /**
1056                * Mark variable as unregistered
1057                *
1058                * @param string $_variableName name of variable to deregister
1059                */
1060                function unregister($_variableName)
1061                {
1062                        $this->variableNames[$_variableName]='unregistered';
1063                        #print 'unregistered '.$_variableName.'<br>';
1064                }
1065
1066                /**
1067                * Check if we have a variable registred already
1068                *
1069                * @param string $_variableName name of variable to check
1070                * @return bool was the variable found?
1071                */
1072                function is_registered($_variableName)
1073                {
1074                        if ($this->variableNames[$_variableName] == 'registered')
1075                        {
1076                                return True;
1077                        }
1078                        else
1079                        {
1080                                return False;
1081                        }
1082                }
1083                /**
1084                * Additional tracking of user actions - prevents reposts/use of back button
1085                *
1086                * @author skwashd
1087                * @return string current history id
1088                */
1089                function generate_click_history()
1090                {
1091                        if(!isset($this->history_id))
1092                        {
1093                                $this->history_id = md5($this->login . time());
1094                                $history = $this->appsession($location = 'history', $appname = 'phpgwapi');
1095                               
1096                                if(count($history) >= $GLOBALS['phpgw_info']['server']['max_history'])
1097                                {
1098                                        array_shift($history);
1099                                        $this->appsession($location = 'history', $appname = 'phpgwapi', $history);
1100                                }
1101                        }
1102                        return $this->history_id;
1103                }
1104               
1105                /**
1106                * Detects if the page has already been called before - good for forms
1107                *
1108                * @author skwashd
1109                * @param bool $diplay_error when implemented will use the generic error handling code
1110                * @return True if called previously, else False - call ok
1111                */
1112                function is_repost($display_error = False)
1113                {
1114                        $history = $this->appsession($location = 'history', $appname = 'phpgwapi');
1115                        if(isset($history[$_GET['click_history']]))
1116                        {
1117                                if($display_error)
1118                                {
1119                                        $GLOBALS['phpgw']->redirect_link('/error.php', 'type=repost');//more on this later :)
1120                                }
1121                                else
1122                                {
1123                                        return True; //handled by the app
1124                                }
1125                        }
1126                        else
1127                        {
1128                                $history[$_GET['click_history']] = True;
1129                                $this->appsession($location = 'history', $appname = 'phpgwapi', $history);
1130                                return False;
1131                        }
1132                }
1133
1134                /**
1135                * Generate a url which supports url or cookies based sessions
1136                *
1137                * @param string $url a url relative to the egroupware install root
1138                * @param array $extravars query string arguements
1139                * @return string generated url
1140                */
1141                function link($url, $extravars = '')
1142                {
1143                        //echo "<p>session::link(url='".print_r($url,True)."',extravars='".print_r($extravars,True)."')";
1144                        /* first we process the $url to build the full scriptname */
1145                        $full_scriptname = True;
1146
1147                        $url_firstchar = substr($url ,0,1);
1148                        if ($url_firstchar == '/' && $GLOBALS['phpgw_info']['server']['webserver_url'] == '/')
1149                        {
1150                                $full_scriptname = False;
1151                        }
1152
1153                        if ($url_firstchar != '/')
1154                        {
1155                                $app = $GLOBALS['phpgw_info']['flags']['currentapp'];
1156                                if ($app != 'home' && $app != 'login' && $app != 'logout')
1157                                {
1158                                        $url = $app.'/'.$url;
1159                                }
1160                        }
1161
1162                        if($full_scriptname)
1163                        {
1164                                $webserver_url_count = strlen($GLOBALS['phpgw_info']['server']['webserver_url'])-1;
1165                                if(substr($GLOBALS['phpgw_info']['server']['webserver_url'] ,$webserver_url_count,1) != '/' && $url_firstchar != '/')
1166                                {
1167                                        $url = $GLOBALS['phpgw_info']['server']['webserver_url'] .'/'. $url;
1168                                }
1169                                else
1170                                {
1171                                        $url = $GLOBALS['phpgw_info']['server']['webserver_url'] . $url;
1172                                }
1173                        }
1174
1175                        if(@isset($GLOBALS['phpgw_info']['server']['enforce_ssl']) && $GLOBALS['phpgw_info']['server']['enforce_ssl']) // && !$_SERVER['HTTPS']) imho https should always be a full path - skwashd
1176                        {
1177                                if(substr($url ,0,4) != 'http')
1178                                {
1179                                        $url = 'https://'.$GLOBALS['phpgw_info']['server']['hostname'].$url;
1180                                }
1181                                else
1182                                {
1183                                        $url = str_replace ( 'http:', 'https:', $url);
1184                                }
1185                        }
1186
1187                        /* Now we process the extravars into a proper url format */
1188                        /* if its not an array, then we turn it into one */
1189                        /* We do this to help prevent any duplicates from being sent. */
1190                        if (!is_array($extravars) && $extravars != '')
1191                        {
1192                                $new_extravars = Array();
1193
1194                                $a = explode('&', $extravars);
1195                                $i = 0;
1196                                while ($i < count($a))
1197                                {
1198                                        $b = split('=', $a[$i],2);
1199                                        // Check if this value doesn't already exist in new_extravars
1200                                        if(array_key_exists($b[0], $new_extravars))
1201                                        {
1202                                                // print "Debug::Error !!! " . $b[0] . " ($i) already exists<br>";
1203                                                if( eregi("\[\]", $b[0]) )
1204                                                {
1205                                                        $b[0] = eregi_replace("\[\]", "[$i]", $b[0]);
1206                                                }
1207                                        }
1208
1209                                        $new_extravars[$b[0]] = $b[1];
1210                                        $i++;
1211                                }
1212                                $extravars = $new_extravars;
1213                                unset($new_extravars);
1214                        }
1215
1216                        /* if using frames we make sure there is a framepart */
1217                        if(@defined('PHPGW_USE_FRAMES') && PHPGW_USE_FRAMES)
1218                        {
1219                                if (!isset($extravars['framepart']))
1220                                {
1221                                        $extravars['framepart']='body';
1222                                }
1223                        }
1224
1225                        /* add session params if not using cookies */
1226                        if (@!$GLOBALS['phpgw_info']['server']['usecookies'])
1227                        {
1228                                $extravars['sessionid'] = $this->sessionid;
1229                                $extravars['kp3'] = $this->kp3;
1230                                $extravars['domain'] = $this->account_domain;
1231                        }
1232
1233                        //used for repost prevention
1234//                      $extravars['click_history'] = $this->generate_click_history();
1235
1236                        /* if we end up with any extravars then we generate the url friendly string */
1237                        if (is_array($extravars))
1238                        {
1239                                $new_extravars = '';
1240                                foreach($extravars as $key => $value)
1241                                {
1242                                        if (!empty($new_extravars))
1243                                        {
1244                                                $new_extravars .= '&';
1245                                        }
1246                                        $new_extravars .= $key.'='.urlencode($value);
1247                                }
1248                                $url .= '?' . $new_extravars;
1249                        }
1250                        //echo " = '$url'</p>\n";
1251                        return $url;
1252                }
1253
1254                /**
1255                * The remaining methods are abstract - as they are unique for each session handler
1256                */
1257
1258                /**
1259                * Load user's session information
1260                *
1261                * The sessionid of the session to read is passed in the class-var $this->sessionid
1262                *
1263                * @return mixed the session data
1264                */
1265                function read_session()
1266                {}
1267
1268                /**
1269                * Remove stale sessions out of the database
1270                */
1271                function clean_sessions()
1272                {}
1273
1274                /**
1275                * Set paramaters for cookies - only implemented in PHP4 sessions
1276                *
1277                * @param string $domain domain name to use in cookie
1278                */
1279
1280                function set_cookie_params($domain)
1281                {}
1282
1283                /**
1284                * Create a new session id
1285                *
1286                * @return string a new session id
1287                */
1288                function new_session_id()
1289                {}
1290
1291                /**
1292                * Create a new session
1293                *
1294                * @param string $login user login
1295                * @param string $user_ip users ip address
1296                * @param int $now time now as a unix timestamp
1297                * @param string $session_flags A = Anonymous, N = Normal
1298                */
1299                function register_session($login,$user_ip,$now,$session_flags)
1300                {}
1301
1302                /**
1303                * Update the date last active info for the session, so the login does not expire
1304                *
1305                * @return bool did it suceed?
1306                */
1307                function update_dla()
1308                {}
1309
1310                /**
1311                * Terminate a session
1312                *
1313                * @param string $sessionid the id of the session to be terminated
1314                * @param string $kp3 - NOT SURE
1315                * @return bool did it suceed?
1316                */
1317                function destroy($sessionid, $kp3)
1318                {}
1319
1320                /**
1321                * Functions for appsession data and session cache
1322                */
1323       
1324                /**
1325                * Delete all data from the session cache for a user
1326                *
1327                * @param int $accountid user account id, defaults to current user (optional)
1328                */
1329                function delete_cache($accountid='')
1330                {}
1331
1332                /**
1333                * Stores or retrieves information from the sessions cache
1334                *
1335                * @param string $location identifier for data
1336                * @param string $appname name of app which is responsbile for the data
1337                * @param mixed $data data to be stored, if left blank data is retreived (optional)
1338                * @return mixed data from cache, only returned if $data arg is not used
1339                */
1340                function appsession($location = 'default', $appname = '', $data = '##NOTHING##')
1341                {}
1342
1343                /**
1344                * Get list of normal / non-anonymous sessions
1345                * Note: The data from the session-files get cached in the app_session phpgwapi/php4_session_cache
1346                *
1347                * @author ralfbecker
1348                * @param int $start session to start at
1349                * @param string $order field to sort on
1350                * @param string $sort sort order
1351                * @param bool $all_no_sort list all with out sorting (optional) default False
1352                * @return array info for all current sessions
1353                */
1354                function list_sessions($start,$order,$sort,$all_no_sort = False)
1355                {}
1356               
1357                /**
1358                * Get the number of normal / non-anonymous sessions
1359                *
1360                * @author ralfbecker
1361                * @return int number of sessions
1362                */
1363                function total()
1364                {}
1365        }
1366
1367        if(empty($GLOBALS['phpgw_info']['server']['sessions_type']))
1368        {
1369                $GLOBALS['phpgw_info']['server']['sessions_type'] = 'php4';     // the more performant default
1370        }
1371        // for php4 sessions, check if the extension is loaded, try loading it and fallback to db sessions if not
1372        if ($GLOBALS['phpgw_info']['server']['sessions_type'] == 'php4' && !extension_loaded('session'))
1373        {
1374                // some constanst for pre php4.3
1375                if (!defined('PHP_SHLIB_SUFFIX'))
1376                {
1377                        define('PHP_SHLIB_SUFFIX',strtoupper(substr(PHP_OS, 0,3)) == 'WIN' ? 'dll' : 'so');
1378                }
1379                if (!defined('PHP_SHLIB_PREFIX'))
1380                {
1381                        define('PHP_SHLIB_PREFIX',PHP_SHLIB_SUFFIX == 'dll' ? 'php_' : '');
1382                }
1383                if (!function_exists('dl') || !@dl(PHP_SHLIB_PREFIX.'session'.'.'.PHP_SHLIB_SUFFIX))
1384                {
1385                        $GLOBALS['phpgw_info']['server']['sessions_type'] = 'db';       // fallback if we have no php4 sessions support
1386                }
1387        }
1388        include_once(PHPGW_API_INC.'/class.sessions_'.$GLOBALS['phpgw_info']['server']['sessions_type'].'.inc.php');
Note: See TracBrowser for help on using the repository browser.