Memcached_DataObject.php 31 KB

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