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