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