Platform  3.1
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
Class.Session.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @license http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Anakeen - licence CC
5  * @package FDL
6 */
7 /**
8  * Generated Header (not documented yet)
9  *
10  * @author Anakeen 2000
11  * @version $Id: Class.Session.php,v 1.38 2009/01/12 15:15:31 jerome Exp $
12  * @license http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Anakeen - licence CC
13  * @package FDL
14  * @subpackage CORE
15  */
16 /**
17  */
18 // ---------------------------------------------------------------------------
19 // Marc Claverie (marc.claverie@anakeen.com)- anakeen 2000
20 // ---------------------------------------------------------------------------
21 // This program is free software; you can redistribute it and/or modify
22 // it under the terms of the GNU General Public License as published by
23 // the Free Software Foundation; either version 2 of the License, or (at
24 // your option) any later version.
25 //
26 // This program is distributed in the hope that it will be useful, but
27 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
28 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
29 // for more details.
30 //
31 // You should have received a copy of the GNU General Public License along
32 // with this program; if not, write to the Free Software Foundation, Inc.,
33 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 // ---------------------------------------------------------------------------
35 // $Id: Class.Session.php,v 1.38 2009/01/12 15:15:31 jerome Exp $
36 //
37 // ---------------------------------------------------------------------------
38 // Syntaxe :
39 // ---------
40 // $session = new Session();
41 //
42 // ---------------------------------------------------------------------------
43 $CLASS_SESSION_PHP = '$Id: Class.Session.php,v 1.38 2009/01/12 15:15:31 jerome Exp $';
44 include_once ('Class.QueryDb.php');
45 include_once ('Class.DbObj.php');
46 include_once ('Class.Log.php');
47 include_once ('Class.User.php');
48 include_once ('Class.SessionConf.php');
49 include_once ("Class.SessionCache.php");
50 
51 class Session extends DbObj
52 {
53 
54  var $fields = array(
55  "id",
56  "userid",
57  "name",
58  "last_seen"
59  );
60 
61  var $id_fields = array(
62  "id"
63  );
64 
65  var $dbtable = "sessions";
66 
67  var $sqlcreate = "create table sessions ( id varchar(100),
68  userid int,
69  name text not null,
70  last_seen timestamp not null DEFAULT now() );
71  create unique index sessions_idx on sessions(id);
72  create index sessions_idx_name on sessions(name);
73  create index sessions_idx_userid on sessions(userid);";
74 
75  var $isCacheble = false;
77 
78  var $session_name = 'freedom_param';
79 
80  function __construct($session_name = 'freedom_param')
81  {
82  parent::__construct();
83  if ($session_name != '') $this->session_name = $session_name;
84  $this->last_seen = strftime('%d/%m/%Y %H:%M:%S %Z', time());
85  }
86 
87  function Set($id = "")
88  {
89  global $_SERVER;
90 
91  if (!$this->sessionDirExistsAndIsWritable()) {
92  return false;
93  }
94 
95  $this->gcSessions();
96 
97  $query = new QueryDb($this->dbaccess, "Session");
98  $query->addQuery("id = '" . pg_escape_string($id) . "'");
99  $list = $query->Query(0, 0, "TABLE");
100  $createNewSession = true;
101  if ($query->nb != 0) {
102  $this->Affect($list[0]);
103  if (!$this->hasExpired()) {
104  $createNewSession = false;
105  $this->touch();
106  session_name($this->session_name);
107  session_id($id);
108  @session_start();
109  @session_write_close(); // avoid block
110 
111  }
112  }
113 
114  if ($createNewSession) {
115  $u = new User();
116  if ($u->SetLoginName($_SERVER['PHP_AUTH_USER'])) {
117  $this->open($u->id);
118  } else {
119  $this->open(ANONYMOUS_ID); //anonymous session
120 
121  }
122  }
123  // set cookie session
124  if ($_SERVER['HTTP_HOST'] != "") {
125  if (!$_SERVER["REDIRECT_URL"]) {
126  $this->setCookieSession($this->id, $this->SetTTL());
127  }
128  }
129  return true;
130  }
131 
132  function setCookieSession($id, $ttl = 0)
133  {
134  $turl = @parse_url($_SERVER["REQUEST_URI"]);
135  if ($turl['path']) {
136  if (substr($turl['path'], -1) != '/') {
137  $path = dirname($turl['path']) . '/';
138  } else {
139  $path = $turl['path'];
140  }
141  $path = preg_replace(':/+:', '/', $path);
142  setcookie($this->name, $id, $ttl, $path);
143  } else {
144  setcookie($this->name, $id, $ttl);
145  }
146  }
147  /**
148  * Closes session and removes all datas
149  */
150  function Close()
151  {
152  global $_SERVER; // use only cache with HTTP
153  if ($_SERVER['HTTP_HOST'] != "") {
154  session_name($this->name);
155  session_id($this->id);
156  @session_unset();
157  @session_destroy();
158  @session_write_close();
159  // delete session cookie
160  setcookie($this->name, false, time() - 3600);
161  $this->Delete();
162  }
163  $this->status = $this->SESSION_CT_CLOSE;
164  return $this->status;
165  }
166  /**
167  * Closes all session
168  */
169  function CloseAll()
170  {
171  $this->exec_query("delete from sessions where name = '" . pg_escape_string($this->name) . "'");
172  $this->status = $this->SESSION_CT_CLOSE;
173  return $this->status;
174  }
175  /**
176  * Closes all user's sessions
177  */
178  function CloseUsers($uid = - 1)
179  {
180  if (!$uid > 0) return;
181  $this->exec_query("delete from sessions where userid= '" . pg_escape_string($uid) . "'");
182  $this->status = $this->SESSION_CT_CLOSE;
183  return $this->status;
184  }
185 
186  function Open($uid = ANONYMOUS_ID)
187  {
188  $idsess = $this->newId();
189  global $_SERVER; // use only cache with HTTP
190  if ($_SERVER['HTTP_HOST'] != "") {
191  session_name($this->session_name);
192  session_id($idsess);
193  @session_start();
194  @session_write_close(); // avoid block
195  // $this->initCache();
196 
197  }
198  $this->name = $this->session_name;
199  $this->id = $idsess;
200  $this->userid = $uid;
201  $this->last_seen = strftime('%d/%m/%Y %H:%M:%S %Z', time());
202  $this->Add();
203  $this->log->debug("Nouvelle Session : {$this->id}");
204  }
205  // --------------------------------
206  // Stocke une variable de session args
207  // $v est une chaine !
208  // --------------------------------
209  function Register($k = "", $v = "")
210  {
211 
212  if ($k == "") {
213  $this->status = $this->SESSION_CT_ARGS;
214  return $this->status;
215  }
216  // global $_SESSION;
217  // $$k=$v;
218  global $_SERVER; // use only cache with HTTP
219  if ($_SERVER['HTTP_HOST'] != "") {
220  // session_register($k);
221  session_name($this->name);
222  session_id($this->id);
223  @session_start();
224  $_SESSION[$k] = $v;
225  @session_write_close(); // avoid block
226 
227  }
228 
229  return true;
230  }
231  // --------------------------------
232  // Récupère une variable de session
233  // $v est une chaine !
234  // --------------------------------
235  function Read($k = "", $d = "")
236  {
237  if ($_SERVER['HTTP_HOST'] != "") {
238  session_name($this->name);
239  session_id($this->id);
240  @session_start();
241  if (isset($_SESSION[$k])) {
242  $val = $_SESSION[$k];
243  @session_write_close();
244  return $val;
245  } else {
246  @session_write_close();
247  return ($d);
248  }
249  }
250  return ($d);
251  }
252  // --------------------------------
253  // Détruit une variable de session
254  // $v est une chaine !
255  // --------------------------------
256  function Unregister($k = "")
257  {
258  global $_SERVER; // use only cache with HTTP
259  if ($_SERVER['HTTP_HOST'] != "") {
260  session_name($this->name);
261  session_id($this->id);
262  @session_start();
263  unset($_SESSION[$k]);
264  @session_write_close(); // avoid block
265 
266  }
267  return;
268  }
269  // ------------------------------------------------------------------------
270  // utilities functions (private)
271  // ------------------------------------------------------------------------
272  function newId()
273  {
274  $this->log->debug("newId");
275  $magic = new SessionConf($this->dbaccess, "MAGIC");
276  $m = $magic->val;
277  unset($magic);
278  return md5(uniqid($m));
279  }
280 
281  function SetTTL()
282  {
283  $ttliv = $this->getSessionTTL(0);
284  if ($ttliv > 0) {
285  //$ttli->CloseConnect();
286  return (time() + $ttliv);
287  }
288  return 0;
289  }
290 
291  function getSessionTTL($default = 0, $ttlParamName = '')
292  {
293  if ($ttlParamName == '') {
294  if ($this->userid == ANONYMOUS_ID) {
295  $ttlParamName = 'CORE_GUEST_SESSIONTTL';
296  } else {
297  $ttlParamName = 'CORE_SESSIONTTL';
298  }
299  }
300  return getParam($ttlParamName, $default);
301  }
302 
303  function getSessionGcProbability($default = "0.01")
304  {
305  return getParam("CORE_SESSIONGCPROBABILITY", $default);
306  }
307 
308  function touch()
309  {
310  $this->last_seen = strftime('%d/%m/%Y %H:%M:%S %Z', time());
311  $err = $this->modify();
312  return $err;
313  }
314 
316  {
317  $ttl = $this->getSessionTTL(0, 'CORE_SESSIONTTL');
318  if ($ttl > 0) {
319  return $this->exec_query(sprintf("DELETE FROM sessions WHERE userid != %s AND last_seen < timestamp 'now()' - interval '%s seconds'", ANONYMOUS_ID, pg_escape_string($ttl)));
320  }
321  return '';
322  }
323 
325  {
326  $ttl = $this->getSessionTTL(0, 'CORE_GUEST_SESSIONTTL');
327  if ($ttl > 0) {
328  return $this->exec_query(sprintf("DELETE FROM sessions WHERE userid = %s AND last_seen < timestamp 'now()' - interval '%s seconds'", ANONYMOUS_ID, pg_escape_string($ttl)));
329  }
330  return '';
331  }
332 
333  function gcSessions()
334  {
335  $gcP = $this->getSessionGcProbability();
336  if ($gcP <= 0) {
337  return "";
338  }
339  $p = rand() / getrandmax();
340  if ($p <= $gcP) {
341  $err = $this->deleteUserExpiredSessions();
342  if ($err != "") {
343  error_log(__CLASS__ . "::" . __FUNCTION__ . " " . "Error cleaning up user sessions: " . $err);
344  }
345  $err = $this->deleteGuestExpiredSessions();
346  if ($err != "") {
347  error_log(__CLASS__ . "::" . __FUNCTION__ . " " . "Error cleaning up guest sessions: " . $err);
348  }
349  }
350  return "";
351  }
352 
353  function setuid($uid)
354  {
355  if (!is_numeric($uid)) {
356  $u = new User();
357  if ($u->SetLoginName($uid)) {
358  $uid = $u->id;
359  } else {
360  $err = "Could not resolve login name '" . $uid . "' to uid";
361  error_log(__CLASS__ . "::" . __FUNCTION__ . " " . $err);
362  return $err;
363  }
364  }
365  $this->userid = $uid;
366  return $this->modify();
367  }
368 
370  {
371  include_once ('WHAT/Lib.Prefix.php');
372 
373  global $pubdir;
374 
375  $sessionDir = sprintf("%s/session", $pubdir);
376  if (!is_dir($sessionDir)) {
377  trigger_error(sprintf("Session directory '%s' does not exists.", $sessionDir));
378  return false;
379  }
380 
381  if (!is_writable($sessionDir)) {
382  trigger_error(sprintf("Session directory '%s' is not writable.", $sessionDir));
383  return false;
384  }
385 
386  return true;
387  }
388 
389  function hasExpired()
390  {
391  include_once ('FDL/Lib.Util.php');
392  $ttl = $this->getSessionTTL(0);
393  if ($ttl > 0) {
394  $now = time();
395  $last_seen = stringDateToUnixTs($this->last_seen);
396  if ($now > $last_seen + $ttl) {
397  return true;
398  }
399  }
400  return false;
401  }
402 
403  function removeSessionFile($sessid = null)
404  {
405  include_once ('WHAT/Lib.Prefix.php');
406  global $pubdir;
407  if ($sessid === null) {
408  $sessid = $this->id;
409  }
410  $sessionFile = sprintf("%s/session/sess_%s", $pubdir, $sessid);
411  if (file_exists($sessionFile)) {
412  unlink($sessionFile);
413  }
414  }
415 } // Class Session
416 
417 ?>
← centre documentaire © anakeen - published under CC License - Dynacase