]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Memcached_DataObject.php
Properly unlink all old avatars when deleting/uploading a new
[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 class Memcached_DataObject extends Safe_DataObject
23 {
24     /**
25      * Wrapper for DB_DataObject's static lookup using memcached
26      * as backing instead of an in-process cache array.
27      *
28      * @param string $cls classname of object type to load
29      * @param mixed $k key field name, or value for primary key
30      * @param mixed $v key field value, or leave out for primary key lookup
31      * @return mixed Memcached_DataObject subtype or false
32      */
33     static function getClassKV($cls, $k, $v=null)
34     {
35         if (!is_a($cls, __CLASS__, true)) {
36             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
37         }
38         if (is_null($v)) {
39             $v = $k;
40             $keys = self::pkeyCols($cls);
41             if (count($keys) > 1) {
42                 // FIXME: maybe call pkeyGetClass() ourselves?
43                 throw new Exception('Use pkeyGetClass() for compound primary keys');
44             }
45             $k = $keys[0];
46         }
47         $i = self::getcached($cls, $k, $v);
48         if ($i === false) { // false == cache miss
49             $i = new $cls;
50             $result = $i->get($k, $v);
51             if ($result) {
52                 // Hit!
53                 $i->encache();
54             } else {
55                 // save the fact that no such row exists
56                 $c = self::memcache();
57                 if (!empty($c)) {
58                     $ck = self::cachekey($cls, $k, $v);
59                     $c->set($ck, null);
60                 }
61                 $i = false;
62             }
63         }
64         return $i;
65     }
66
67     /**
68      * Get multiple items from the database by key
69      *
70      * @param string  $cls       Class to fetch
71      * @param string  $keyCol    name of column for key
72      * @param array   $keyVals   key values to fetch
73      * @param boolean $skipNulls return only non-null results?
74      *
75      * @return array Array of objects, in order
76      */
77     static function multiGetClass($cls, $keyCol, array $keyVals, $skipNulls=true)
78     {
79         $result = self::pivotGetClass($cls, $keyCol, $keyVals);
80
81         $values = array_values($result);
82
83         if ($skipNulls) {
84             $tmp = array();
85             foreach ($values as $value) {
86                 if (!empty($value)) {
87                     $tmp[] = $value;
88                 }
89             }
90             $values = $tmp;
91         }
92
93         return new ArrayWrapper($values);
94     }
95
96     /**
97      * Get multiple items from the database by key
98      *
99      * @param string  $cls       Class to fetch
100      * @param string  $keyCol    name of column for key
101      * @param array   $keyVals   key values to fetch
102      * @param boolean $otherCols Other columns to hold fixed
103      *
104      * @return array Array mapping $keyVals to objects, or null if not found
105      */
106     static function pivotGetClass($cls, $keyCol, array $keyVals, array $otherCols = array())
107     {
108         if (!is_a($cls, __CLASS__, true)) {
109             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
110         }
111         if (is_array($keyCol)) {
112             foreach ($keyVals as $keyVal) {
113                 $result[implode(',', $keyVal)] = null;
114             }
115         } else {
116             $result = array_fill_keys($keyVals, null);
117         }
118
119         $toFetch = array();
120
121         foreach ($keyVals as $keyVal) {
122
123             if (is_array($keyCol)) {
124                 $kv = array_combine($keyCol, $keyVal);
125             } else {
126                 $kv = array($keyCol => $keyVal);
127             }
128
129             $kv = array_merge($otherCols, $kv);
130
131             $i = self::multicache($cls, $kv);
132
133             if ($i !== false) {
134                 if (is_array($keyCol)) {
135                     $result[implode(',', $keyVal)] = $i;
136                 } else {
137                     $result[$keyVal] = $i;
138                 }
139             } else if (!empty($keyVal)) {
140                 $toFetch[] = $keyVal;
141             }
142         }
143
144         if (count($toFetch) > 0) {
145             $i = new $cls;
146             foreach ($otherCols as $otherKeyCol => $otherKeyVal) {
147                 $i->$otherKeyCol = $otherKeyVal;
148             }
149             if (is_array($keyCol)) {
150                 $i->whereAdd(self::_inMultiKey($i, $keyCol, $toFetch));
151             } else {
152                 $i->whereAddIn($keyCol, $toFetch, $i->columnType($keyCol));
153             }
154             if ($i->find()) {
155                 while ($i->fetch()) {
156                     $copy = clone($i);
157                     $copy->encache();
158                     if (is_array($keyCol)) {
159                         $vals = array();
160                         foreach ($keyCol as $k) {
161                             $vals[] = $i->$k;
162                         }
163                         $result[implode(',', $vals)] = $copy;
164                     } else {
165                         $result[$i->$keyCol] = $copy;
166                     }
167                 }
168             }
169
170             // Save state of DB misses
171
172             foreach ($toFetch as $keyVal) {
173                 $r = null;
174                 if (is_array($keyCol)) {
175                     $r = $result[implode(',', $keyVal)];
176                 } else {
177                     $r = $result[$keyVal];
178                 }
179                 if (empty($r)) {
180                     if (is_array($keyCol)) {
181                         $kv = array_combine($keyCol, $keyVal);
182                     } else {
183                         $kv = array($keyCol => $keyVal);
184                     }
185                     $kv = array_merge($otherCols, $kv);
186                     // save the fact that no such row exists
187                     $c = self::memcache();
188                     if (!empty($c)) {
189                         $ck = self::multicacheKey($cls, $kv);
190                         $c->set($ck, null);
191                     }
192                 }
193             }
194         }
195
196         return $result;
197     }
198
199     static function _inMultiKey($i, $cols, $values)
200     {
201         $types = array();
202
203         foreach ($cols as $col) {
204             $types[$col] = $i->columnType($col);
205         }
206
207         $first = true;
208
209         $query = '';
210
211         foreach ($values as $value) {
212             if ($first) {
213                 $query .= '( ';
214                 $first = false;
215             } else {
216                 $query .= ' OR ';
217             }
218             $query .= '( ';
219             $i = 0;
220             $firstc = true;
221             foreach ($cols as $col) {
222                 if (!$firstc) {
223                     $query .= ' AND ';
224                 } else {
225                     $firstc = false;
226                 }
227                 switch ($types[$col]) {
228                 case 'string':
229                 case 'datetime':
230                     $query .= sprintf("%s = %s", $col, $i->_quote($value[$i]));
231                     break;
232                 default:
233                     $query .= sprintf("%s = %s", $col, $value[$i]);
234                     break;
235                 }
236             }
237             $query .= ') ';
238         }
239
240         if (!$first) {
241             $query .= ' )';
242         }
243
244         return $query;
245     }
246
247     static function pkeyCols($cls)
248     {
249         if (!is_a($cls, __CLASS__, true)) {
250             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
251         }
252         $i = new $cls;
253         $types = $i->keyTypes();
254         ksort($types);
255
256         $pkey = array();
257
258         foreach ($types as $key => $type) {
259             if ($type == 'K' || $type == 'N') {
260                 $pkey[] = $key;
261             }
262         }
263
264         return $pkey;
265     }
266
267     static function listFindClass($cls, $keyCol, array $keyVals)
268     {
269         if (!is_a($cls, __CLASS__, true)) {
270             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
271         }
272
273         $i = new $cls;
274         $i->whereAddIn($keyCol, $keyVals, $i->columnType($keyCol));
275         if (!$i->find()) {
276             throw new NoResultException($i);
277         }
278
279         return $i;
280     }
281
282     static function listGetClass($cls, $keyCol, array $keyVals)
283     {
284         if (!is_a($cls, __CLASS__, true)) {
285             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
286         }
287         $pkeyMap = array_fill_keys($keyVals, array());
288         $result = array_fill_keys($keyVals, array());
289
290         $pkeyCols = self::pkeyCols($cls);
291
292         $toFetch = array();
293         $allPkeys = array();
294
295         // We only cache keys -- not objects!
296
297         foreach ($keyVals as $keyVal) {
298             $l = self::cacheGet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal));
299             if ($l !== false) {
300                 $pkeyMap[$keyVal] = $l;
301                 foreach ($l as $pkey) {
302                     $allPkeys[] = $pkey;
303                 }
304             } else {
305                 $toFetch[] = $keyVal;
306             }
307         }
308
309         if (count($allPkeys) > 0) {
310             $keyResults = self::pivotGetClass($cls, $pkeyCols, $allPkeys);
311
312             foreach ($pkeyMap as $keyVal => $pkeyList) {
313                 foreach ($pkeyList as $pkeyVal) {
314                     $i = $keyResults[implode(',',$pkeyVal)];
315                     if (!empty($i)) {
316                         $result[$keyVal][] = $i;
317                     }
318                 }
319             }
320         }
321
322         if (count($toFetch) > 0) {
323             try {
324                 $i = self::listFindClass($cls, $keyCol, $toFetch);
325
326                 while ($i->fetch()) {
327                     $copy = clone($i);
328                     $copy->encache();
329                     $result[$i->$keyCol][] = $copy;
330                     $pkeyVal = array();
331                     foreach ($pkeyCols as $pkeyCol) {
332                         $pkeyVal[] = $i->$pkeyCol;
333                     }
334                     $pkeyMap[$i->$keyCol][] = $pkeyVal;
335                 }
336             } catch (NoResultException $e) {
337                 // no results found for our keyVals, so we leave them as empty arrays
338             }
339             foreach ($toFetch as $keyVal) {
340                 self::cacheSet(sprintf("%s:list-ids:%s:%s", strtolower($cls), $keyCol, $keyVal),
341                                $pkeyMap[$keyVal]);
342             }
343         }
344
345         return $result;
346     }
347
348     function columnType($columnName)
349     {
350         $keys = $this->table();
351         if (!array_key_exists($columnName, $keys)) {
352             throw new Exception('Unknown key column ' . $columnName . ' in ' . join(',', array_keys($keys)));
353         }
354
355         $def = $keys[$columnName];
356
357         if ($def & DB_DATAOBJECT_INT) {
358             return 'integer';
359         } else {
360             return 'string';
361         }
362     }
363
364     /**
365      * @todo FIXME: Should this return false on lookup fail to match getKV?
366      */
367     static function pkeyGetClass($cls, array $kv)
368     {
369         if (!is_a($cls, __CLASS__, true)) {
370             throw new Exception('Trying to fetch ' . __CLASS__ . ' into a non-related class');
371         }
372         $i = Memcached_DataObject::multicache($cls, $kv);
373         if ($i !== false) { // false == cache miss
374             return $i;
375         } else {
376             $i = new $cls;
377             foreach ($kv as $k => $v) {
378                 if (is_null($v)) {
379                     // XXX: possible SQL injection...? Don't
380                     // pass keys from the browser, eh.
381                     $i->whereAdd("$k is null");
382                 } else {
383                     $i->$k = $v;
384                 }
385             }
386             if ($i->find(true)) {
387                 $i->encache();
388             } else {
389                 $i = null;
390                 $c = self::memcache();
391                 if (!empty($c)) {
392                     $ck = self::multicacheKey($cls, $kv);
393                     $c->set($ck, null);
394                 }
395             }
396             return $i;
397         }
398     }
399
400     function insert()
401     {
402         $result = parent::insert();
403         if ($result) {
404             $this->fixupTimestamps();
405             $this->encache(); // in case of cached negative lookups
406         }
407         return $result;
408     }
409
410     function update($orig=null)
411     {
412         if (is_object($orig) && $orig instanceof Memcached_DataObject) {
413             $orig->decache(); # might be different keys
414         }
415         $result = parent::update($orig);
416         if ($result) {
417             $this->fixupTimestamps();
418             $this->encache();
419         }
420         return $result;
421     }
422
423     function delete()
424     {
425         $this->decache(); # while we still have the values!
426         return parent::delete();
427     }
428
429     static function memcache() {
430         return Cache::instance();
431     }
432
433     static function cacheKey($cls, $k, $v) {
434         if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
435             $e = new Exception();
436             common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
437                 str_replace("\n", " ", $e->getTraceAsString()));
438         }
439         $vstr = self::valueString($v);
440         return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
441     }
442
443     static function getcached($cls, $k, $v) {
444         $c = Memcached_DataObject::memcache();
445         if (!$c) {
446             return false;
447         } else {
448             $obj = $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
449             if (0 == strcasecmp($cls, 'User')) {
450                 // Special case for User
451                 if (is_object($obj) && is_object($obj->id)) {
452                     common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
453                     $c->delete(Memcached_DataObject::cacheKey($cls, $k, $v));
454                     return false;
455                 }
456             }
457             return $obj;
458         }
459     }
460
461     function keyTypes()
462     {
463         // ini-based classes return number-indexed arrays. handbuilt
464         // classes return column => keytype. Make this uniform.
465
466         $keys = $this->keys();
467
468         $keyskeys = array_keys($keys);
469
470         if (is_string($keyskeys[0])) {
471             return $keys;
472         }
473
474         global $_DB_DATAOBJECT;
475         if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
476             $this->databaseStructure();
477
478         }
479         return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
480     }
481
482     function encache()
483     {
484         $c = $this->memcache();
485
486         if (!$c) {
487             return false;
488         } else if ($this->tableName() == 'user' && is_object($this->id)) {
489             // Special case for User bug
490             $e = new Exception();
491             common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
492                        str_replace("\n", " ", $e->getTraceAsString()));
493             return false;
494         } else {
495             $keys = $this->_allCacheKeys();
496
497             foreach ($keys as $key) {
498                 $c->set($key, $this);
499             }
500         }
501     }
502
503     function decache()
504     {
505         $c = $this->memcache();
506
507         if (!$c) {
508             return false;
509         }
510
511         $keys = $this->_allCacheKeys();
512
513         foreach ($keys as $key) {
514             $c->delete($key, $this);
515         }
516     }
517
518     function _allCacheKeys()
519     {
520         $ckeys = array();
521
522         $types = $this->keyTypes();
523         ksort($types);
524
525         $pkey = array();
526         $pval = array();
527
528         foreach ($types as $key => $type) {
529
530             assert(!empty($key));
531
532             if ($type == 'U') {
533                 if (empty($this->$key)) {
534                     continue;
535                 }
536                 $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
537             } else if ($type == 'K' || $type == 'N') {
538                 $pkey[] = $key;
539                 $pval[] = self::valueString($this->$key);
540             } else {
541                 // Low level exception. No need for i18n as discussed with Brion.
542                 throw new Exception("Unknown key type $key => $type for " . $this->tableName());
543             }
544         }
545
546         assert(count($pkey) > 0);
547
548         // XXX: should work for both compound and scalar pkeys
549         $pvals = implode(',', $pval);
550         $pkeys = implode(',', $pkey);
551
552         $ckeys[] = $this->cacheKey($this->tableName(), $pkeys, $pvals);
553
554         return $ckeys;
555     }
556
557     static function multicache($cls, $kv)
558     {
559         ksort($kv);
560         $c = self::memcache();
561         if (!$c) {
562             return false;
563         } else {
564             return $c->get(self::multicacheKey($cls, $kv));
565         }
566     }
567
568     static function multicacheKey($cls, $kv)
569     {
570         ksort($kv);
571         $pkeys = implode(',', array_keys($kv));
572         $pvals = implode(',', array_values($kv));
573         return self::cacheKey($cls, $pkeys, $pvals);
574     }
575
576     function getSearchEngine($table)
577     {
578         require_once INSTALLDIR.'/lib/search_engines.php';
579
580         if (Event::handle('GetSearchEngine', array($this, $table, &$search_engine))) {
581             if ('mysql' === common_config('db', 'type')) {
582                 $type = common_config('search', 'type');
583                 if ($type == 'like') {
584                     $search_engine = new MySQLLikeSearch($this, $table);
585                 } else if ($type == 'fulltext') {
586                     $search_engine = new MySQLSearch($this, $table);
587                 } else {
588                     // Low level exception. No need for i18n as discussed with Brion.
589                     throw new ServerException('Unknown search type: ' . $type);
590                 }
591             } else {
592                 $search_engine = new PGSearch($this, $table);
593             }
594         }
595
596         return $search_engine;
597     }
598
599     static function cachedQuery($cls, $qry, $expiry=3600)
600     {
601         $c = Memcached_DataObject::memcache();
602         if (!$c) {
603             $inst = new $cls();
604             $inst->query($qry);
605             return $inst;
606         }
607         $key_part = Cache::keyize($cls).':'.md5($qry);
608         $ckey = Cache::key($key_part);
609         $stored = $c->get($ckey);
610
611         if ($stored !== false) {
612             return new ArrayWrapper($stored);
613         }
614
615         $inst = new $cls();
616         $inst->query($qry);
617         $cached = array();
618         while ($inst->fetch()) {
619             $cached[] = clone($inst);
620         }
621         $inst->free();
622         $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
623         return new ArrayWrapper($cached);
624     }
625
626     /**
627      * sends query to database - this is the private one that must work
628      *   - internal functions use this rather than $this->query()
629      *
630      * Overridden to do logging.
631      *
632      * @param  string  $string
633      * @access private
634      * @return mixed none or PEAR_Error
635      */
636     function _query($string)
637     {
638         if (common_config('db', 'annotate_queries')) {
639             $string = $this->annotateQuery($string);
640         }
641
642         $start = microtime(true);
643         $fail = false;
644         $result = null;
645         if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
646             common_perf_counter('query', $string);
647             try {
648                 $result = parent::_query($string);
649             } catch (Exception $e) {
650                 $fail = $e;
651             }
652             Event::handle('EndDBQuery', array($this, $string, &$result));
653         }
654         $delta = microtime(true) - $start;
655
656         $limit = common_config('db', 'log_slow_queries');
657         if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
658             $clean = $this->sanitizeQuery($string);
659             if ($fail) {
660                 $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
661             } else {
662                 $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
663             }
664             common_log(LOG_DEBUG, $msg);
665         }
666
667         if ($fail) {
668             throw $fail;
669         }
670         return $result;
671     }
672
673     /**
674      * Find the first caller in the stack trace that's not a
675      * low-level database function and add a comment to the
676      * query string. This should then be visible in process lists
677      * and slow query logs, to help identify problem areas.
678      *
679      * Also marks whether this was a web GET/POST or which daemon
680      * was running it.
681      *
682      * @param string $string SQL query string
683      * @return string SQL query string, with a comment in it
684      */
685     function annotateQuery($string)
686     {
687         $ignore = array('annotateQuery',
688                         '_query',
689                         'query',
690                         'get',
691                         'insert',
692                         'delete',
693                         'update',
694                         'find');
695         $ignoreStatic = array('getKV',
696                               'getClassKV',
697                               'pkeyGet',
698                               'pkeyGetClass',
699                               'cachedQuery');
700         $here = get_class($this); // if we get confused
701         $bt = debug_backtrace();
702
703         // Find the first caller that's not us?
704         foreach ($bt as $frame) {
705             $func = $frame['function'];
706             if (isset($frame['type']) && $frame['type'] == '::') {
707                 if (in_array($func, $ignoreStatic)) {
708                     continue;
709                 }
710                 $here = $frame['class'] . '::' . $func;
711                 break;
712             } else if (isset($frame['type']) && $frame['type'] == '->') {
713                 if ($frame['object'] === $this && in_array($func, $ignore)) {
714                     continue;
715                 }
716                 if (in_array($func, $ignoreStatic)) {
717                     continue; // @todo FIXME: This shouldn't be needed?
718                 }
719                 $here = get_class($frame['object']) . '->' . $func;
720                 break;
721             }
722             $here = $func;
723             break;
724         }
725
726         if (php_sapi_name() == 'cli') {
727             $context = basename($_SERVER['PHP_SELF']);
728         } else {
729             $context = $_SERVER['REQUEST_METHOD'];
730         }
731
732         // Slip the comment in after the first command,
733         // or DB_DataObject gets confused about handling inserts and such.
734         $parts = explode(' ', $string, 2);
735         $parts[0] .= " /* $context $here */";
736         return implode(' ', $parts);
737     }
738
739     // Sanitize a query for logging
740     // @fixme don't trim spaces in string literals
741     function sanitizeQuery($string)
742     {
743         $string = preg_replace('/\s+/', ' ', $string);
744         $string = trim($string);
745         return $string;
746     }
747
748     // We overload so that 'SET NAMES "utf8"' is called for
749     // each connection
750
751     function _connect()
752     {
753         global $_DB_DATAOBJECT, $_PEAR;
754
755         $sum = $this->_getDbDsnMD5();
756
757         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
758             !$_PEAR->isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
759             $exists = true;
760         } else {
761             $exists = false;
762        }
763
764         // @fixme horrible evil hack!
765         //
766         // In multisite configuration we don't want to keep around a separate
767         // connection for every database; we could end up with thousands of
768         // connections open per thread. In an ideal world we might keep
769         // a connection per server and select different databases, but that'd
770         // be reliant on having the same db username/pass as well.
771         //
772         // MySQL connections are cheap enough we're going to try just
773         // closing out the old connection and reopening when we encounter
774         // a new DSN.
775         //
776         // WARNING WARNING if we end up actually using multiple DBs at a time
777         // we'll need some fancier logic here.
778         if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
779             foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
780                 if (!empty($conn)) {
781                     $conn->disconnect();
782                 }
783                 unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
784             }
785         }
786
787         $result = parent::_connect();
788
789         if ($result && !$exists) {
790             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
791             if (common_config('db', 'type') == 'mysql' &&
792                 common_config('db', 'utf8')) {
793                 $conn = $DB->connection;
794                 if (!empty($conn)) {
795                     if ($DB instanceof DB_mysqli) {
796                         mysqli_set_charset($conn, 'utf8');
797                     } else if ($DB instanceof DB_mysql) {
798                         mysql_set_charset('utf8', $conn);
799                     }
800                 }
801             }
802             // Needed to make timestamp values usefully comparable.
803             if (common_config('db', 'type') == 'mysql') {
804                 parent::_query("set time_zone='+0:00'");
805             }
806         }
807
808         return $result;
809     }
810
811     // XXX: largely cadged from DB_DataObject
812
813     function _getDbDsnMD5()
814     {
815         if ($this->_database_dsn_md5) {
816             return $this->_database_dsn_md5;
817         }
818
819         $dsn = $this->_getDbDsn();
820
821         if (is_string($dsn)) {
822             $sum = md5($dsn);
823         } else {
824             /// support array based dsn's
825             $sum = md5(serialize($dsn));
826         }
827
828         return $sum;
829     }
830
831     function _getDbDsn()
832     {
833         global $_DB_DATAOBJECT;
834
835         if (empty($_DB_DATAOBJECT['CONFIG'])) {
836             DB_DataObject::_loadConfig();
837         }
838
839         $options = &$_DB_DATAOBJECT['CONFIG'];
840
841         // if the databse dsn dis defined in the object..
842
843         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
844
845         if (!$dsn) {
846
847             if (!$this->_database) {
848                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
849             }
850
851             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
852                 $dsn = $options["database_{$this->_database}"];
853             } else if (!empty($options['database'])) {
854                 $dsn = $options['database'];
855             }
856         }
857
858         if (!$dsn) {
859             // TRANS: Exception thrown when database name or Data Source Name could not be found.
860             throw new Exception(_('No database name or DSN found anywhere.'));
861         }
862
863         return $dsn;
864     }
865
866     static function blow()
867     {
868         $c = self::memcache();
869
870         if (empty($c)) {
871             return false;
872         }
873
874         $args = func_get_args();
875
876         $format = array_shift($args);
877
878         $keyPart = vsprintf($format, $args);
879
880         $cacheKey = Cache::key($keyPart);
881
882         return $c->delete($cacheKey);
883     }
884
885     function fixupTimestamps()
886     {
887         // Fake up timestamp columns
888         $columns = $this->table();
889         foreach ($columns as $name => $type) {
890             if ($type & DB_DATAOBJECT_MYSQLTIMESTAMP) {
891                 $this->$name = common_sql_now();
892             }
893         }
894     }
895
896     function debugDump()
897     {
898         common_debug("debugDump: " . common_log_objstring($this));
899     }
900
901     function raiseError($message, $type = null, $behaviour = null)
902     {
903         $id = get_class($this);
904         if (!empty($this->id)) {
905             $id .= ':' . $this->id;
906         }
907         if ($message instanceof PEAR_Error) {
908             $message = $message->getMessage();
909         }
910         // Low level exception. No need for i18n as discussed with Brion.
911         throw new ServerException("[$id] DB_DataObject error [$type]: $message");
912     }
913
914     static function cacheGet($keyPart)
915     {
916         $c = self::memcache();
917
918         if (empty($c)) {
919             return false;
920         }
921
922         $cacheKey = Cache::key($keyPart);
923
924         return $c->get($cacheKey);
925     }
926
927     static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
928     {
929         $c = self::memcache();
930
931         if (empty($c)) {
932             return false;
933         }
934
935         $cacheKey = Cache::key($keyPart);
936
937         return $c->set($cacheKey, $value, $flag, $expiry);
938     }
939
940     static function valueString($v)
941     {
942         $vstr = null;
943         if (is_object($v) && $v instanceof DB_DataObject_Cast) {
944             switch ($v->type) {
945             case 'date':
946                 $vstr = $v->year . '-' . $v->month . '-' . $v->day;
947                 break;
948             case 'blob':
949             case 'string':
950             case 'sql':
951             case 'datetime':
952             case 'time':
953                 // Low level exception. No need for i18n as discussed with Brion.
954                 throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
955                 break;
956             default:
957                 // Low level exception. No need for i18n as discussed with Brion.
958                 throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
959                 break;
960             }
961         } else {
962             $vstr = strval($v);
963         }
964         return $vstr;
965     }
966 }