]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
add inbox data class
[quix0rs-gnu-social.git] / classes / Memcached_DataObject.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
23
24 class Memcached_DataObject extends DB_DataObject
25 {
26     /**
27      * Destructor to free global memory resources associated with
28      * this data object when it's unset or goes out of scope.
29      * DB_DataObject doesn't do this yet by itself.
30      */
31
32     function __destruct()
33     {
34         $this->free();
35         if (method_exists('DB_DataObject', '__destruct')) {
36             parent::__destruct();
37         }
38     }
39
40     /**
41      * Wrapper for DB_DataObject's static lookup using memcached
42      * as backing instead of an in-process cache array.
43      *
44      * @param string $cls classname of object type to load
45      * @param mixed $k key field name, or value for primary key
46      * @param mixed $v key field value, or leave out for primary key lookup
47      * @return mixed Memcached_DataObject subtype or false
48      */
49     function &staticGet($cls, $k, $v=null)
50     {
51         if (is_null($v)) {
52             $v = $k;
53             # XXX: HACK!
54             $i = new $cls;
55             $keys = $i->keys();
56             $k = $keys[0];
57             unset($i);
58         }
59         $i = Memcached_DataObject::getcached($cls, $k, $v);
60         if ($i) {
61             return $i;
62         } else {
63             $i = DB_DataObject::staticGet($cls, $k, $v);
64             if ($i) {
65                 // DB_DataObject's in-process lookup cache interferes with GC
66                 // to cause massive memory leaks in long-running processes.
67                 if (php_sapi_name() == 'cli') {
68                     $i->_clear_cache();
69                 }
70                 
71                 // Now store it into the shared memcached, if present...
72                 $i->encache();
73             }
74             return $i;
75         }
76     }
77
78     function &pkeyGet($cls, $kv)
79     {
80         $i = Memcached_DataObject::multicache($cls, $kv);
81         if ($i) {
82             return $i;
83         } else {
84             $i = new $cls();
85             foreach ($kv as $k => $v) {
86                 $i->$k = $v;
87             }
88             if ($i->find(true)) {
89                 $i->encache();
90             } else {
91                 $i = null;
92             }
93             return $i;
94         }
95     }
96
97     function insert()
98     {
99         $result = parent::insert();
100         return $result;
101     }
102
103     function update($orig=null)
104     {
105         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
106             $orig->decache(); # might be different keys
107         }
108         $result = parent::update($orig);
109         if ($result) {
110             $this->encache();
111         }
112         return $result;
113     }
114
115     function delete()
116     {
117         $this->decache(); # while we still have the values!
118         return parent::delete();
119     }
120
121     static function memcache() {
122         return common_memcache();
123     }
124
125     static function cacheKey($cls, $k, $v) {
126         if (is_object($cls) || is_object($j) || is_object($v)) {
127             $e = new Exception();
128             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
129                 str_replace("\n", " ", $e->getTraceAsString()));
130         }
131         return common_cache_key(strtolower($cls).':'.$k.':'.$v);
132     }
133
134     static function getcached($cls, $k, $v) {
135         $c = Memcached_DataObject::memcache();
136         if (!$c) {
137             return false;
138         } else {
139             return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
140         }
141     }
142
143     function keyTypes()
144     {
145         global $_DB_DATAOBJECT;
146         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
147             $this->databaseStructure();
148
149         }
150         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
151     }
152
153     function encache()
154     {
155         $c = $this->memcache();
156         if (!$c) {
157             return false;
158         } else {
159             $pkey = array();
160             $pval = array();
161             $types = $this->keyTypes();
162             ksort($types);
163             foreach ($types as $key => $type) {
164                 if ($type == 'K') {
165                     $pkey[] = $key;
166                     $pval[] = $this->$key;
167                 } else {
168                     $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this);
169                 }
170             }
171             # XXX: should work for both compound and scalar pkeys
172             $pvals = implode(',', $pval);
173             $pkeys = implode(',', $pkey);
174             $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this);
175         }
176     }
177
178     function decache()
179     {
180         $c = $this->memcache();
181         if (!$c) {
182             return false;
183         } else {
184             $pkey = array();
185             $pval = array();
186             $types = $this->keyTypes();
187             ksort($types);
188             foreach ($types as $key => $type) {
189                 if ($type == 'K') {
190                     $pkey[] = $key;
191                     $pval[] = $this->$key;
192                 } else {
193                     $c->delete($this->cacheKey($this->tableName(), $key, $this->$key));
194                 }
195             }
196             # should work for both compound and scalar pkeys
197             # XXX: comma works for now but may not be safe separator for future keys
198             $pvals = implode(',', $pval);
199             $pkeys = implode(',', $pkey);
200             $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals));
201         }
202     }
203
204     function multicache($cls, $kv)
205     {
206         ksort($kv);
207         $c = Memcached_DataObject::memcache();
208         if (!$c) {
209             return false;
210         } else {
211             $pkeys = implode(',', array_keys($kv));
212             $pvals = implode(',', array_values($kv));
213             return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
214         }
215     }
216
217     function getSearchEngine($table)
218     {
219         require_once INSTALLDIR.'/lib/search_engines.php';
220         static $search_engine;
221         if (!isset($search_engine)) {
222             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
223                 if ('mysql' === common_config('db', 'type')) {
224                     $type = common_config('search', 'type');
225                     if ($type == 'like') {
226                         $search_engine = new MySQLLikeSearch($this, $table);
227                     } else if ($type == 'fulltext') {
228                         $search_engine = new MySQLSearch($this, $table);
229                     } else {
230                         throw new ServerException('Unknown search type: ' . $type);
231                     }
232                 } else {
233                     $search_engine = new PGSearch($this, $table);
234                 }
235             }
236         }
237         return $search_engine;
238     }
239
240     static function cachedQuery($cls, $qry, $expiry=3600)
241     {
242         $c = Memcached_DataObject::memcache();
243         if (!$c) {
244             $inst = new $cls();
245             $inst->query($qry);
246             return $inst;
247         }
248         $key_part = common_keyize($cls).':'.md5($qry);
249         $ckey = common_cache_key($key_part);
250         $stored = $c->get($ckey);
251         if ($stored) {
252             return new ArrayWrapper($stored);
253         }
254
255         $inst = new $cls();
256         $inst->query($qry);
257         $cached = array();
258         while ($inst->fetch()) {
259             $cached[] = clone($inst);
260         }
261         $inst->free();
262         $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
263         return new ArrayWrapper($cached);
264     }
265
266     // We overload so that 'SET NAMES "utf8"' is called for
267     // each connection
268
269     function _connect()
270     {
271         global $_DB_DATAOBJECT;
272
273         $sum = $this->_getDbDsnMD5();
274
275         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
276             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
277             $exists = true;
278         } else {
279             $exists = false;
280        }
281
282         $result = parent::_connect();
283
284         if ($result && !$exists) {
285             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
286             if (common_config('db', 'type') == 'mysql' &&
287                 common_config('db', 'utf8')) {
288                 $conn = $DB->connection;
289                 if (!empty($conn)) {
290                     if ($DB instanceof DB_mysqli) {
291                         mysqli_set_charset($conn, 'utf8');
292                     } else if ($DB instanceof DB_mysql) {
293                         mysql_set_charset('utf8', $conn);
294                     }
295                 }
296             }
297         }
298
299         return $result;
300     }
301
302     // XXX: largely cadged from DB_DataObject
303
304     function _getDbDsnMD5()
305     {
306         if ($this->_database_dsn_md5) {
307             return $this->_database_dsn_md5;
308         }
309
310         $dsn = $this->_getDbDsn();
311
312         if (is_string($dsn)) {
313             $sum = md5($dsn);
314         } else {
315             /// support array based dsn's
316             $sum = md5(serialize($dsn));
317         }
318
319         return $sum;
320     }
321
322     function _getDbDsn()
323     {
324         global $_DB_DATAOBJECT;
325
326         if (empty($_DB_DATAOBJECT['CONFIG'])) {
327             DB_DataObject::_loadConfig();
328         }
329
330         $options = &$_DB_DATAOBJECT['CONFIG'];
331
332         // if the databse dsn dis defined in the object..
333
334         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
335
336         if (!$dsn) {
337
338             if (!$this->_database) {
339                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
340             }
341
342             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
343                 $dsn = $options["database_{$this->_database}"];
344             } else if (!empty($options['database'])) {
345                 $dsn = $options['database'];
346             }
347         }
348
349         if (!$dsn) {
350             throw new Exception("No database name / dsn found anywhere");
351         }
352
353         return $dsn;
354     }
355 }