]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
33645a3e8b6eeaf75246d69e87f70db41ab209a7
[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) {
95             return $i;
96         } else {
97             $i = DB_DataObject::factory($cls);
98             if (empty($i)) {
99                 $i = false;
100                 return $i;
101             }
102             $result = $i->get($k, $v);
103             if ($result) {
104                 $i->encache();
105                 return $i;
106             } else {
107                 $i = false;
108                 return $i;
109             }
110         }
111     }
112
113     function &pkeyGet($cls, $kv)
114     {
115         $i = Memcached_DataObject::multicache($cls, $kv);
116         if ($i) {
117             return $i;
118         } else {
119             $i = new $cls();
120             foreach ($kv as $k => $v) {
121                 $i->$k = $v;
122             }
123             if ($i->find(true)) {
124                 $i->encache();
125             } else {
126                 $i = null;
127             }
128             return $i;
129         }
130     }
131
132     function insert()
133     {
134         $result = parent::insert();
135         return $result;
136     }
137
138     function update($orig=null)
139     {
140         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
141             $orig->decache(); # might be different keys
142         }
143         $result = parent::update($orig);
144         if ($result) {
145             $this->encache();
146         }
147         return $result;
148     }
149
150     function delete()
151     {
152         $this->decache(); # while we still have the values!
153         return parent::delete();
154     }
155
156     static function memcache() {
157         return common_memcache();
158     }
159
160     static function cacheKey($cls, $k, $v) {
161         if (is_object($cls) || is_object($k) || is_object($v)) {
162             $e = new Exception();
163             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
164                 str_replace("\n", " ", $e->getTraceAsString()));
165         }
166         return common_cache_key(strtolower($cls).':'.$k.':'.$v);
167     }
168
169     static function getcached($cls, $k, $v) {
170         $c = Memcached_DataObject::memcache();
171         if (!$c) {
172             return false;
173         } else {
174             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
175             if (0 == strcasecmp($cls, 'User')) {
176                 // Special case for User
177                 if (is_object($obj) && is_object($obj->id)) {
178                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
179                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
180                     return false;
181                 }
182             }
183             return $obj;
184         }
185     }
186
187     function keyTypes()
188     {
189         global $_DB_DATAOBJECT;
190         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
191             $this->databaseStructure();
192
193         }
194         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
195     }
196
197     function encache()
198     {
199         $c = $this->memcache();
200         if (!$c) {
201             return false;
202         } else if ($this->tableName() == 'user' && is_object($this->id)) {
203             // Special case for User bug
204             $e = new Exception();
205             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
206                        str_replace("\n", " ", $e->getTraceAsString()));
207             return false;
208         } else {
209             $pkey = array();
210             $pval = array();
211             $types = $this->keyTypes();
212             ksort($types);
213             foreach ($types as $key => $type) {
214                 if ($type == 'K') {
215                     $pkey[] = $key;
216                     $pval[] = $this->$key;
217                 } else {
218                     $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this);
219                 }
220             }
221             # XXX: should work for both compound and scalar pkeys
222             $pvals = implode(',', $pval);
223             $pkeys = implode(',', $pkey);
224             $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this);
225         }
226     }
227
228     function decache()
229     {
230         $c = $this->memcache();
231         if (!$c) {
232             return false;
233         } else {
234             $pkey = array();
235             $pval = array();
236             $types = $this->keyTypes();
237             ksort($types);
238             foreach ($types as $key => $type) {
239                 if ($type == 'K') {
240                     $pkey[] = $key;
241                     $pval[] = $this->$key;
242                 } else {
243                     $c->delete($this->cacheKey($this->tableName(), $key, $this->$key));
244                 }
245             }
246             # should work for both compound and scalar pkeys
247             # XXX: comma works for now but may not be safe separator for future keys
248             $pvals = implode(',', $pval);
249             $pkeys = implode(',', $pkey);
250             $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals));
251         }
252     }
253
254     function multicache($cls, $kv)
255     {
256         ksort($kv);
257         $c = Memcached_DataObject::memcache();
258         if (!$c) {
259             return false;
260         } else {
261             $pkeys = implode(',', array_keys($kv));
262             $pvals = implode(',', array_values($kv));
263             return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
264         }
265     }
266
267     function getSearchEngine($table)
268     {
269         require_once INSTALLDIR.'/lib/search_engines.php';
270         static $search_engine;
271         if (!isset($search_engine)) {
272             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
273                 if ('mysql' === common_config('db', 'type')) {
274                     $type = common_config('search', 'type');
275                     if ($type == 'like') {
276                         $search_engine = new MySQLLikeSearch($this, $table);
277                     } else if ($type == 'fulltext') {
278                         $search_engine = new MySQLSearch($this, $table);
279                     } else {
280                         throw new ServerException('Unknown search type: ' . $type);
281                     }
282                 } else {
283                     $search_engine = new PGSearch($this, $table);
284                 }
285             }
286         }
287         return $search_engine;
288     }
289
290     static function cachedQuery($cls, $qry, $expiry=3600)
291     {
292         $c = Memcached_DataObject::memcache();
293         if (!$c) {
294             $inst = new $cls();
295             $inst->query($qry);
296             return $inst;
297         }
298         $key_part = common_keyize($cls).':'.md5($qry);
299         $ckey = common_cache_key($key_part);
300         $stored = $c->get($ckey);
301         if ($stored) {
302             return new ArrayWrapper($stored);
303         }
304
305         $inst = new $cls();
306         $inst->query($qry);
307         $cached = array();
308         while ($inst->fetch()) {
309             $cached[] = clone($inst);
310         }
311         $inst->free();
312         $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
313         return new ArrayWrapper($cached);
314     }
315
316     /**
317      * sends query to database - this is the private one that must work 
318      *   - internal functions use this rather than $this->query()
319      *
320      * Overridden to do logging.
321      *
322      * @param  string  $string
323      * @access private
324      * @return mixed none or PEAR_Error
325      */
326     function _query($string)
327     {
328         $start = microtime(true);
329         $result = parent::_query($string);
330         $delta = microtime(true) - $start;
331
332         $limit = common_config('db', 'log_slow_queries');
333         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
334             $clean = $this->sanitizeQuery($string);
335             common_log(LOG_DEBUG, sprintf("DB query (%0.3fs): %s", $delta, $clean));
336         }
337         return $result;
338     }
339
340     // Sanitize a query for logging
341     // @fixme don't trim spaces in string literals
342     function sanitizeQuery($string)
343     {
344         $string = preg_replace('/\s+/', ' ', $string);
345         $string = trim($string);
346         return $string;
347     }
348
349     // We overload so that 'SET NAMES "utf8"' is called for
350     // each connection
351
352     function _connect()
353     {
354         global $_DB_DATAOBJECT;
355
356         $sum = $this->_getDbDsnMD5();
357
358         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
359             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
360             $exists = true;
361         } else {
362             $exists = false;
363        }
364
365         // @fixme horrible evil hack!
366         //
367         // In multisite configuration we don't want to keep around a separate
368         // connection for every database; we could end up with thousands of
369         // connections open per thread. In an ideal world we might keep
370         // a connection per server and select different databases, but that'd
371         // be reliant on having the same db username/pass as well.
372         //
373         // MySQL connections are cheap enough we're going to try just
374         // closing out the old connection and reopening when we encounter
375         // a new DSN.
376         //
377         // WARNING WARNING if we end up actually using multiple DBs at a time
378         // we'll need some fancier logic here.
379         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS'])) {
380             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
381                 if (!empty($conn)) {
382                     $conn->disconnect();
383                 }
384                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
385             }
386         }
387
388         $result = parent::_connect();
389
390         if ($result && !$exists) {
391             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
392             if (common_config('db', 'type') == 'mysql' &&
393                 common_config('db', 'utf8')) {
394                 $conn = $DB->connection;
395                 if (!empty($conn)) {
396                     if ($DB instanceof DB_mysqli) {
397                         mysqli_set_charset($conn, 'utf8');
398                     } else if ($DB instanceof DB_mysql) {
399                         mysql_set_charset('utf8', $conn);
400                     }
401                 }
402             }
403         }
404
405         return $result;
406     }
407
408     // XXX: largely cadged from DB_DataObject
409
410     function _getDbDsnMD5()
411     {
412         if ($this->_database_dsn_md5) {
413             return $this->_database_dsn_md5;
414         }
415
416         $dsn = $this->_getDbDsn();
417
418         if (is_string($dsn)) {
419             $sum = md5($dsn);
420         } else {
421             /// support array based dsn's
422             $sum = md5(serialize($dsn));
423         }
424
425         return $sum;
426     }
427
428     function _getDbDsn()
429     {
430         global $_DB_DATAOBJECT;
431
432         if (empty($_DB_DATAOBJECT['CONFIG'])) {
433             DB_DataObject::_loadConfig();
434         }
435
436         $options = &$_DB_DATAOBJECT['CONFIG'];
437
438         // if the databse dsn dis defined in the object..
439
440         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
441
442         if (!$dsn) {
443
444             if (!$this->_database) {
445                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
446             }
447
448             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
449                 $dsn = $options["database_{$this->_database}"];
450             } else if (!empty($options['database'])) {
451                 $dsn = $options['database'];
452             }
453         }
454
455         if (!$dsn) {
456             throw new Exception("No database name / dsn found anywhere");
457         }
458
459         return $dsn;
460     }
461 }