Memcached_DataObject.php 29 KB

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