Memcached_DataObject.php 29 KB

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