Managed_DataObject.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. * Wrapper for Memcached_DataObject which knows its own schema definition.
  18. * Builds its own damn settings from a schema definition.
  19. *
  20. * @package GNUsocial
  21. * @author Brion Vibber <brion@status.net>
  22. * @copyright 2010 Free Software Foundation, Inc http://www.fsf.org
  23. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  24. */
  25. defined('GNUSOCIAL') || die();
  26. abstract class Managed_DataObject extends Memcached_DataObject
  27. {
  28. /**
  29. * The One True Thingy that must be defined and declared.
  30. */
  31. public static function schemaDef()
  32. {
  33. throw new MethodNotImplementedException(__METHOD__);
  34. }
  35. /**
  36. * Get an instance by key
  37. *
  38. * @param string $k Key to use to lookup (usually 'id' for this class)
  39. * @param mixed $v Value to lookup
  40. *
  41. * @return get_called_class() object if found, or null for no hits
  42. *
  43. */
  44. public static function getKV($k, $v = null)
  45. {
  46. return parent::getClassKV(get_called_class(), $k, $v);
  47. }
  48. /**
  49. * Get an instance by compound key
  50. *
  51. * This is a utility method to get a single instance with a given set of
  52. * key-value pairs. Usually used for the primary key for a compound key; thus
  53. * the name.
  54. *
  55. * @param array $kv array of key-value mappings
  56. *
  57. * @return get_called_class() object if found, or null for no hits
  58. *
  59. */
  60. public static function pkeyGet(array $kv)
  61. {
  62. return parent::pkeyGetClass(get_called_class(), $kv);
  63. }
  64. public static function pkeyCols()
  65. {
  66. return parent::pkeyColsClass(get_called_class());
  67. }
  68. /**
  69. * Get multiple items from the database by key
  70. *
  71. * @param string $keyCol name of column for key
  72. * @param array $keyVals key values to fetch
  73. * @param boolean $skipNulls return only non-null results?
  74. *
  75. * @return array Array of objects, in order
  76. */
  77. public static function multiGet($keyCol, array $keyVals, $skipNulls = true)
  78. {
  79. return parent::multiGetClass(get_called_class(), $keyCol, $keyVals, $skipNulls);
  80. }
  81. /**
  82. * Get multiple items from the database by key
  83. *
  84. * @param string $keyCol name of column for key
  85. * @param array $keyVals key values to fetch
  86. * @param array $otherCols Other columns to hold fixed
  87. *
  88. * @return array Array mapping $keyVals to objects, or null if not found
  89. */
  90. public static function pivotGet($keyCol, array $keyVals, array $otherCols = [])
  91. {
  92. return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
  93. }
  94. /**
  95. * Get a multi-instance object
  96. *
  97. * This is a utility method to get multiple instances with a given set of
  98. * values for a specific column.
  99. *
  100. * @param string $keyCol key column name
  101. * @param array $keyVals array of key values
  102. *
  103. * @return get_called_class() object with multiple instances if found,
  104. * Exception is thrown when no entries are found.
  105. *
  106. */
  107. public static function listFind($keyCol, array $keyVals)
  108. {
  109. return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
  110. }
  111. /**
  112. * Get a multi-instance object separated into an array
  113. *
  114. * This is a utility method to get multiple instances with a given set of
  115. * values for a specific key column. Usually used for the primary key when
  116. * multiple values are desired. Result is an array.
  117. *
  118. * @param string $keyCol key column name
  119. * @param array $keyVals array of key values
  120. *
  121. * @return array with an get_called_class() object for each $keyVals entry
  122. *
  123. */
  124. public static function listGet($keyCol, array $keyVals)
  125. {
  126. return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
  127. }
  128. /**
  129. * get/set an associative array of table columns
  130. *
  131. * @access public
  132. * @return array (associative)
  133. */
  134. public function table()
  135. {
  136. $table = static::schemaDef();
  137. return array_map(array($this, 'columnBitmap'), $table['fields']);
  138. }
  139. /**
  140. * get/set an array of table primary keys
  141. *
  142. * Key info is pulled from the table definition array.
  143. *
  144. * @access private
  145. * @return array
  146. */
  147. public function keys()
  148. {
  149. return array_keys($this->keyTypes());
  150. }
  151. /**
  152. * Get a sequence key
  153. *
  154. * Returns the first serial column defined in the table, if any.
  155. *
  156. * @access private
  157. * @return array (column,use_native,sequence_name)
  158. */
  159. public function sequenceKey()
  160. {
  161. $table = static::schemaDef();
  162. foreach ($table['fields'] as $name => $column) {
  163. if ($column['type'] == 'serial') {
  164. // We have a serial/autoincrement column.
  165. // Declare it to be a native sequence!
  166. return array($name, true, false);
  167. }
  168. }
  169. // No sequence key on this table.
  170. return array(false, false, false);
  171. }
  172. /**
  173. * Return key definitions for DB_DataObject and Memcache_DataObject.
  174. *
  175. * DB_DataObject needs to know about keys that the table has; this function
  176. * defines them.
  177. *
  178. * @return array key definitions
  179. */
  180. public function keyTypes()
  181. {
  182. $table = static::schemaDef();
  183. $keys = array();
  184. if (!empty($table['unique keys'])) {
  185. foreach ($table['unique keys'] as $idx => $fields) {
  186. foreach ($fields as $name) {
  187. $keys[$name] = 'U';
  188. }
  189. }
  190. }
  191. if (!empty($table['primary key'])) {
  192. foreach ($table['primary key'] as $name) {
  193. $keys[$name] = 'K';
  194. }
  195. }
  196. return $keys;
  197. }
  198. /**
  199. * Build the appropriate DB_DataObject bitfield map for this field.
  200. *
  201. * @param array $column
  202. * @return int
  203. */
  204. public function columnBitmap($column)
  205. {
  206. $type = $column['type'];
  207. // For quoting style...
  208. $intTypes = [
  209. 'int',
  210. 'float',
  211. 'serial',
  212. 'numeric'
  213. ];
  214. if (in_array($type, $intTypes)) {
  215. $style = DB_DATAOBJECT_INT;
  216. } else {
  217. $style = DB_DATAOBJECT_STR;
  218. }
  219. // Data type formatting style...
  220. $formatStyles = [
  221. 'blob' => DB_DATAOBJECT_BLOB,
  222. 'text' => DB_DATAOBJECT_TXT,
  223. 'bool' => DB_DATAOBJECT_BOOL,
  224. 'date' => DB_DATAOBJECT_DATE,
  225. 'time' => DB_DATAOBJECT_TIME,
  226. 'datetime' => DB_DATAOBJECT_DATE | DB_DATAOBJECT_TIME,
  227. 'timestamp' => DB_DATAOBJECT_MYSQLTIMESTAMP,
  228. ];
  229. if (isset($formatStyles[$type])) {
  230. $style |= $formatStyles[$type];
  231. }
  232. // Nullable?
  233. if (!empty($column['not null'])) {
  234. $style |= DB_DATAOBJECT_NOTNULL;
  235. }
  236. return $style;
  237. }
  238. public function links()
  239. {
  240. $links = array();
  241. $table = static::schemaDef();
  242. foreach ($table['foreign keys'] as $keyname => $keydef) {
  243. if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
  244. if (isset($keydef[1][0])) {
  245. $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
  246. }
  247. }
  248. }
  249. return $links;
  250. }
  251. /**
  252. * Return a list of all primary/unique keys / vals that will be used for
  253. * caching. This will understand compound unique keys, which
  254. * Memcached_DataObject doesn't have enough info to handle properly.
  255. *
  256. * @return array of strings
  257. * @throws MethodNotImplementedException
  258. * @throws ServerException
  259. */
  260. public function _allCacheKeys()
  261. {
  262. $table = static::schemaDef();
  263. $ckeys = array();
  264. if (!empty($table['unique keys'])) {
  265. $keyNames = $table['unique keys'];
  266. foreach ($keyNames as $idx => $fields) {
  267. $val = array();
  268. foreach ($fields as $name) {
  269. $val[$name] = self::valueString($this->$name);
  270. }
  271. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  272. }
  273. }
  274. if (!empty($table['primary key'])) {
  275. $fields = $table['primary key'];
  276. $val = array();
  277. foreach ($fields as $name) {
  278. $val[$name] = self::valueString($this->$name);
  279. }
  280. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  281. }
  282. return $ckeys;
  283. }
  284. public function escapedTableName()
  285. {
  286. return common_database_tablename($this->tableName());
  287. }
  288. /**
  289. * Returns an object by looking at the primary key column(s).
  290. *
  291. * Will require all primary key columns to be defined in an associative array
  292. * and ignore any keys which are not part of the primary key.
  293. *
  294. * Will NOT accept NULL values as part of primary key.
  295. *
  296. * @param array $vals Must match all primary key columns for the dataobject.
  297. *
  298. * @return Managed_DataObject of the get_called_class() type
  299. * @throws NoResultException if no object with that primary key
  300. */
  301. public static function getByPK(array $vals)
  302. {
  303. $classname = get_called_class();
  304. $pkey = static::pkeyCols();
  305. if (is_null($pkey)) {
  306. throw new ServerException("Failed to get primary key columns for class '{$classname}'");
  307. }
  308. $object = new $classname();
  309. foreach ($pkey as $col) {
  310. if (!array_key_exists($col, $vals)) {
  311. throw new ServerException("Missing primary key column '{$col}' for ".get_called_class()." among provided keys: ".implode(',', array_keys($vals)));
  312. } elseif (is_null($vals[$col])) {
  313. throw new ServerException("NULL values not allowed in getByPK for column '{$col}'");
  314. }
  315. $object->$col = $vals[$col];
  316. }
  317. if (!$object->find(true)) {
  318. throw new NoResultException($object);
  319. }
  320. return $object;
  321. }
  322. /**
  323. * Returns an object by looking at given unique key columns.
  324. *
  325. * Will NOT accept NULL values for a unique key column. Ignores non-key values.
  326. *
  327. * @param array $vals All array keys which are set must be non-null.
  328. *
  329. * @return Managed_DataObject of the get_called_class() type
  330. * @throws NoResultException if no object with that primary key
  331. */
  332. public static function getByKeys(array $vals)
  333. {
  334. $classname = get_called_class();
  335. $object = new $classname();
  336. $keys = $object->keys();
  337. if (is_null($keys)) {
  338. throw new ServerException("Failed to get key columns for class '{$classname}'");
  339. }
  340. foreach ($keys as $col) {
  341. if (!array_key_exists($col, $vals)) {
  342. continue;
  343. } elseif (is_null($vals[$col])) {
  344. throw new ServerException("NULL values not allowed in getByKeys for column '{$col}'");
  345. }
  346. $object->$col = $vals[$col];
  347. }
  348. if (!$object->find(true)) {
  349. throw new NoResultException($object);
  350. }
  351. return $object;
  352. }
  353. public static function getByID($id)
  354. {
  355. if (!property_exists(get_called_class(), 'id')) {
  356. throw new ServerException('Trying to get undefined property of dataobject class.');
  357. }
  358. if (empty($id)) {
  359. throw new EmptyPkeyValueException(get_called_class(), 'id');
  360. }
  361. // getByPK throws exception if id is null
  362. // or if the class does not have a single 'id' column as primary key
  363. return static::getByPK(array('id' => $id));
  364. }
  365. public static function getByUri($uri)
  366. {
  367. if (!property_exists(get_called_class(), 'uri')) {
  368. throw new ServerException('Trying to get undefined property of dataobject class.');
  369. }
  370. if (empty($uri)) {
  371. throw new EmptyPkeyValueException(get_called_class(), 'uri');
  372. }
  373. $class = get_called_class();
  374. $obj = new $class();
  375. $obj->uri = $uri;
  376. if (!$obj->find(true)) {
  377. throw new NoResultException($obj);
  378. }
  379. return $obj;
  380. }
  381. /**
  382. * Returns an ID, checked that it is set and reasonably valid
  383. *
  384. * If this dataobject uses a special id field (not 'id'), just
  385. * implement your ID getting method in the child class.
  386. *
  387. * @return int ID of dataobject
  388. * @throws Exception (when ID is not available or not set yet)
  389. */
  390. public function getID()
  391. {
  392. // FIXME: Make these exceptions more specific (their own classes)
  393. if (!isset($this->id)) {
  394. throw new Exception('No ID set.');
  395. } elseif (empty($this->id)) {
  396. throw new Exception('Empty ID for object! (not inserted yet?).');
  397. }
  398. return intval($this->id);
  399. }
  400. /**
  401. * WARNING: Only use this on Profile and Notice. We should probably do
  402. * this with traits/"implements" or whatever, but that's over the top
  403. * right now, I'm just throwing this in here to avoid code duplication
  404. * in Profile and Notice classes.
  405. */
  406. public function getAliases()
  407. {
  408. return array_keys($this->getAliasesWithIDs());
  409. }
  410. public function getAliasesWithIDs()
  411. {
  412. $aliases = array();
  413. $aliases[$this->getUri()] = $this->getID();
  414. try {
  415. $aliases[$this->getUrl()] = $this->getID();
  416. } catch (InvalidUrlException $e) {
  417. // getUrl failed because no valid URL could be returned, just ignore it
  418. }
  419. if (common_config('fix', 'fancyurls')) {
  420. /**
  421. * Here we add some hacky hotfixes for remote lookups that have been taught the
  422. * (at least now) wrong URI but it's still obviously the same user. Such as:
  423. * - https://site.example/user/1 even if the client requests https://site.example/index.php/user/1
  424. * - https://site.example/user/1 even if the client requests https://site.example//index.php/user/1
  425. * - https://site.example/index.php/user/1 even if the client requests https://site.example/user/1
  426. * - https://site.example/index.php/user/1 even if the client requests https://site.example///index.php/user/1
  427. */
  428. foreach ($aliases as $alias=>$id) {
  429. try {
  430. // get a "fancy url" version of the alias, even without index.php/
  431. $alt_url = common_fake_local_fancy_url($alias);
  432. // store this as well so remote sites can be sure we really are the same profile
  433. $aliases[$alt_url] = $id;
  434. } catch (Exception $e) {
  435. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  436. }
  437. try {
  438. // get a non-"fancy url" version of the alias, i.e. add index.php/
  439. $alt_url = common_fake_local_nonfancy_url($alias);
  440. // store this as well so remote sites can be sure we really are the same profile
  441. $aliases[$alt_url] = $id;
  442. } catch (Exception $e) {
  443. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  444. }
  445. }
  446. }
  447. return $aliases;
  448. }
  449. /**
  450. * "update" won't write key columns, so we have to do it ourselves.
  451. * This also automatically calls "update" _before_ it sets the keys.
  452. * FIXME: This only works with single-column primary keys so far! Beware!
  453. *
  454. * @param Managed_DataObject $orig Must be "instanceof" $this
  455. * @param string|null $pid (optional) Primary ID column (no escaping is done on column name!)
  456. * @return bool|void|number of changed rows, no guarantees are made about the return really...
  457. * @throws MethodNotImplementedException
  458. * @throws ServerException
  459. */
  460. public function updateWithKeys(Managed_DataObject $orig, ?string $pid = null)
  461. {
  462. if (!$orig instanceof $this) {
  463. throw new ServerException('Tried updating a DataObject with a different class than itself.');
  464. }
  465. if ($this->N <1) {
  466. throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
  467. }
  468. $this->onUpdateKeys($orig);
  469. // do it in a transaction
  470. $this->query('BEGIN');
  471. $parts = [];
  472. foreach ($this->keys() as $k) {
  473. $v = $this->table()[$k];
  474. if ($this->$k !== $orig->$k) {
  475. if (is_object($this->$k) && $this->$k instanceof DB_DataObject_Cast) {
  476. $value = $this->$k->toString($v, $this->getDatabaseConnection());
  477. } elseif (DB_DataObject::_is_null($this, $k)) {
  478. $value = 'NULL';
  479. } elseif ($v & DB_DATAOBJECT_STR) { // if a string
  480. $value = $this->_quote((string) $this->$k);
  481. } else {
  482. $value = (int) $this->$k;
  483. }
  484. $parts[] = "{$k} = {$value}";
  485. }
  486. }
  487. if (count($parts) == 0) {
  488. // No changes to keys, it's safe to run ->update(...)
  489. if ($this->update($orig) === false) {
  490. common_log_db_error($this, 'UPDATE', __FILE__);
  491. // rollback as something bad occurred
  492. $this->query('ROLLBACK');
  493. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  494. }
  495. $orig->decache();
  496. $this->encache();
  497. // commit our db transaction since we won't reach the COMMIT below
  498. $this->query('COMMIT');
  499. // @FIXME return true only if something changed (otherwise 0)
  500. return true;
  501. }
  502. if ($pid === null) {
  503. $schema = static::schemaDef();
  504. $pid = $schema['primary key'];
  505. unset($schema);
  506. }
  507. $pidWhere = [];
  508. foreach ((array) $pid as $pidCol) {
  509. $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
  510. }
  511. if (empty($pidWhere)) {
  512. throw new ServerException('No primary ID column(s) set for updateWithKeys');
  513. }
  514. $qry = sprintf(
  515. 'UPDATE %1$s SET %2$s WHERE %3$s',
  516. $this->escapedTableName(),
  517. implode(', ', $parts),
  518. implode(' AND ', $pidWhere)
  519. );
  520. $result = $this->query($qry);
  521. if ($result === false) {
  522. common_log_db_error($this, 'UPDATE', __FILE__);
  523. // rollback as something bad occurred
  524. $this->query('ROLLBACK');
  525. throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
  526. }
  527. // Update non-keys too, if the previous endeavour worked.
  528. // The ->update call uses "$this" values for keys, that's why we can't do this until
  529. // the keys are updated (because they might differ from $orig and update the wrong entries).
  530. if ($this->update($orig) === false) {
  531. common_log_db_error($this, 'UPDATE', __FILE__);
  532. // rollback as something bad occurred
  533. $this->query('ROLLBACK');
  534. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  535. }
  536. $orig->decache();
  537. $this->encache();
  538. // commit our db transaction
  539. $this->query('COMMIT');
  540. // @FIXME return true only if something changed (otherwise 0)
  541. return $result;
  542. }
  543. public static function beforeSchemaUpdate()
  544. {
  545. // NOOP
  546. }
  547. public static function newUri(Profile $actor, Managed_DataObject $object, $created = null)
  548. {
  549. if (is_null($created)) {
  550. $created = common_sql_now();
  551. }
  552. return TagURI::mint(
  553. strtolower(get_called_class()) . ':%d:%s:%d:%s',
  554. $actor->getID(),
  555. ActivityUtils::resolveUri($object->getObjectType(), true),
  556. $object->getID(),
  557. common_date_iso8601($created)
  558. );
  559. }
  560. protected function onInsert()
  561. {
  562. // NOOP by default
  563. }
  564. protected function onUpdate($dataObject=false)
  565. {
  566. // NOOP by default
  567. }
  568. protected function onUpdateKeys(Managed_DataObject $orig)
  569. {
  570. // NOOP by default
  571. }
  572. public function insert()
  573. {
  574. $this->onInsert();
  575. return parent::insert();
  576. }
  577. public function update($dataObject=false)
  578. {
  579. $this->onUpdate($dataObject);
  580. return parent::update($dataObject);
  581. }
  582. }