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