Memcached_DataObject.php 31 KB

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