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