]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Session.php
Some minor refactoring on session handler
[quix0rs-gnu-social.git] / classes / Session.php
1 <?php
2 /**
3  * Table Definition for session
4  *
5  * StatusNet - the distributed open-source microblogging tool
6  * Copyright (C) 2009, StatusNet, Inc.
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU Affero General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU Affero General Public License for more details.
17  *
18  * You should have received a copy of the GNU Affero General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 if (!defined('STATUSNET') && !defined('LACONICA')) {
23     exit(1);
24 }
25
26 require_once INSTALLDIR . '/classes/Memcached_DataObject.php';
27
28 class Session extends Managed_DataObject
29 {
30     ###START_AUTOCODE
31     /* the code below is auto generated do not remove the above tag */
32
33     public $__table = 'session';             // table name
34     public $id;                              // varchar(32)  primary_key not_null
35     public $session_data;                    // text()
36     public $created;                         // datetime()   not_null
37     public $modified;                        // timestamp()  not_null default_CURRENT_TIMESTAMP
38
39     /* the code above is auto generated do not remove the tag below */
40     ###END_AUTOCODE
41
42     public static function schemaDef()
43     {
44         return [
45             'fields' => [
46                 'id'           => ['type' => 'varchar', 'length' => 32, 'not null' => true, 'description' => 'session ID'],
47                 'session_data' => ['type' => 'text', 'description' => 'session data'],
48                 'created'      => ['type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'],
49                 'modified'     => ['type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'],
50             ],
51             'primary key' => ['id'],
52             'indexes' => [
53                 'session_modified_idx' => ['modified'],
54             ],
55         ];
56     }
57
58     static function open($save_path, $session_name)
59     {
60         return true;
61     }
62
63     static function close()
64     {
65         return true;
66     }
67
68     static function read($id)
69     {
70         self::logdeb("Fetching session '$id'");
71
72         $session = Session::getKV('id', $id);
73
74         if (empty($session)) {
75             self::logdeb("Couldn't find '$id'");
76             return '';
77         } else {
78             self::logdeb("Found '$id', returning " .
79                          strlen($session->session_data) .
80                          " chars of data");
81             return (string)$session->session_data;
82         }
83     }
84
85     static function logdeb($msg)
86     {
87         if (common_config('sessions', 'debug')) {
88             common_debug("Session: " . $msg);
89         }
90     }
91
92     static function write($id, $session_data)
93     {
94         self::logdeb("Writing session '$id'");
95
96         $session = Session::getKV('id', $id);
97
98         if (empty($session)) {
99             self::logdeb("'$id' doesn't yet exist; inserting.");
100             $session = new Session();
101
102             $session->id = $id;
103             $session->session_data = $session_data;
104             $session->created = common_sql_now();
105
106             $result = $session->insert();
107
108             if (!$result) {
109                 common_log_db_error($session, 'INSERT', __FILE__);
110                 self::logdeb("Failed to insert '$id'.");
111             } else {
112                 self::logdeb("Successfully inserted '$id' (result = $result).");
113             }
114             return $result;
115         } else {
116             self::logdeb("'$id' already exists; updating.");
117             if (strcmp($session->session_data, $session_data) == 0) {
118                 self::logdeb("Not writing session '$id'; unchanged");
119                 return true;
120             } else {
121                 self::logdeb("Session '$id' data changed; updating");
122
123                 $orig = clone($session);
124
125                 $session->session_data = $session_data;
126
127                 $result = $session->update($orig);
128
129                 if (!$result) {
130                     common_log_db_error($session, 'UPDATE', __FILE__);
131                     self::logdeb("Failed to update '$id'.");
132                 } else {
133                     self::logdeb("Successfully updated '$id' (result = $result).");
134                 }
135
136                 return $result;
137             }
138         }
139     }
140
141     static function gc($maxlifetime)
142     {
143         self::logdeb("garbage collection (maxlifetime = $maxlifetime)");
144
145         $epoch = common_sql_date(time() - $maxlifetime);
146
147         $ids = [];
148
149         $session = new Session();
150         $session->whereAdd('modified < "' . $epoch . '"');
151         $session->selectAdd();
152         $session->selectAdd('id');
153
154         $limit = common_config('sessions', 'gc_limit');
155         if ($limit > 0) {
156             // On large sites, too many sessions to expire
157             // at once will just result in failure.
158             $session->limit($limit);
159         }
160
161         $session->find();
162
163         while ($session->fetch()) {
164             $ids[] = $session->id;
165         }
166
167         $session->free();
168
169         self::logdeb("Found " . count($ids) . " ids to delete.");
170
171         foreach ($ids as $id) {
172             self::logdeb("Destroying session '$id'.");
173             self::destroy($id);
174         }
175     }
176
177     static function destroy($id)
178     {
179         self::logdeb("Deleting session $id");
180
181         $session = Session::getKV('id', $id);
182
183         if (empty($session)) {
184             self::logdeb("Can't find '$id' to delete.");
185             return false;
186         } else {
187             $result = $session->delete();
188             if (!$result) {
189                 common_log_db_error($session, 'DELETE', __FILE__);
190                 self::logdeb("Failed to delete '$id'.");
191             } else {
192                 self::logdeb("Successfully deleted '$id' (result = $result).");
193             }
194             return $result;
195         }
196     }
197
198     static function setSaveHandler()
199     {
200         self::logdeb("setting save handlers");
201         $result = session_set_save_handler('Session::open', 'Session::close', 'Session::read',
202                                            'Session::write', 'Session::destroy', 'Session::gc');
203         self::logdeb("save handlers result = $result");
204
205         // PHP 5.3 with APC ends up destroying a bunch of object stuff before the session
206         // save handlers get called on request teardown.
207         // Registering an explicit shutdown function should take care of this before
208         // everything breaks on us.
209         register_shutdown_function('Session::cleanup');
210
211         return $result;
212     }
213
214     static function cleanup()
215     {
216         session_write_close();
217     }
218 }