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