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