Memcached_DataObject.php 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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 = hrtime(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 = (hrtime(true) - $start) / 1000000000;
  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 'sql':
  842. if (strcasecmp($v->value, 'NULL') == 0) {
  843. // Very selectively handling NULLs.
  844. $vstr = '';
  845. break;
  846. }
  847. // no break
  848. case 'blob':
  849. case 'string':
  850. case 'datetime':
  851. case 'time':
  852. // Low level exception. No need for i18n as discussed with Brion.
  853. throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  854. break;
  855. default:
  856. // Low level exception. No need for i18n as discussed with Brion.
  857. throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
  858. break;
  859. }
  860. } else {
  861. $vstr = strval($v);
  862. }
  863. return $vstr;
  864. }
  865. }