Memcached_DataObject.php 30 KB

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