Managed_DataObject.php 23 KB

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