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

Revision 4945, 42.9 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #2224 - Caracteres estranhos em e-mail originado do Outlook

  • 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                        if (($blocked = $this->login_blocked($login,$user_ip)) ||       // too many unsuccessful attempts
490                                $GLOBALS['phpgw_info']['server']['global_denied_users'][$this->account_lid] ||
491                                !$GLOBALS['phpgw']->auth->authenticate($this->account_lid, $this->passwd, $this->passwd_type) ||
492                                $this->account_id && $GLOBALS['phpgw']->accounts->get_type($this->account_id) == 'g')
493                        {
494                                $this->reason = $blocked ? 'blocked, too many attempts' : 'bad login or password';
495                                $this->cd_reason = $blocked ? 99 : 5;
496
497                                $this->log_access($this->reason,$login,$user_ip,0);     // log unsuccessfull login
498                                return False;
499                        }
500                        // Só verifica tempo de inatividade do usuário, caso esteja configurado no Administrador.
501                        if(isset($GLOBALS['phpgw_info']['server']['time_to_account_expires']) &&
502                                $this->account_id !=null && $this->account_lid != "expresso-admin") {
503                                        $last_access = $this->get_last_access_on_history($this->account_id);
504                                        $this->read_repositories(False);
505                                        if ($last_access && ($last_access+($GLOBALS['phpgw_info']['server']['time_to_account_expires']*86400) < time()))
506                                        {
507                                                if(is_object($GLOBALS['phpgw']->log))
508                                                {
509                                                        $GLOBALS['phpgw']->log->message(array(
510                                                                'text' => 'W-LoginFailure, account loginid %1 is expired for innativity',
511                                                                'p1'   => $this->account_lid,
512                                                                'line' => __LINE__,
513                                                                'file' => __FILE__
514                                                        ));
515                                                        $GLOBALS['phpgw']->log->commit();
516                                                }
517                                                $this->reason = 'account is expired';
518                                                $this->cd_reason = 98;
519               
520                                                return False;
521                                        }
522                        }
523
524                        /* jakjr: Expresso does not use auto-create account.
525                        if (!$this->account_id && $GLOBALS['phpgw_info']['server']['auto_create_acct'] == True)
526                        {
527                                $this->account_id = $GLOBALS['phpgw']->accounts->auto_add($this->account_lid, $passwd);
528                        }
529                        */
530
531                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->account_id;
532                        $GLOBALS['phpgw']->accounts->accounts($this->account_id);
533                        $this->sessionid = $this->new_session_id();
534                        $this->kp3       = md5($GLOBALS['phpgw']->common->randomstring(15));
535
536                        if ($GLOBALS['phpgw_info']['server']['usecookies'])
537                        {
538                                $this->phpgw_setcookie('sessionid',$this->sessionid);
539                                $this->phpgw_setcookie('kp3',$this->kp3);
540                                $this->phpgw_setcookie('domain',$this->account_domain);
541                        }
542                        if ($GLOBALS['phpgw_info']['server']['usecookies'] || isset($_COOKIE['last_loginid']))
543                        {
544                                $this->phpgw_setcookie('last_loginid', $this->account_lid ,$now+1209600); /* For 2 weeks */
545                                $this->phpgw_setcookie('last_domain',$this->account_domain,$now+1209600);
546                                $this->phpgw_setcookie('last_organization',$_POST['organization'],$now+1209600);
547                        }
548                        unset($GLOBALS['phpgw_info']['server']['default_domain']); /* we kill this for security reasons */
549
550                        /* init the crypto object */
551                        $this->key = md5($this->kp3 . $this->sessionid . $GLOBALS['phpgw_info']['server']['encryptkey']);
552                        $this->iv  = $GLOBALS['phpgw_info']['server']['mcrypt_iv'];
553                        $GLOBALS['phpgw']->crypto->init(array($this->key,$this->iv));
554
555                        $this->read_repositories(False);
556                        if ($this->user['expires'] != -1 && $this->user['expires'] < time())
557                        {
558                                if(is_object($GLOBALS['phpgw']->log))
559                                {
560                                        $GLOBALS['phpgw']->log->message(array(
561                                                'text' => 'W-LoginFailure, account loginid %1 is expired',
562                                                'p1'   => $this->account_lid,
563                                                'line' => __LINE__,
564                                                'file' => __FILE__
565                                        ));
566                                        $GLOBALS['phpgw']->log->commit();
567                                }
568                                $this->reason = 'account is expired';
569                                $this->cd_reason = 98;
570
571                                return False;
572                        }
573                        $GLOBALS['phpgw_info']['user']  = $this->user;
574                        $GLOBALS['phpgw_info']['hooks'] = $this->hooks;
575
576                        $this->appsession('password','phpgwapi',base64_encode($this->passwd));
577                        $this->appsession('browser_agent','phpgwapi',$GLOBALS['browser']->BROWSER_AGENT);
578                        if($this->certificate) $this->appsession('certificate','phpgwapi',$this->certificate);
579                        if ($GLOBALS['phpgw']->acl->check('anonymous',1,'phpgwapi'))
580                        {
581                                $session_flags = 'A';
582                        }
583                        else
584                        {
585                                $session_flags = 'N';
586                        }
587
588                        $GLOBALS['phpgw']->db->transaction_begin();
589                        $this->register_session($login,$user_ip,$now,$session_flags);
590                        if ($session_flags != 'A')              // dont log anonymous sessions
591                        {
592                                $this->log_access($this->sessionid,$login,$user_ip,$this->account_id);
593                        }
594                        $this->appsession('account_previous_login','phpgwapi',$GLOBALS['phpgw']->auth->previous_login);
595                        // Expresso
596                        //$GLOBALS['phpgw']->auth->update_lastlogin($this->account_id,$user_ip);
597                        $GLOBALS['phpgw']->db->transaction_commit();
598
599                        //if (!$this->sessionid) echo "<p>session::create(login='$login') = '$this->sessionid': lid='$this->account_lid', domain='$this->account_domain'</p>\n";
600
601                        return $this->sessionid;
602                }
603
604                /**
605                 * Retorna o UNIX DATE do ultimo acesso dessa conta, baseado na tabela de histórico.
606                 */
607                function get_last_access_on_history($account_id) {
608                        $GLOBALS['phpgw']->db->query("select li from phpgw_access_log where account_id='$account_id' order by li desc limit 1",__LINE__,__FILE__);
609                        if(!$GLOBALS['phpgw']->db->next_record())
610                                return false;
611                        return $GLOBALS['phpgw']->db->f('li');
612                }
613
614                /**
615        * Write or update (for logout) the access_log
616                *
617                * @param string $sessionid id of session or 0 for unsuccessful logins
618                * @param string $login account_lid (evtl. with domain) or '' for settion the logout-time
619                * @param string $user_ip ip to log
620                * @param int $account_id numerical account_id
621                */
622                function log_access($sessionid,$login='',$user_ip='',$account_id='')
623                {
624                        $now = time();
625
626                        if ($login != '')
627                        {
628                                if (strlen($login) > 30)
629                                {
630                                        $login = substr($login,0,30);
631                                }
632                                $GLOBALS['phpgw']->db->query('INSERT INTO phpgw_access_log(sessionid,loginid,ip,li,lo,account_id,browser)'
633                                        . " VALUES ('" . $sessionid . "','" . $this->db->db_addslashes($login). "','"
634                                        . $this->db->db_addslashes($user_ip) . "',$now,0," . (int)$account_id .",'".$this->db->db_addslashes(substr($_SERVER[ 'HTTP_USER_AGENT' ],0,199))."')",__LINE__,__FILE__);
635                        }
636                        else if($sessionid != 'bad login or password')
637                        {
638                                $GLOBALS['phpgw']->db->query("UPDATE phpgw_access_log SET lo=" . $now . " WHERE sessionid='"
639                                        . $sessionid . "'",__LINE__,__FILE__);
640                        }
641
642                        /* jakjr: Clean phpgw_access_log with a crontab event.
643                        if ($GLOBALS['phpgw_info']['server']['max_access_log_age'])
644                        {
645                                $max_age = $now - $GLOBALS['phpgw_info']['server']['max_access_log_age'] * 24 * 60 * 60;
646
647                                $GLOBALS['phpgw']->db->query("DELETE FROM phpgw_access_log WHERE li < $max_age");
648                        }
649                        */
650                }
651
652                /**
653                * Protect against brute force attacks, block login if too many unsuccessful login attmepts
654        *
655                * @param string $login account_lid (evtl. with domain)
656                * @param string $ip ip of the user
657                * @returns bool login blocked?
658                */
659                function login_blocked($login,$ip)
660                {
661                        /*jakjr: Disable this protection. When block an proxy server ip, all the sub-network will be blocking.*/
662                        //return false; //
663
664                        $blocked = False;
665                        $block_time = time() - $GLOBALS['phpgw_info']['server']['block_time'] * 60;
666                        /*
667                        $ip = $this->db->db_addslashes($ip);
668                        $this->db->query("SELECT count(*) FROM phpgw_access_log WHERE account_id=0 AND ip='$ip' AND li > $block_time",__LINE__,__FILE__);
669                        $this->db->next_record();
670                        if (($false_ip = $this->db->f(0)) > $GLOBALS['phpgw_info']['server']['num_unsuccessful_ip'])
671                        {
672                                //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";
673                                $blocked = True;
674                        }
675                        */
676                        $login = $this->db->db_addslashes($login);
677                        $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__);
678                        $this->db->next_record();
679                        if (($false_id = $this->db->f(0)) > $GLOBALS['phpgw_info']['server']['num_unsuccessful_id'])
680                        {
681                                //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";
682                                $blocked = True;
683                        }
684                        if ($blocked && $GLOBALS['phpgw_info']['server']['admin_mails'] &&
685                                // max. one mail each 5mins
686                                $GLOBALS['phpgw_info']['server']['login_blocked_mail_time'] < time()-5*60)
687                        {
688                                // notify admin(s) via email
689                                $from    = 'eGroupWare@'.$GLOBALS['phpgw_info']['server']['mail_suffix'];
690                                $subject = lang("eGroupWare: login blocked for user '%1', IP %2",$login,$ip);
691                                $body    = lang("Too many unsucessful attempts to login: %1 for the user '%2', %3 for the IP %4",$false_id,$login,$false_ip,$ip);
692                               
693                                if(!is_object($GLOBALS['phpgw']->send))
694                                {
695                                        $GLOBALS['phpgw']->send = CreateObject('phpgwapi.send');
696                                }
697                                $subject = $GLOBALS['phpgw']->send->encode_subject($subject);
698                                $admin_mails = explode(',',$GLOBALS['phpgw_info']['server']['admin_mails']);
699                                foreach($admin_mails as $to)
700                                {
701                                        $GLOBALS['phpgw']->send->msg('email',$to,$subject,$body,'','','',$from,$from);
702                                }
703                                // save time of mail, to not send to many mails
704                                $config = CreateObject('phpgwapi.config','phpgwapi');
705                                $config->read_repository();
706                                $config->value('login_blocked_mail_time',time());
707                                $config->save_repository();
708                        }
709                        return $blocked;
710                }
711
712                /**
713                * Verfy a peer server access request
714                *
715                * @param string $sessionid session id to verfiy
716                * @param string $kp3 ??
717                * @return bool verfied?
718                */
719                function verify_server($sessionid, $kp3)
720                {
721                        $GLOBALS['phpgw']->interserver = CreateObject('phpgwapi.interserver');
722                        $this->sessionid = $sessionid;
723                        $this->kp3       = $kp3;
724
725                        $session = $this->read_session();
726                        $this->session_flags = $session['session_flags'];
727
728                        list($this->account_lid,$this->account_domain) = explode('@', $session['session_lid']);
729                       
730                        if ($this->account_domain == '')
731                        {
732                                $this->account_domain = $GLOBALS['phpgw_info']['server']['default_domain'];
733                        }
734
735                        $GLOBALS['phpgw_info']['user']['kp3'] = $this->kp3;
736                        $phpgw_info_flags = $GLOBALS['phpgw_info']['flags'];
737
738                        $GLOBALS['phpgw_info']['flags'] = $phpgw_info_flags;
739
740                        $this->update_dla();
741                        $this->account_id = $GLOBALS['phpgw']->interserver->name2id($this->account_lid);
742
743                        if (!$this->account_id)
744                        {
745                                return False;
746                        }
747
748                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->account_id;
749
750                        $this->read_repositories(@$GLOBALS['phpgw_info']['server']['cache_phpgw_info']);
751
752                        /* init the crypto object before appsession call below */
753                        $this->key = md5($this->kp3 . $this->sessionid . $GLOBALS['phpgw_info']['server']['encryptkey']);
754                        $this->iv  = $GLOBALS['phpgw_info']['server']['mcrypt_iv'];
755                        $GLOBALS['phpgw']->crypto->init(array($this->key,$this->iv));
756
757                        $GLOBALS['phpgw_info']['user']  = $this->user;
758                        $GLOBALS['phpgw_info']['hooks'] = $this->hooks;
759
760                        $GLOBALS['phpgw_info']['user']['session_ip'] = $session['session_ip'];
761                        $GLOBALS['phpgw_info']['user']['passwd'] = base64_decode($this->appsession('password','phpgwapi'));
762
763                        if ($userid_array[1] != $GLOBALS['phpgw_info']['user']['domain'])
764                        {
765                                if(is_object($GLOBALS['phpgw']->log))
766                                {
767                                        $GLOBALS['phpgw']->log->message(array(
768                                                'text' => 'W-VerifySession, the domains %1 and %2 don\t match',
769                                                'p1'   => $userid_array[1],
770                                                'p2'   => $GLOBALS['phpgw_info']['user']['domain'],
771                                                'line' => __LINE__,
772                                                'file' => __FILE__
773                                        ));
774                                        $GLOBALS['phpgw']->log->commit();
775                                }
776
777                                if(is_object($GLOBALS['phpgw']->crypto))
778                                {
779                                        $GLOBALS['phpgw']->crypto->cleanup();
780                                        unset($GLOBALS['phpgw']->crypto);
781                                }
782                                return False;
783                        }
784
785                        if(@$GLOBALS['phpgw_info']['server']['sessions_checkip'])
786                        {
787                                if((PHP_OS != 'Windows') && (PHP_OS != 'WINNT') &&
788                                        (!$GLOBALS['phpgw_info']['user']['session_ip'] || $GLOBALS['phpgw_info']['user']['session_ip'] != $this->getuser_ip())
789                                )
790                                {
791                                        if(is_object($GLOBALS['phpgw']->log))
792                                        {
793                                                // This needs some better wording
794                                                $GLOBALS['phpgw']->log->message(array(
795                                                        'text' => 'W-VerifySession, IP %1 doesn\'t match IP %2 in session table',
796                                                        'p1'   => $this->getuser_ip(),
797                                                        'p2'   => $GLOBALS['phpgw_info']['user']['session_ip'],
798                                                        'line' => __LINE__,
799                                                        'file' => __FILE__
800                                                ));
801                                                $GLOBALS['phpgw']->log->commit();
802                                        }
803
804                                        if(is_object($GLOBALS['phpgw']->crypto))
805                                        {
806                                                $GLOBALS['phpgw']->crypto->cleanup();
807                                                unset($GLOBALS['phpgw']->crypto);
808                                        }
809                                        return False;
810                                }
811                        }
812
813                        $GLOBALS['phpgw']->acl->acl($this->account_id);
814                        $GLOBALS['phpgw']->accounts->accounts($this->account_id);
815                        $GLOBALS['phpgw']->preferences->preferences($this->account_id);
816                        $GLOBALS['phpgw']->applications->applications($this->account_id);
817
818                        if (! $this->account_lid)
819                        {
820                                if(is_object($GLOBALS['phpgw']->log))
821                                {
822                                        // This needs some better wording
823                                        $GLOBALS['phpgw']->log->message(array(
824                                                'text' => 'W-VerifySession, account_id is empty',
825                                                'line' => __LINE__,
826                                                'file' => __FILE__
827                                        ));
828                                        $GLOBALS['phpgw']->log->commit();
829                                }
830
831                                if(is_object($GLOBALS['phpgw']->crypto))
832                                {
833                                        $GLOBALS['phpgw']->crypto->cleanup();
834                                        unset($GLOBALS['phpgw']->crypto);
835                                }
836                                return False;
837                        }
838                        else
839                        {
840                                return True;
841                        }
842                }
843
844                /**
845                * Validate a peer server login request
846                *
847                * @param string $login login name
848                * @param string $password password
849                * @return bool login ok?
850                */
851                function create_server($login,$passwd)
852                {
853                        $GLOBALS['phpgw']->interserver = CreateObject('phpgwapi.interserver');
854                        $this->login  = $login;
855                        $this->passwd = $passwd;
856                        $this->clean_sessions();
857                        $login_array = explode('@', $login);
858                        $this->account_lid = $login_array[0];
859                        $now = time();
860
861                        if ($login_array[1] != '')
862                        {
863                                $this->account_domain = $login_array[1];
864                        }
865                        else
866                        {
867                                $this->account_domain = $GLOBALS['phpgw_info']['server']['default_domain'];
868                        }
869
870                        $serverdata = array(
871                                'server_name' => $this->account_domain,
872                                'username'    => $this->account_lid,
873                                'password'    => $passwd
874                        );
875                        if (!$GLOBALS['phpgw']->interserver->auth($serverdata))
876                        {
877                                return False;
878                                exit;
879                        }
880
881                        if (!$GLOBALS['phpgw']->interserver->exists($this->account_lid))
882                        {
883                                $this->account_id = $GLOBALS['phpgw']->interserver->name2id($this->account_lid);
884                        }
885                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->account_id;
886                        $GLOBALS['phpgw']->interserver->serverid = $this->account_id;
887
888                        $this->sessionid = md5($GLOBALS['phpgw']->common->randomstring(10));
889                        $this->kp3       = md5($GLOBALS['phpgw']->common->randomstring(15));
890
891                        /* re-init the crypto object */
892                        $this->key = md5($this->kp3 . $this->sessionid . $GLOBALS['phpgw_info']['server']['encryptkey']);
893                        $this->iv  = $GLOBALS['phpgw_info']['server']['mcrypt_iv'];
894                        $GLOBALS['phpgw']->crypto->init(array($this->key,$this->iv));
895
896                        //$this->read_repositories(False);
897
898                        $GLOBALS['phpgw_info']['user']  = $this->user;
899                        $GLOBALS['phpgw_info']['hooks'] = $this->hooks;
900
901                        $this->appsession('password','phpgwapi',base64_encode($this->passwd));
902                        $session_flags = 'S';
903
904                        $user_ip = $this->getuser_ip();
905
906                        $GLOBALS['phpgw']->db->transaction_begin();
907                        $this->register_session($login,$user_ip,$now,$session_flags);
908
909                        $this->log_access($this->sessionid,$login,$user_ip,$this->account_id);
910
911                        $this->appsession('account_previous_login','phpgwapi',$GLOBALS['phpgw']->auth->previous_login);
912                        $GLOBALS['phpgw']->auth->update_lastlogin($this->account_id,$user_ip);
913                        $GLOBALS['phpgw']->db->transaction_commit();
914
915                        return array($this->sessionid,$this->kp3);
916                }
917
918                /**
919                * Functions for appsession data and session cache
920                */
921
922                /**
923                * Is this also useless?? (skwashd)
924                */
925                function read_repositories($cached='',$write_cache=True)
926                {
927                        $GLOBALS['phpgw']->acl->acl($this->account_id);
928                        $GLOBALS['phpgw']->accounts->accounts($this->account_id);
929                        $GLOBALS['phpgw']->preferences->preferences($this->account_id);
930                        $GLOBALS['phpgw']->applications->applications($this->account_id);
931
932                        if(@$cached)
933                        {
934                                $this->user = $this->appsession('phpgw_info_cache','phpgwapi');
935                                if(!empty($this->user))
936                                {
937                                        $GLOBALS['phpgw']->preferences->data = $this->user['preferences'];
938                                        if (!isset($GLOBALS['phpgw_info']['apps']) || !is_array($GLOBALS['phpgw_info']['apps']))
939                                        {
940                                                $GLOBALS['phpgw']->applications->read_installed_apps();
941                                        }
942                                }
943                                else
944                                {
945                                        $this->setup_cache($write_cache);
946                                }
947                        }
948                        else
949                        {
950                                $this->setup_cache($write_cache);
951                        }
952                        $this->hooks = $GLOBALS['phpgw']->hooks->read();
953                }
954
955                /**
956                * Is this also useless?? (skwashd)
957                */
958                function setup_cache($write_cache=True)
959                {
960                        $this->user                = $GLOBALS['phpgw']->accounts->read_repository();
961                        $this->user['acl']         = $GLOBALS['phpgw']->acl->read_repository();
962                        $this->user['preferences'] = $GLOBALS['phpgw']->preferences->read_repository();
963                        $this->user['apps']        = $GLOBALS['phpgw']->applications->read_repository();
964                        //@reset($this->data['user']['apps']);
965
966                        $this->user['domain']      = $this->account_domain;
967                        $this->user['sessionid']   = $this->sessionid;
968                        $this->user['kp3']         = $this->kp3;
969                        $this->user['session_ip']  = $this->getuser_ip();
970                        $this->user['session_lid'] = $this->account_lid.'@'.$this->account_domain;
971                        $this->user['account_id']  = $this->account_id;
972                        $this->user['account_lid'] = $this->account_lid;
973                        $this->user['userid']      = $this->account_lid;
974                        $this->user['passwd']      = @$this->passwd;
975                        if(@$GLOBALS['phpgw_info']['server']['cache_phpgw_info'] && $write_cache)
976                        {
977                                $this->delete_cache();
978                                $this->appsession('phpgw_info_cache','phpgwapi',$this->user);
979                        }
980                }
981       
982                /**
983                * This looks to be useless
984                * This will capture everything in the $GLOBALS['phpgw_info'] including server info,
985                * and store it in appsessions.  This is really incompatible with any type of restoring
986                * from appsession as the saved user info is really in ['user'] rather than the root of
987                * the structure, which is what this class likes.
988                */
989                function save_repositories()
990                {
991                        $phpgw_info_temp = $GLOBALS['phpgw_info'];
992                        $phpgw_info_temp['user']['kp3'] = '';
993                        $phpgw_info_temp['flags'] = array();
994
995                        if ($GLOBALS['phpgw_info']['server']['cache_phpgw_info'])
996                        {
997                                $this->appsession('phpgw_info_cache','phpgwapi',$phpgw_info_temp);
998                        }
999                }
1000
1001                function restore()
1002                {
1003                        $sessionData = $this->appsession('sessiondata');
1004
1005                        if (!empty($sessionData) && is_array($sessionData))
1006                        {
1007                                foreach($sessionData as $key => $value)
1008                                {
1009                                        global $$key;
1010                                        $$key = $value;
1011                                        $this->variableNames[$key] = 'registered';
1012                                        // echo 'restored: '.$key.', ' . $value . '<br>';
1013                                }
1014                        }
1015                }
1016
1017                /**
1018                * Save the current values of all registered variables
1019                */
1020                function save()
1021                {
1022                        if (is_array($this->variableNames))
1023                        {
1024                                reset($this->variableNames);
1025                                while(list($key, $value) = each($this->variableNames))
1026                                {
1027                                        if ($value == 'registered')
1028                                        {
1029                                                global $$key;
1030                                                $sessionData[$key] = $$key;
1031                                        }
1032                                }
1033                                $this->appsession('sessiondata','',$sessionData);
1034                        }
1035                }
1036
1037                /**
1038                * Create a list a variable names, which data needs to be restored
1039                *
1040                * @param string $_variableName name of variable to be registered
1041                */
1042                function register($_variableName)
1043                {
1044                        $this->variableNames[$_variableName]='registered';
1045                        #print 'registered '.$_variableName.'<br>';
1046                }
1047
1048                /**
1049                * Mark variable as unregistered
1050                *
1051                * @param string $_variableName name of variable to deregister
1052                */
1053                function unregister($_variableName)
1054                {
1055                        $this->variableNames[$_variableName]='unregistered';
1056                        #print 'unregistered '.$_variableName.'<br>';
1057                }
1058
1059                /**
1060                * Check if we have a variable registred already
1061                *
1062                * @param string $_variableName name of variable to check
1063                * @return bool was the variable found?
1064                */
1065                function is_registered($_variableName)
1066                {
1067                        if ($this->variableNames[$_variableName] == 'registered')
1068                        {
1069                                return True;
1070                        }
1071                        else
1072                        {
1073                                return False;
1074                        }
1075                }
1076                /**
1077                * Additional tracking of user actions - prevents reposts/use of back button
1078                *
1079                * @author skwashd
1080                * @return string current history id
1081                */
1082                function generate_click_history()
1083                {
1084                        if(!isset($this->history_id))
1085                        {
1086                                $this->history_id = md5($this->login . time());
1087                                $history = $this->appsession($location = 'history', $appname = 'phpgwapi');
1088                               
1089                                if(count($history) >= $GLOBALS['phpgw_info']['server']['max_history'])
1090                                {
1091                                        array_shift($history);
1092                                        $this->appsession($location = 'history', $appname = 'phpgwapi', $history);
1093                                }
1094                        }
1095                        return $this->history_id;
1096                }
1097               
1098                /**
1099                * Detects if the page has already been called before - good for forms
1100                *
1101                * @author skwashd
1102                * @param bool $diplay_error when implemented will use the generic error handling code
1103                * @return True if called previously, else False - call ok
1104                */
1105                function is_repost($display_error = False)
1106                {
1107                        $history = $this->appsession($location = 'history', $appname = 'phpgwapi');
1108                        if(isset($history[$_GET['click_history']]))
1109                        {
1110                                if($display_error)
1111                                {
1112                                        $GLOBALS['phpgw']->redirect_link('/error.php', 'type=repost');//more on this later :)
1113                                }
1114                                else
1115                                {
1116                                        return True; //handled by the app
1117                                }
1118                        }
1119                        else
1120                        {
1121                                $history[$_GET['click_history']] = True;
1122                                $this->appsession($location = 'history', $appname = 'phpgwapi', $history);
1123                                return False;
1124                        }
1125                }
1126
1127                /**
1128                * Generate a url which supports url or cookies based sessions
1129                *
1130                * @param string $url a url relative to the egroupware install root
1131                * @param array $extravars query string arguements
1132                * @return string generated url
1133                */
1134                function link($url, $extravars = '')
1135                {
1136                        //echo "<p>session::link(url='".print_r($url,True)."',extravars='".print_r($extravars,True)."')";
1137                        /* first we process the $url to build the full scriptname */
1138                        $full_scriptname = True;
1139
1140                        $url_firstchar = substr($url ,0,1);
1141                        if ($url_firstchar == '/' && $GLOBALS['phpgw_info']['server']['webserver_url'] == '/')
1142                        {
1143                                $full_scriptname = False;
1144                        }
1145
1146                        if ($url_firstchar != '/')
1147                        {
1148                                $app = $GLOBALS['phpgw_info']['flags']['currentapp'];
1149                                if ($app != 'home' && $app != 'login' && $app != 'logout')
1150                                {
1151                                        $url = $app.'/'.$url;
1152                                }
1153                        }
1154
1155                        if($full_scriptname)
1156                        {
1157                                $webserver_url_count = strlen($GLOBALS['phpgw_info']['server']['webserver_url'])-1;
1158                                if(substr($GLOBALS['phpgw_info']['server']['webserver_url'] ,$webserver_url_count,1) != '/' && $url_firstchar != '/')
1159                                {
1160                                        $url = $GLOBALS['phpgw_info']['server']['webserver_url'] .'/'. $url;
1161                                }
1162                                else
1163                                {
1164                                        $url = $GLOBALS['phpgw_info']['server']['webserver_url'] . $url;
1165                                }
1166                        }
1167
1168                        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
1169                        {
1170                                if(substr($url ,0,4) != 'http')
1171                                {
1172                                        $url = 'https://'.$GLOBALS['phpgw_info']['server']['hostname'].$url;
1173                                }
1174                                else
1175                                {
1176                                        $url = str_replace ( 'http:', 'https:', $url);
1177                                }
1178                        }
1179
1180                        /* Now we process the extravars into a proper url format */
1181                        /* if its not an array, then we turn it into one */
1182                        /* We do this to help prevent any duplicates from being sent. */
1183                        if (!is_array($extravars) && $extravars != '')
1184                        {
1185                                $new_extravars = Array();
1186
1187                                $a = explode('&', $extravars);
1188                                $i = 0;
1189                                while ($i < count($a))
1190                                {
1191                                        $b = split('=', $a[$i],2);
1192                                        // Check if this value doesn't already exist in new_extravars
1193                                        if(array_key_exists($b[0], $new_extravars))
1194                                        {
1195                                                // print "Debug::Error !!! " . $b[0] . " ($i) already exists<br>";
1196                                                if( eregi("\[\]", $b[0]) )
1197                                                {
1198                                                        $b[0] = eregi_replace("\[\]", "[$i]", $b[0]);
1199                                                }
1200                                        }
1201
1202                                        $new_extravars[$b[0]] = $b[1];
1203                                        $i++;
1204                                }
1205                                $extravars = $new_extravars;
1206                                unset($new_extravars);
1207                        }
1208
1209                        /* if using frames we make sure there is a framepart */
1210                        if(@defined('PHPGW_USE_FRAMES') && PHPGW_USE_FRAMES)
1211                        {
1212                                if (!isset($extravars['framepart']))
1213                                {
1214                                        $extravars['framepart']='body';
1215                                }
1216                        }
1217
1218                        /* add session params if not using cookies */
1219                        if (@!$GLOBALS['phpgw_info']['server']['usecookies'])
1220                        {
1221                                $extravars['sessionid'] = $this->sessionid;
1222                                $extravars['kp3'] = $this->kp3;
1223                                $extravars['domain'] = $this->account_domain;
1224                        }
1225
1226                        //used for repost prevention
1227//                      $extravars['click_history'] = $this->generate_click_history();
1228
1229                        /* if we end up with any extravars then we generate the url friendly string */
1230                        if (is_array($extravars))
1231                        {
1232                                $new_extravars = '';
1233                                foreach($extravars as $key => $value)
1234                                {
1235                                        if (!empty($new_extravars))
1236                                        {
1237                                                $new_extravars .= '&';
1238                                        }
1239                                        $new_extravars .= $key.'='.urlencode($value);
1240                                }
1241                                $url .= '?' . $new_extravars;
1242                        }
1243                        //echo " = '$url'</p>\n";
1244                        return $url;
1245                }
1246
1247                /**
1248                * The remaining methods are abstract - as they are unique for each session handler
1249                */
1250
1251                /**
1252                * Load user's session information
1253                *
1254                * The sessionid of the session to read is passed in the class-var $this->sessionid
1255                *
1256                * @return mixed the session data
1257                */
1258                function read_session()
1259                {}
1260
1261                /**
1262                * Remove stale sessions out of the database
1263                */
1264                function clean_sessions()
1265                {}
1266
1267                /**
1268                * Set paramaters for cookies - only implemented in PHP4 sessions
1269                *
1270                * @param string $domain domain name to use in cookie
1271                */
1272
1273                function set_cookie_params($domain)
1274                {}
1275
1276                /**
1277                * Create a new session id
1278                *
1279                * @return string a new session id
1280                */
1281                function new_session_id()
1282                {}
1283
1284                /**
1285                * Create a new session
1286                *
1287                * @param string $login user login
1288                * @param string $user_ip users ip address
1289                * @param int $now time now as a unix timestamp
1290                * @param string $session_flags A = Anonymous, N = Normal
1291                */
1292                function register_session($login,$user_ip,$now,$session_flags)
1293                {}
1294
1295                /**
1296                * Update the date last active info for the session, so the login does not expire
1297                *
1298                * @return bool did it suceed?
1299                */
1300                function update_dla()
1301                {}
1302
1303                /**
1304                * Terminate a session
1305                *
1306                * @param string $sessionid the id of the session to be terminated
1307                * @param string $kp3 - NOT SURE
1308                * @return bool did it suceed?
1309                */
1310                function destroy($sessionid, $kp3)
1311                {}
1312
1313                /**
1314                * Functions for appsession data and session cache
1315                */
1316       
1317                /**
1318                * Delete all data from the session cache for a user
1319                *
1320                * @param int $accountid user account id, defaults to current user (optional)
1321                */
1322                function delete_cache($accountid='')
1323                {}
1324
1325                /**
1326                * Stores or retrieves information from the sessions cache
1327                *
1328                * @param string $location identifier for data
1329                * @param string $appname name of app which is responsbile for the data
1330                * @param mixed $data data to be stored, if left blank data is retreived (optional)
1331                * @return mixed data from cache, only returned if $data arg is not used
1332                */
1333                function appsession($location = 'default', $appname = '', $data = '##NOTHING##')
1334                {}
1335
1336                /**
1337                * Get list of normal / non-anonymous sessions
1338                * Note: The data from the session-files get cached in the app_session phpgwapi/php4_session_cache
1339                *
1340                * @author ralfbecker
1341                * @param int $start session to start at
1342                * @param string $order field to sort on
1343                * @param string $sort sort order
1344                * @param bool $all_no_sort list all with out sorting (optional) default False
1345                * @return array info for all current sessions
1346                */
1347                function list_sessions($start,$order,$sort,$all_no_sort = False)
1348                {}
1349               
1350                /**
1351                * Get the number of normal / non-anonymous sessions
1352                *
1353                * @author ralfbecker
1354                * @return int number of sessions
1355                */
1356                function total()
1357                {}
1358        }
1359
1360        if(empty($GLOBALS['phpgw_info']['server']['sessions_type']))
1361        {
1362                $GLOBALS['phpgw_info']['server']['sessions_type'] = 'php4';     // the more performant default
1363        }
1364        // for php4 sessions, check if the extension is loaded, try loading it and fallback to db sessions if not
1365        if ($GLOBALS['phpgw_info']['server']['sessions_type'] == 'php4' && !extension_loaded('session'))
1366        {
1367                // some constanst for pre php4.3
1368                if (!defined('PHP_SHLIB_SUFFIX'))
1369                {
1370                        define('PHP_SHLIB_SUFFIX',strtoupper(substr(PHP_OS, 0,3)) == 'WIN' ? 'dll' : 'so');
1371                }
1372                if (!defined('PHP_SHLIB_PREFIX'))
1373                {
1374                        define('PHP_SHLIB_PREFIX',PHP_SHLIB_SUFFIX == 'dll' ? 'php_' : '');
1375                }
1376                if (!function_exists('dl') || !@dl(PHP_SHLIB_PREFIX.'session'.'.'.PHP_SHLIB_SUFFIX))
1377                {
1378                        $GLOBALS['phpgw_info']['server']['sessions_type'] = 'db';       // fallback if we have no php4 sessions support
1379                }
1380        }
1381        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.