]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
Merge branch 'master' 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      * Wrapper for DB_DataObject's static lookup using memcached
42      * as backing instead of an in-process cache array.
43      *
44      * @param string $cls classname of object type to load
45      * @param mixed $k key field name, or value for primary key
46      * @param mixed $v key field value, or leave out for primary key lookup
47      * @return mixed Memcached_DataObject subtype or false
48      */
49     function &staticGet($cls, $k, $v=null)
50     {
51         if (is_null($v)) {
52             $v = $k;
53             # XXX: HACK!
54             $i = new $cls;
55             $keys = $i->keys();
56             $k = $keys[0];
57             unset($i);
58         }
59         $i = Memcached_DataObject::getcached($cls, $k, $v);
60         if ($i) {
61             return $i;
62         } else {
63             $i = DB_DataObject::factory($cls);
64             if (empty($i)) {
65                 return null;
66             }
67             $result = $i->get($k, $v);
68             if ($result) {
69                 $i->encache();
70                 return $i;
71             } else {
72                 return null;
73             }
74         }
75     }
76
77     function &pkeyGet($cls, $kv)
78     {
79         $i = Memcached_DataObject::multicache($cls, $kv);
80         if ($i) {
81             return $i;
82         } else {
83             $i = new $cls();
84             foreach ($kv as $k => $v) {
85                 $i->$k = $v;
86             }
87             if ($i->find(true)) {
88                 $i->encache();
89             } else {
90                 $i = null;
91             }
92             return $i;
93         }
94     }
95
96     function insert()
97     {
98         $result = parent::insert();
99         return $result;
100     }
101
102     function update($orig=null)
103     {
104         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
105             $orig->decache(); # might be different keys
106         }
107         $result = parent::update($orig);
108         if ($result) {
109             $this->encache();
110         }
111         return $result;
112     }
113
114     function delete()
115     {
116         $this->decache(); # while we still have the values!
117         return parent::delete();
118     }
119
120     static function memcache() {
121         return common_memcache();
122     }
123
124     static function cacheKey($cls, $k, $v) {
125         if (is_object($cls) || is_object($j) || is_object($v)) {
126             $e = new Exception();
127             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
128                 str_replace("\n", " ", $e->getTraceAsString()));
129         }
130         return common_cache_key(strtolower($cls).':'.$k.':'.$v);
131     }
132
133     static function getcached($cls, $k, $v) {
134         $c = Memcached_DataObject::memcache();
135         if (!$c) {
136             return false;
137         } else {
138             return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
139         }
140     }
141
142     function keyTypes()
143     {
144         global $_DB_DATAOBJECT;
145         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
146             $this->databaseStructure();
147
148         }
149         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
150     }
151
152     function encache()
153     {
154         $c = $this->memcache();
155         if (!$c) {
156             return false;
157         } else {
158             $pkey = array();
159             $pval = array();
160             $types = $this->keyTypes();
161             ksort($types);
162             foreach ($types as $key => $type) {
163                 if ($type == 'K') {
164                     $pkey[] = $key;
165                     $pval[] = $this->$key;
166                 } else {
167                     $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this);
168                 }
169             }
170             # XXX: should work for both compound and scalar pkeys
171             $pvals = implode(',', $pval);
172             $pkeys = implode(',', $pkey);
173             $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this);
174         }
175     }
176
177     function decache()
178     {
179         $c = $this->memcache();
180         if (!$c) {
181             return false;
182         } else {
183             $pkey = array();
184             $pval = array();
185             $types = $this->keyTypes();
186             ksort($types);
187             foreach ($types as $key => $type) {
188                 if ($type == 'K') {
189                     $pkey[] = $key;
190                     $pval[] = $this->$key;
191                 } else {
192                     $c->delete($this->cacheKey($this->tableName(), $key, $this->$key));
193                 }
194             }
195             # should work for both compound and scalar pkeys
196             # XXX: comma works for now but may not be safe separator for future keys
197             $pvals = implode(',', $pval);
198             $pkeys = implode(',', $pkey);
199             $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals));
200         }
201     }
202
203     function multicache($cls, $kv)
204     {
205         ksort($kv);
206         $c = Memcached_DataObject::memcache();
207         if (!$c) {
208             return false;
209         } else {
210             $pkeys = implode(',', array_keys($kv));
211             $pvals = implode(',', array_values($kv));
212             return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
213         }
214     }
215
216     function getSearchEngine($table)
217     {
218         require_once INSTALLDIR.'/lib/search_engines.php';
219         static $search_engine;
220         if (!isset($search_engine)) {
221             if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
222                 if ('mysql' === common_config('db', 'type')) {
223                     $type = common_config('search', 'type');
224                     if ($type == 'like') {
225                         $search_engine = new MySQLLikeSearch($this, $table);
226                     } else if ($type == 'fulltext') {
227                         $search_engine = new MySQLSearch($this, $table);
228                     } else {
229                         throw new ServerException('Unknown search type: ' . $type);
230                     }
231                 } else {
232                     $search_engine = new PGSearch($this, $table);
233                 }
234             }
235         }
236         return $search_engine;
237     }
238
239     static function cachedQuery($cls, $qry, $expiry=3600)
240     {
241         $c = Memcached_DataObject::memcache();
242         if (!$c) {
243             $inst = new $cls();
244             $inst->query($qry);
245             return $inst;
246         }
247         $key_part = common_keyize($cls).':'.md5($qry);
248         $ckey = common_cache_key($key_part);
249         $stored = $c->get($ckey);
250         if ($stored) {
251             return new ArrayWrapper($stored);
252         }
253
254         $inst = new $cls();
255         $inst->query($qry);
256         $cached = array();
257         while ($inst->fetch()) {
258             $cached[] = clone($inst);
259         }
260         $inst->free();
261         $c->set($ckey, $cached, MEMCACHE_COMPRESSED, $expiry);
262         return new ArrayWrapper($cached);
263     }
264
265     function cleanup()
266     {
267         global $_DB_DATAOBJECT;
268
269         if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
270             unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
271         }
272         if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
273             unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
274         }
275     }
276
277     // We overload so that 'SET NAMES "utf8"' is called for
278     // each connection
279
280     function _connect()
281     {
282         global $_DB_DATAOBJECT;
283
284         $sum = $this->_getDbDsnMD5();
285
286         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
287             !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
288             $exists = true;
289         } else {
290             $exists = false;
291        }
292
293         $result = parent::_connect();
294
295         if ($result && !$exists) {
296             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
297             if (common_config('db', 'type') == 'mysql' &&
298                 common_config('db', 'utf8')) {
299                 $conn = $DB->connection;
300                 if (!empty($conn)) {
301                     if ($DB instanceof DB_mysqli) {
302                         mysqli_set_charset($conn, 'utf8');
303                     } else if ($DB instanceof DB_mysql) {
304                         mysql_set_charset('utf8', $conn);
305                     }
306                 }
307             }
308         }
309
310         return $result;
311     }
312
313     // XXX: largely cadged from DB_DataObject
314
315     function _getDbDsnMD5()
316     {
317         if ($this->_database_dsn_md5) {
318             return $this->_database_dsn_md5;
319         }
320
321         $dsn = $this->_getDbDsn();
322
323         if (is_string($dsn)) {
324             $sum = md5($dsn);
325         } else {
326             /// support array based dsn's
327             $sum = md5(serialize($dsn));
328         }
329
330         return $sum;
331     }
332
333     function _getDbDsn()
334     {
335         global $_DB_DATAOBJECT;
336
337         if (empty($_DB_DATAOBJECT['CONFIG'])) {
338             DB_DataObject::_loadConfig();
339         }
340
341         $options = &$_DB_DATAOBJECT['CONFIG'];
342
343         // if the databse dsn dis defined in the object..
344
345         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
346
347         if (!$dsn) {
348
349             if (!$this->_database) {
350                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
351             }
352
353             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
354                 $dsn = $options["database_{$this->_database}"];
355             } else if (!empty($options['database'])) {
356                 $dsn = $options['database'];
357             }
358         }
359
360         if (!$dsn) {
361             throw new Exception("No database name / dsn found anywhere");
362         }
363
364         return $dsn;
365     }
366 }