]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
d830884b675de2a7669bdf2f0cbe4bc42af9a3f2
[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 class Memcached_DataObject extends DB_DataObject
23 {
24     /**
25      * Destructor to free global memory resources associated with
26      * this data object when it's unset or goes out of scope.
27      * DB_DataObject doesn't do this yet by itself.
28      */
29
30     function __destruct()
31     {
32         $this->free();
33         if (method_exists('DB_DataObject', '__destruct')) {
34             parent::__destruct();
35         }
36     }
37
38     /**
39      * Magic function called at serialize() time.
40      *
41      * We use this to drop a couple process-specific references
42      * from DB_DataObject which can cause trouble in future
43      * processes.
44      *
45      * @return array of variable names to include in serialization.
46      */
47     function __sleep()
48     {
49         $vars = array_keys(get_object_vars($this));
50         $skip = array('_DB_resultid', '_link_loaded');
51         return array_diff($vars, $skip);
52     }
53
54     /**
55      * Magic function called at unserialize() time.
56      *
57      * Clean out some process-specific variables which might
58      * be floating around from a previous process's cached
59      * objects.
60      *
61      * Old cached objects may still have them.
62      */
63     function __wakeup()
64     {
65         // Refers to global state info from a previous process.
66         // Clear this out so we don't accidentally break global
67         // state in *this* process.
68         $this->_DB_resultid = null;
69         
70         // We don't have any local DBO refs, so clear these out.
71         $this->_link_loaded = false;
72     }
73
74     /**
75      * Wrapper for DB_DataObject's static lookup using memcached
76      * as backing instead of an in-process cache array.
77      *
78      * @param string $cls classname of object type to load
79      * @param mixed $k key field name, or value for primary key
80      * @param mixed $v key field value, or leave out for primary key lookup
81      * @return mixed Memcached_DataObject subtype or false
82      */
83     function &staticGet($cls, $k, $v=null)
84     {
85         if (is_null($v)) {
86             $v = $k;
87             # XXX: HACK!
88             $i = new $cls;
89             $keys = $i->keys();
90             $k = $keys[0];
91             unset($i);
92         }
93         $i = Memcached_DataObject::getcached($cls, $k, $v);
94         if ($i !== false) { // false == cache miss
95             return $i;
96         } else {
97             $i = DB_DataObject::factory($cls);
98             if (empty($i)) {
99                 return false;
100             }
101             $result = $i->get($k, $v);
102             if ($result) {
103                 $i->encache();
104                 return $i;
105             } else {
106                 // save the fact that no such row exists
107                 $c = self::memcache();
108                 if (!empty($c)) {
109                     $ck = self::cachekey($cls, $k, $v);
110                     $c->set($ck, null);
111                 }
112                 return false;
113             }
114         }
115     }
116
117     function &pkeyGet($cls, $kv)
118     {
119         $i = Memcached_DataObject::multicache($cls, $kv);
120         if ($i !== false) { // false == cache miss
121             return $i;
122         } else {
123             $i = DB_DataObject::factory($cls);
124             if (empty($i)) {
125                 return false;
126             }
127             foreach ($kv as $k => $v) {
128                 $i->$k = $v;
129             }
130             if ($i->find(true)) {
131                 $i->encache();
132             } else {
133                 $i = null;
134                 $c = self::memcache();
135                 if (!empty($c)) {
136                     $ck = self::multicacheKey($cls, $kv);
137                     $c->set($ck, null);
138                 }
139             }
140             return $i;
141         }
142     }
143
144     function insert()
145     {
146         $result = parent::insert();
147         return $result;
148     }
149
150     function update($orig=null)
151     {
152         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
153             $orig->decache(); # might be different keys
154         }
155         $result = parent::update($orig);
156         if ($result) {
157             $this->encache();
158         }
159         return $result;
160     }
161
162     function delete()
163     {
164         $this->decache(); # while we still have the values!
165         return parent::delete();
166     }
167
168     static function memcache() {
169         return common_memcache();
170     }
171
172     static function cacheKey($cls, $k, $v) {
173         if (is_object($cls) || is_object($k) || is_object($v)) {
174             $e = new Exception();
175             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
176                 str_replace("\n", " ", $e->getTraceAsString()));
177         }
178         return common_cache_key(strtolower($cls).':'.$k.':'.$v);
179     }
180
181     static function getcached($cls, $k, $v) {
182         $c = Memcached_DataObject::memcache();
183         if (!$c) {
184             return false;
185         } else {
186             return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
187         }
188     }
189
190     function keyTypes()
191     {
192         global $_DB_DATAOBJECT;
193         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
194             $this->databaseStructure();
195
196         }
197         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
198     }
199
200     function encache()
201     {
202         $c = $this->memcache();
203
204         if (!$c) {
205             return false;
206         }
207
208         $keys = $this->_allCacheKeys();
209
210         foreach ($keys as $key) {
211             $c->set($key, $this);
212         }
213     }
214
215     function decache()
216     {
217         $c = $this->memcache();
218
219         if (!$c) {
220             return false;
221         }
222
223         $keys = $this->_allCacheKeys();
224
225         foreach ($keys as $key) {
226             $c->delete($key, $this);
227         }
228     }
229
230     function _allCacheKeys()
231     {
232         $ckeys = array();
233
234         $types = $this->keyTypes();
235         ksort($types);
236
237         $pkey = array();
238         $pval = array();
239
240         foreach ($types as $key => $type) {
241
242             assert(!empty($key));
243
244             if ($type == 'U') {
245                 if (empty($this->$key)) {
246                     continue;
247                 }
248                 $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
249             } else if ($type == 'K' || $type == 'N') {
250                 $pkey[] = $key;
251                 $pval[] = $this->$key;
252             } else {
253                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
254             }
255         }
256
257         assert(count($pkey) > 0);
258
259         // XXX: should work for both compound and scalar pkeys
260         $pvals = implode(',', $pval);
261         $pkeys = implode(',', $pkey);
262
263         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
264
265         return $ckeys;
266     }
267
268     function multicache($cls, $kv)
269     {
270         ksort($kv);
271         $c = self::memcache();
272         if (!$c) {
273             return false;
274         } else {
275             return $c->get(self::multicacheKey($cls, $kv));
276         }
277     }
278
279     static function multicacheKey($cls, $kv)
280     {
281         ksort($kv);
282         $pkeys = implode(',', array_keys($kv));
283         $pvals = implode(',', array_values($kv));
284         return self::cacheKey($cls, $pkeys, $pvals);
285     }
286
287     function getSearchEngine($table)
288     {
289         require_once INSTALLDIR.'/lib/search_engines.php';
290         static $search_engine;
291         if (!isset($search_engine)) {
292             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
293                 if ('mysql' === common_config('db', 'type')) {
294                     $type = common_config('search', 'type');
295                     if ($type == 'like') {
296                         $search_engine = new MySQLLikeSearch($this, $table);
297                     } else if ($type == 'fulltext') {
298                         $search_engine = new MySQLSearch($this, $table);
299                     } else {
300                         throw new ServerException('Unknown search type: ' . $type);
301                     }
302                 } else {
303                     $search_engine = new PGSearch($this, $table);
304                 }
305             }
306         }
307         return $search_engine;
308     }
309
310     static function cachedQuery($cls, $qry, $expiry=3600)
311     {
312         $c = Memcached_DataObject::memcache();
313         if (!$c) {
314             $inst = new $cls();
315             $inst->query($qry);
316             return $inst;
317         }
318         $key_part = common_keyize($cls).':'.md5($qry);
319         $ckey = common_cache_key($key_part);
320         $stored = $c->get($ckey);
321
322         if ($stored !== false) {
323             return new ArrayWrapper($stored);
324         }
325
326         $inst = new $cls();
327         $inst->query($qry);
328         $cached = array();
329         while ($inst->fetch()) {
330             $cached[] = clone($inst);
331         }
332         $inst->free();
333         $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
334         return new ArrayWrapper($cached);
335     }
336
337     // We overload so that 'SET NAMES "utf8"' is called for
338     // each connection
339
340     function _connect()
341     {
342         global $_DB_DATAOBJECT;
343
344         $sum = $this->_getDbDsnMD5();
345
346         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
347             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
348             $exists = true;
349         } else {
350             $exists = false;
351        }
352
353         $result = parent::_connect();
354
355         if ($result && !$exists) {
356             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
357             if (common_config('db', 'type') == 'mysql' &&
358                 common_config('db', 'utf8')) {
359                 $conn = $DB->connection;
360                 if (!empty($conn)) {
361                     if ($DB instanceof DB_mysqli) {
362                         mysqli_set_charset($conn, 'utf8');
363                     } else if ($DB instanceof DB_mysql) {
364                         mysql_set_charset('utf8', $conn);
365                     }
366                 }
367             }
368         }
369
370         return $result;
371     }
372
373     // XXX: largely cadged from DB_DataObject
374
375     function _getDbDsnMD5()
376     {
377         if ($this->_database_dsn_md5) {
378             return $this->_database_dsn_md5;
379         }
380
381         $dsn = $this->_getDbDsn();
382
383         if (is_string($dsn)) {
384             $sum = md5($dsn);
385         } else {
386             /// support array based dsn's
387             $sum = md5(serialize($dsn));
388         }
389
390         return $sum;
391     }
392
393     function _getDbDsn()
394     {
395         global $_DB_DATAOBJECT;
396
397         if (empty($_DB_DATAOBJECT['CONFIG'])) {
398             DB_DataObject::_loadConfig();
399         }
400
401         $options = &$_DB_DATAOBJECT['CONFIG'];
402
403         // if the databse dsn dis defined in the object..
404
405         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
406
407         if (!$dsn) {
408
409             if (!$this->_database) {
410                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
411             }
412
413             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
414                 $dsn = $options["database_{$this->_database}"];
415             } else if (!empty($options['database'])) {
416                 $dsn = $options['database'];
417             }
418         }
419
420         if (!$dsn) {
421             throw new Exception("No database name / dsn found anywhere");
422         }
423
424         return $dsn;
425     }
426 }