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