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