Memcached_DataObject.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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->encache(); // in case of cached negative lookups
  396. }
  397. return $result;
  398. }
  399. public function update($dataObject = false)
  400. {
  401. if (is_object($dataObject) && $dataObject instanceof Memcached_DataObject) {
  402. $dataObject->decache(); # might be different keys
  403. }
  404. $result = parent::update($dataObject);
  405. if ($result !== false) {
  406. $this->encache();
  407. }
  408. return $result;
  409. }
  410. public function delete($useWhere = false)
  411. {
  412. $this->decache(); # while we still have the values!
  413. return parent::delete($useWhere);
  414. }
  415. public static function memcache()
  416. {
  417. return Cache::instance();
  418. }
  419. public static function cacheKey($cls, $k, $v)
  420. {
  421. if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
  422. $e = new Exception();
  423. common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
  424. str_replace("\n", " ", $e->getTraceAsString()));
  425. }
  426. $vstr = self::valueString($v);
  427. return Cache::key(strtolower($cls).':'.$k.':'.$vstr);
  428. }
  429. public static function getcached($cls, $k, $v)
  430. {
  431. $c = self::memcache();
  432. if (!$c) {
  433. return false;
  434. } else {
  435. $obj = $c->get(self::cacheKey($cls, $k, $v));
  436. if (0 == strcasecmp($cls, 'User')) {
  437. // Special case for User
  438. if (is_object($obj) && is_object($obj->id)) {
  439. common_log(LOG_ERR, "User " . $obj->nickname . " was cached with User as ID; deleting");
  440. $c->delete(self::cacheKey($cls, $k, $v));
  441. return false;
  442. }
  443. }
  444. return $obj;
  445. }
  446. }
  447. public function keyTypes()
  448. {
  449. // ini-based classes return number-indexed arrays. handbuilt
  450. // classes return column => keytype. Make this uniform.
  451. $keys = $this->keys();
  452. $keyskeys = array_keys($keys);
  453. if (is_string($keyskeys[0])) {
  454. return $keys;
  455. }
  456. global $_DB_DATAOBJECT;
  457. if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"])) {
  458. $this->databaseStructure();
  459. }
  460. return $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"];
  461. }
  462. public function encache()
  463. {
  464. $c = self::memcache();
  465. if (!$c) {
  466. return false;
  467. } elseif ($this->tableName() === 'user' && is_object($this->id)) {
  468. // Special case for User bug
  469. $e = new Exception();
  470. common_log(LOG_ERR, __METHOD__ . ' caching user with User object as ID ' .
  471. str_replace("\n", " ", $e->getTraceAsString()));
  472. return false;
  473. } else {
  474. $keys = $this->_allCacheKeys();
  475. foreach ($keys as $key) {
  476. $c->set($key, $this);
  477. }
  478. }
  479. }
  480. public function decache()
  481. {
  482. $c = self::memcache();
  483. if (!$c) {
  484. return false;
  485. }
  486. $keys = $this->_allCacheKeys();
  487. foreach ($keys as $key) {
  488. $c->delete($key, $this);
  489. }
  490. }
  491. public function _allCacheKeys()
  492. {
  493. $ckeys = array();
  494. $types = $this->keyTypes();
  495. ksort($types);
  496. $pkey = array();
  497. $pval = array();
  498. foreach ($types as $key => $type) {
  499. assert(!empty($key));
  500. if ($type == 'U') {
  501. if (empty($this->$key)) {
  502. continue;
  503. }
  504. $ckeys[] = self::cacheKey($this->tableName(), $key, self::valueString($this->$key));
  505. } elseif (in_array($type, ['K', 'N'])) {
  506. $pkey[] = $key;
  507. $pval[] = self::valueString($this->$key);
  508. } else {
  509. // Low level exception. No need for i18n as discussed with Brion.
  510. throw new Exception("Unknown key type $key => $type for " . $this->tableName());
  511. }
  512. }
  513. assert(count($pkey) > 0);
  514. // XXX: should work for both compound and scalar pkeys
  515. $pvals = implode(',', $pval);
  516. $pkeys = implode(',', $pkey);
  517. $ckeys[] = self::cacheKey($this->tableName(), $pkeys, $pvals);
  518. return $ckeys;
  519. }
  520. public static function multicache($cls, $kv)
  521. {
  522. ksort($kv);
  523. $c = self::memcache();
  524. if (!$c) {
  525. return false;
  526. } else {
  527. return $c->get(self::multicacheKey($cls, $kv));
  528. }
  529. }
  530. public static function multicacheKey($cls, $kv)
  531. {
  532. ksort($kv);
  533. $pkeys = implode(',', array_keys($kv));
  534. $pvals = implode(',', array_values($kv));
  535. return self::cacheKey($cls, $pkeys, $pvals);
  536. }
  537. public function getSearchEngine($table)
  538. {
  539. require_once INSTALLDIR . '/lib/search/search_engines.php';
  540. if (Event::handle('GetSearchEngine', [$this, $table, &$search_engine])) {
  541. $type = common_config('search', 'type');
  542. if ($type === 'like') {
  543. $search_engine = new SQLLikeSearch($this, $table);
  544. } elseif ($type === 'fulltext') {
  545. switch (common_config('db', 'type')) {
  546. case 'pgsql':
  547. $search_engine = new PostgreSQLSearch($this, $table);
  548. break;
  549. case 'mysql':
  550. $search_engine = new MySQLSearch($this, $table);
  551. break;
  552. default:
  553. throw new ServerException('Unknown DB type selected.');
  554. }
  555. } else {
  556. // Low level exception. No need for i18n as discussed with Brion.
  557. throw new ServerException('Unknown search type: ' . $type);
  558. }
  559. }
  560. return $search_engine;
  561. }
  562. public static function cachedQuery($cls, $qry, $expiry = 3600)
  563. {
  564. $c = self::memcache();
  565. if (!$c) {
  566. $inst = new $cls();
  567. $inst->query($qry);
  568. return $inst;
  569. }
  570. $key_part = Cache::keyize($cls).':'.md5($qry);
  571. $ckey = Cache::key($key_part);
  572. $stored = $c->get($ckey);
  573. if ($stored !== false) {
  574. return new ArrayWrapper($stored);
  575. }
  576. $inst = new $cls();
  577. $inst->query($qry);
  578. $cached = array();
  579. while ($inst->fetch()) {
  580. $cached[] = clone($inst);
  581. }
  582. $inst->free();
  583. $c->set($ckey, $cached, Cache::COMPRESSED, $expiry);
  584. return new ArrayWrapper($cached);
  585. }
  586. /**
  587. * sends query to database - this is the private one that must work
  588. * - internal functions use this rather than $this->query()
  589. *
  590. * Overridden to do logging.
  591. *
  592. * @param string $string
  593. * @access private
  594. * @return mixed none or PEAR_Error
  595. */
  596. public function _query($string)
  597. {
  598. if (common_config('db', 'annotate_queries')) {
  599. $string = $this->annotateQuery($string);
  600. }
  601. $start = hrtime(true);
  602. $fail = false;
  603. $result = null;
  604. if (Event::handle('StartDBQuery', array($this, $string, &$result))) {
  605. common_perf_counter('query', $string);
  606. try {
  607. $result = parent::_query($string);
  608. } catch (Exception $e) {
  609. $fail = $e;
  610. }
  611. Event::handle('EndDBQuery', array($this, $string, &$result));
  612. }
  613. $delta = (hrtime(true) - $start) / 1000000000;
  614. $limit = common_config('db', 'log_slow_queries');
  615. if (($limit > 0 && $delta >= $limit) || common_config('db', 'log_queries')) {
  616. $clean = $this->sanitizeQuery($string);
  617. if ($fail) {
  618. $msg = sprintf("FAILED DB query (%0.3fs): %s - %s", $delta, $fail->getMessage(), $clean);
  619. } else {
  620. $msg = sprintf("DB query (%0.3fs): %s", $delta, $clean);
  621. }
  622. common_log(LOG_DEBUG, $msg);
  623. }
  624. if ($fail) {
  625. throw $fail;
  626. }
  627. return $result;
  628. }
  629. /**
  630. * Find the first caller in the stack trace that's not a
  631. * low-level database function and add a comment to the
  632. * query string. This should then be visible in process lists
  633. * and slow query logs, to help identify problem areas.
  634. *
  635. * Also marks whether this was a web GET/POST or which daemon
  636. * was running it.
  637. *
  638. * @param string $string SQL query string
  639. * @return string SQL query string, with a comment in it
  640. */
  641. public function annotateQuery($string)
  642. {
  643. $ignore = array('annotateQuery',
  644. '_query',
  645. 'query',
  646. 'get',
  647. 'insert',
  648. 'delete',
  649. 'update',
  650. 'find');
  651. $ignoreStatic = array('getKV',
  652. 'getClassKV',
  653. 'pkeyGet',
  654. 'pkeyGetClass',
  655. 'cachedQuery');
  656. $here = get_class($this); // if we get confused
  657. $bt = debug_backtrace();
  658. // Find the first caller that's not us?
  659. foreach ($bt as $frame) {
  660. $func = $frame['function'];
  661. if (isset($frame['type']) && $frame['type'] == '::') {
  662. if (in_array($func, $ignoreStatic)) {
  663. continue;
  664. }
  665. $here = $frame['class'] . '::' . $func;
  666. break;
  667. } elseif (isset($frame['type']) && $frame['type'] === '->') {
  668. if ($frame['object'] === $this && in_array($func, $ignore)) {
  669. continue;
  670. }
  671. if (in_array($func, $ignoreStatic)) {
  672. continue; // @todo FIXME: This shouldn't be needed?
  673. }
  674. $here = get_class($frame['object']) . '->' . $func;
  675. break;
  676. }
  677. $here = $func;
  678. break;
  679. }
  680. if (php_sapi_name() == 'cli') {
  681. $context = basename($_SERVER['PHP_SELF']);
  682. } else {
  683. $context = $_SERVER['REQUEST_METHOD'];
  684. }
  685. // Slip the comment in after the first command,
  686. // or DB_DataObject gets confused about handling inserts and such.
  687. $parts = explode(' ', $string, 2);
  688. $parts[0] .= " /* $context $here */";
  689. return implode(' ', $parts);
  690. }
  691. // Sanitize a query for logging
  692. // @fixme don't trim spaces in string literals
  693. public function sanitizeQuery($string)
  694. {
  695. $string = preg_replace('/\s+/', ' ', $string);
  696. $string = trim($string);
  697. return $string;
  698. }
  699. // We overload so that 'SET NAMES "utf8mb4"' is called for
  700. // each connection
  701. public function _connect()
  702. {
  703. global $_DB_DATAOBJECT, $_PEAR;
  704. $sum = $this->_getDbDsnMD5();
  705. if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) &&
  706. !$_PEAR->isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) {
  707. $exists = true;
  708. } else {
  709. $exists = false;
  710. }
  711. // @fixme horrible evil hack!
  712. //
  713. // In multisite configuration we don't want to keep around a separate
  714. // connection for every database; we could end up with thousands of
  715. // connections open per thread. In an ideal world we might keep
  716. // a connection per server and select different databases, but that'd
  717. // be reliant on having the same db username/pass as well.
  718. //
  719. // MySQL connections are cheap enough we're going to try just
  720. // closing out the old connection and reopening when we encounter
  721. // a new DSN.
  722. //
  723. // WARNING WARNING if we end up actually using multiple DBs at a time
  724. // we'll need some fancier logic here.
  725. if (!$exists && !empty($_DB_DATAOBJECT['CONNECTIONS']) && php_sapi_name() == 'cli') {
  726. foreach ($_DB_DATAOBJECT['CONNECTIONS'] as $index => $conn) {
  727. if ($_PEAR->isError($conn)) {
  728. common_log(LOG_WARNING, __METHOD__ . " cannot disconnect failed DB connection: '".$conn->getMessage()."'.");
  729. } elseif (!empty($conn)) {
  730. $conn->disconnect();
  731. }
  732. unset($_DB_DATAOBJECT['CONNECTIONS'][$index]);
  733. }
  734. }
  735. $result = parent::_connect();
  736. if ($result && !$exists) {
  737. $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  738. if (common_config('db', 'type') == 'mysql' &&
  739. common_config('db', 'utf8')) {
  740. $conn = $DB->connection;
  741. if (!empty($conn)) {
  742. if ($DB instanceof DB_mysqli || $DB instanceof MDB2_Driver_mysqli) {
  743. mysqli_set_charset($conn, 'utf8mb4');
  744. } elseif ($DB instanceof DB_mysql || $DB instanceof MDB2_Driver_mysql) {
  745. mysql_set_charset('utf8mb4', $conn);
  746. }
  747. }
  748. }
  749. // Needed to make timestamp values usefully comparable.
  750. if (common_config('db', 'type') == 'mysql') {
  751. parent::_query("set time_zone='+0:00'");
  752. }
  753. }
  754. return $result;
  755. }
  756. // XXX: largely cadged from DB_DataObject
  757. public function _getDbDsnMD5()
  758. {
  759. if ($this->_database_dsn_md5) {
  760. return $this->_database_dsn_md5;
  761. }
  762. $dsn = $this->_getDbDsn();
  763. if (is_string($dsn)) {
  764. $sum = md5($dsn);
  765. } else {
  766. /// support array based dsn's
  767. $sum = md5(serialize($dsn));
  768. }
  769. return $sum;
  770. }
  771. public function _getDbDsn()
  772. {
  773. global $_DB_DATAOBJECT;
  774. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  775. self::_loadConfig();
  776. }
  777. $options = &$_DB_DATAOBJECT['CONFIG'];
  778. // if the databse dsn dis defined in the object..
  779. $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
  780. if (!$dsn) {
  781. if (!$this->_database) {
  782. $this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
  783. }
  784. if ($this->_database && !empty($options["database_{$this->_database}"])) {
  785. $dsn = $options["database_{$this->_database}"];
  786. } elseif (!empty($options['database'])) {
  787. $dsn = $options['database'];
  788. }
  789. }
  790. if (!$dsn) {
  791. // TRANS: Exception thrown when database name or Data Source Name could not be found.
  792. throw new Exception(_('No database name or DSN found anywhere.'));
  793. }
  794. return $dsn;
  795. }
  796. public static function blow()
  797. {
  798. $c = self::memcache();
  799. if (empty($c)) {
  800. return false;
  801. }
  802. $args = func_get_args();
  803. $format = array_shift($args);
  804. $keyPart = vsprintf($format, $args);
  805. $cacheKey = Cache::key($keyPart);
  806. return $c->delete($cacheKey);
  807. }
  808. public function raiseError($message, $type = null, $behavior = null)
  809. {
  810. $id = get_class($this);
  811. if (!empty($this->id)) {
  812. $id .= ':' . $this->id;
  813. }
  814. if ($message instanceof PEAR_Error) {
  815. $message = $message->getMessage();
  816. }
  817. // Low level exception. No need for i18n as discussed with Brion.
  818. throw new ServerException("[$id] DB_DataObject error [$type]: $message");
  819. }
  820. public static function cacheGet($keyPart)
  821. {
  822. $c = self::memcache();
  823. if (empty($c)) {
  824. return false;
  825. }
  826. $cacheKey = Cache::key($keyPart);
  827. return $c->get($cacheKey);
  828. }
  829. public static function cacheSet($keyPart, $value, $flag = null, $expiry = null)
  830. {
  831. $c = self::memcache();
  832. if (empty($c)) {
  833. return false;
  834. }
  835. $cacheKey = Cache::key($keyPart);
  836. return $c->set($cacheKey, $value, $flag, $expiry);
  837. }
  838. public static function valueString($v)
  839. {
  840. $vstr = null;
  841. if (is_object($v) && $v instanceof DB_DataObject_Cast) {
  842. switch ($v->type) {
  843. case 'date':
  844. $vstr = "{$v->year} - {$v->month} - {$v->day}";
  845. break;
  846. case 'sql':
  847. if (strcasecmp($v->value, 'NULL') == 0) {
  848. // Very selectively handling NULLs.
  849. $vstr = '';
  850. break;
  851. }
  852. // no break
  853. case 'blob':
  854. case 'string':
  855. case 'datetime':
  856. case 'time':
  857. // Low level exception. No need for i18n as discussed with Brion.
  858. throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  859. break;
  860. default:
  861. // Low level exception. No need for i18n as discussed with Brion.
  862. throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  863. break;
  864. }
  865. } else {
  866. $vstr = strval($v);
  867. }
  868. return $vstr;
  869. }
  870. }