]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
ca360d4111fa092defaf4cc273dfeee47f22f23a
[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                 return false;
102             }
103             $result = $i->get($k, $v);
104             if ($result) {
105                 $i->encache();
106                 return $i;
107             } else {
108                 return false;
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             return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
175         }
176     }
177
178     function keyTypes()
179     {
180         global $_DB_DATAOBJECT;
181         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
182             $this->databaseStructure();
183
184         }
185         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
186     }
187
188     function encache()
189     {
190         $c = $this->memcache();
191         if (!$c) {
192             return false;
193         } else {
194             $pkey = array();
195             $pval = array();
196             $types = $this->keyTypes();
197             ksort($types);
198             foreach ($types as $key => $type) {
199                 if ($type == 'K') {
200                     $pkey[] = $key;
201                     $pval[] = $this->$key;
202                 } else {
203                     $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this);
204                 }
205             }
206             # XXX: should work for both compound and scalar pkeys
207             $pvals = implode(',', $pval);
208             $pkeys = implode(',', $pkey);
209             $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this);
210         }
211     }
212
213     function decache()
214     {
215         $c = $this->memcache();
216         if (!$c) {
217             return false;
218         } else {
219             $pkey = array();
220             $pval = array();
221             $types = $this->keyTypes();
222             ksort($types);
223             foreach ($types as $key => $type) {
224                 if ($type == 'K') {
225                     $pkey[] = $key;
226                     $pval[] = $this->$key;
227                 } else {
228                     $c->delete($this->cacheKey($this->tableName(), $key, $this->$key));
229                 }
230             }
231             # should work for both compound and scalar pkeys
232             # XXX: comma works for now but may not be safe separator for future keys
233             $pvals = implode(',', $pval);
234             $pkeys = implode(',', $pkey);
235             $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals));
236         }
237     }
238
239     function multicache($cls, $kv)
240     {
241         ksort($kv);
242         $c = Memcached_DataObject::memcache();
243         if (!$c) {
244             return false;
245         } else {
246             $pkeys = implode(',', array_keys($kv));
247             $pvals = implode(',', array_values($kv));
248             return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
249         }
250     }
251
252     function getSearchEngine($table)
253     {
254         require_once INSTALLDIR.'/lib/search_engines.php';
255         static $search_engine;
256         if (!isset($search_engine)) {
257             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
258                 if ('mysql' === common_config('db', 'type')) {
259                     $type = common_config('search', 'type');
260                     if ($type == 'like') {
261                         $search_engine = new MySQLLikeSearch($this, $table);
262                     } else if ($type == 'fulltext') {
263                         $search_engine = new MySQLSearch($this, $table);
264                     } else {
265                         throw new ServerException('Unknown search type: ' . $type);
266                     }
267                 } else {
268                     $search_engine = new PGSearch($this, $table);
269                 }
270             }
271         }
272         return $search_engine;
273     }
274
275     static function cachedQuery($cls, $qry, $expiry=3600)
276     {
277         $c = Memcached_DataObject::memcache();
278         if (!$c) {
279             $inst = new $cls();
280             $inst->query($qry);
281             return $inst;
282         }
283         $key_part = common_keyize($cls).':'.md5($qry);
284         $ckey = common_cache_key($key_part);
285         $stored = $c->get($ckey);
286         if ($stored) {
287             return new ArrayWrapper($stored);
288         }
289
290         $inst = new $cls();
291         $inst->query($qry);
292         $cached = array();
293         while ($inst->fetch()) {
294             $cached[] = clone($inst);
295         }
296         $inst->free();
297         $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
298         return new ArrayWrapper($cached);
299     }
300
301     // We overload so that 'SET NAMES "utf8"' is called for
302     // each connection
303
304     function _connect()
305     {
306         global $_DB_DATAOBJECT;
307
308         $sum = $this->_getDbDsnMD5();
309
310         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
311             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
312             $exists = true;
313         } else {
314             $exists = false;
315        }
316
317         $result = parent::_connect();
318
319         if ($result && !$exists) {
320             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
321             if (common_config('db', 'type') == 'mysql' &&
322                 common_config('db', 'utf8')) {
323                 $conn = $DB->connection;
324                 if (!empty($conn)) {
325                     if ($DB instanceof DB_mysqli) {
326                         mysqli_set_charset($conn, 'utf8');
327                     } else if ($DB instanceof DB_mysql) {
328                         mysql_set_charset('utf8', $conn);
329                     }
330                 }
331             }
332         }
333
334         return $result;
335     }
336
337     // XXX: largely cadged from DB_DataObject
338
339     function _getDbDsnMD5()
340     {
341         if ($this->_database_dsn_md5) {
342             return $this->_database_dsn_md5;
343         }
344
345         $dsn = $this->_getDbDsn();
346
347         if (is_string($dsn)) {
348             $sum = md5($dsn);
349         } else {
350             /// support array based dsn's
351             $sum = md5(serialize($dsn));
352         }
353
354         return $sum;
355     }
356
357     function _getDbDsn()
358     {
359         global $_DB_DATAOBJECT;
360
361         if (empty($_DB_DATAOBJECT['CONFIG'])) {
362             DB_DataObject::_loadConfig();
363         }
364
365         $options = &$_DB_DATAOBJECT['CONFIG'];
366
367         // if the databse dsn dis defined in the object..
368
369         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
370
371         if (!$dsn) {
372
373             if (!$this->_database) {
374                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
375             }
376
377             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
378                 $dsn = $options["database_{$this->_database}"];
379             } else if (!empty($options['database'])) {
380                 $dsn = $options['database'];
381             }
382         }
383
384         if (!$dsn) {
385             throw new Exception("No database name / dsn found anywhere");
386         }
387
388         return $dsn;
389     }
390 }