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