Managed_DataObject.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. ];
  228. if (isset($formatStyles[$type])) {
  229. $style |= $formatStyles[$type];
  230. }
  231. // Nullable?
  232. if (!empty($column['not null'])) {
  233. $style |= DB_DATAOBJECT_NOTNULL;
  234. }
  235. return $style;
  236. }
  237. public function links()
  238. {
  239. $links = array();
  240. $table = static::schemaDef();
  241. foreach ($table['foreign keys'] as $keyname => $keydef) {
  242. if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
  243. if (isset($keydef[1][0])) {
  244. $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
  245. }
  246. }
  247. }
  248. return $links;
  249. }
  250. /**
  251. * Return a list of all primary/unique keys / vals that will be used for
  252. * caching. This will understand compound unique keys, which
  253. * Memcached_DataObject doesn't have enough info to handle properly.
  254. *
  255. * @return array of strings
  256. * @throws MethodNotImplementedException
  257. * @throws ServerException
  258. */
  259. public function _allCacheKeys()
  260. {
  261. $table = static::schemaDef();
  262. $ckeys = array();
  263. if (!empty($table['unique keys'])) {
  264. $keyNames = $table['unique keys'];
  265. foreach ($keyNames as $idx => $fields) {
  266. $val = array();
  267. foreach ($fields as $name) {
  268. $val[$name] = self::valueString($this->$name);
  269. }
  270. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  271. }
  272. }
  273. if (!empty($table['primary key'])) {
  274. $fields = $table['primary key'];
  275. $val = array();
  276. foreach ($fields as $name) {
  277. $val[$name] = self::valueString($this->$name);
  278. }
  279. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  280. }
  281. return $ckeys;
  282. }
  283. public function escapedTableName()
  284. {
  285. return common_database_tablename($this->tableName());
  286. }
  287. /**
  288. * Returns an object by looking at the primary key column(s).
  289. *
  290. * Will require all primary key columns to be defined in an associative array
  291. * and ignore any keys which are not part of the primary key.
  292. *
  293. * Will NOT accept NULL values as part of primary key.
  294. *
  295. * @param array $vals Must match all primary key columns for the dataobject.
  296. *
  297. * @return Managed_DataObject of the get_called_class() type
  298. * @throws NoResultException if no object with that primary key
  299. */
  300. public static function getByPK(array $vals)
  301. {
  302. $classname = get_called_class();
  303. $pkey = static::pkeyCols();
  304. if (is_null($pkey)) {
  305. throw new ServerException("Failed to get primary key columns for class '{$classname}'");
  306. }
  307. $object = new $classname();
  308. foreach ($pkey as $col) {
  309. if (!array_key_exists($col, $vals)) {
  310. throw new ServerException("Missing primary key column '{$col}' for ".get_called_class()." among provided keys: ".implode(',', array_keys($vals)));
  311. } elseif (is_null($vals[$col])) {
  312. throw new ServerException("NULL values not allowed in getByPK for column '{$col}'");
  313. }
  314. $object->$col = $vals[$col];
  315. }
  316. if (!$object->find(true)) {
  317. throw new NoResultException($object);
  318. }
  319. return $object;
  320. }
  321. /**
  322. * Returns an object by looking at given unique key columns.
  323. *
  324. * Will NOT accept NULL values for a unique key column. Ignores non-key values.
  325. *
  326. * @param array $vals All array keys which are set must be non-null.
  327. *
  328. * @return Managed_DataObject of the get_called_class() type
  329. * @throws NoResultException if no object with that primary key
  330. */
  331. public static function getByKeys(array $vals)
  332. {
  333. $classname = get_called_class();
  334. $object = new $classname();
  335. $keys = $object->keys();
  336. if (is_null($keys)) {
  337. throw new ServerException("Failed to get key columns for class '{$classname}'");
  338. }
  339. foreach ($keys as $col) {
  340. if (!array_key_exists($col, $vals)) {
  341. continue;
  342. } elseif (is_null($vals[$col])) {
  343. throw new ServerException("NULL values not allowed in getByKeys for column '{$col}'");
  344. }
  345. $object->$col = $vals[$col];
  346. }
  347. if (!$object->find(true)) {
  348. throw new NoResultException($object);
  349. }
  350. return $object;
  351. }
  352. public static function getByID($id)
  353. {
  354. if (!property_exists(get_called_class(), 'id')) {
  355. throw new ServerException('Trying to get undefined property of dataobject class.');
  356. }
  357. if (empty($id)) {
  358. throw new EmptyPkeyValueException(get_called_class(), 'id');
  359. }
  360. // getByPK throws exception if id is null
  361. // or if the class does not have a single 'id' column as primary key
  362. return static::getByPK(array('id' => $id));
  363. }
  364. public static function getByUri($uri)
  365. {
  366. if (!property_exists(get_called_class(), 'uri')) {
  367. throw new ServerException('Trying to get undefined property of dataobject class.');
  368. }
  369. if (empty($uri)) {
  370. throw new EmptyPkeyValueException(get_called_class(), 'uri');
  371. }
  372. $class = get_called_class();
  373. $obj = new $class();
  374. $obj->uri = $uri;
  375. if (!$obj->find(true)) {
  376. throw new NoResultException($obj);
  377. }
  378. return $obj;
  379. }
  380. /**
  381. * Returns an ID, checked that it is set and reasonably valid
  382. *
  383. * If this dataobject uses a special id field (not 'id'), just
  384. * implement your ID getting method in the child class.
  385. *
  386. * @return int ID of dataobject
  387. * @throws Exception (when ID is not available or not set yet)
  388. */
  389. public function getID()
  390. {
  391. // FIXME: Make these exceptions more specific (their own classes)
  392. if (!isset($this->id)) {
  393. throw new Exception('No ID set.');
  394. } elseif (empty($this->id)) {
  395. throw new Exception('Empty ID for object! (not inserted yet?).');
  396. }
  397. return intval($this->id);
  398. }
  399. /**
  400. * Check whether the column is NULL in SQL
  401. *
  402. * @param string $key column property name
  403. *
  404. * @return bool
  405. */
  406. public function isNull(string $key): bool
  407. {
  408. if (array_key_exists($key, get_object_vars($this))
  409. && is_null($this->$key)) {
  410. // If there was no fetch, this is a false positive.
  411. return true;
  412. } elseif (is_object($this->$key)
  413. && $this->$key instanceof DB_DataObject_Cast
  414. && $this->$key->type === 'sql') {
  415. // This is cast to raw SQL, let's see if it's NULL.
  416. return (strcasecmp($this->$key->value, 'NULL') == 0);
  417. } elseif (DB_DataObject::_is_null($this, $key)) {
  418. // DataObject's NULL magic should be disabled,
  419. // this is just for completeness.
  420. return true;
  421. }
  422. return false;
  423. }
  424. /**
  425. * WARNING: Only use this on Profile and Notice. We should probably do
  426. * this with traits/"implements" or whatever, but that's over the top
  427. * right now, I'm just throwing this in here to avoid code duplication
  428. * in Profile and Notice classes.
  429. */
  430. public function getAliases()
  431. {
  432. return array_keys($this->getAliasesWithIDs());
  433. }
  434. public function getAliasesWithIDs()
  435. {
  436. $aliases = array();
  437. $aliases[$this->getUri()] = $this->getID();
  438. try {
  439. $aliases[$this->getUrl()] = $this->getID();
  440. } catch (InvalidUrlException $e) {
  441. // getUrl failed because no valid URL could be returned, just ignore it
  442. }
  443. if (common_config('fix', 'fancyurls')) {
  444. /**
  445. * Here we add some hacky hotfixes for remote lookups that have been taught the
  446. * (at least now) wrong URI but it's still obviously the same user. Such as:
  447. * - https://site.example/user/1 even if the client requests https://site.example/index.php/user/1
  448. * - https://site.example/user/1 even if the client requests https://site.example//index.php/user/1
  449. * - https://site.example/index.php/user/1 even if the client requests https://site.example/user/1
  450. * - https://site.example/index.php/user/1 even if the client requests https://site.example///index.php/user/1
  451. */
  452. foreach ($aliases as $alias=>$id) {
  453. try {
  454. // get a "fancy url" version of the alias, even without index.php/
  455. $alt_url = common_fake_local_fancy_url($alias);
  456. // store this as well so remote sites can be sure we really are the same profile
  457. $aliases[$alt_url] = $id;
  458. } catch (Exception $e) {
  459. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  460. }
  461. try {
  462. // get a non-"fancy url" version of the alias, i.e. add index.php/
  463. $alt_url = common_fake_local_nonfancy_url($alias);
  464. // store this as well so remote sites can be sure we really are the same profile
  465. $aliases[$alt_url] = $id;
  466. } catch (Exception $e) {
  467. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  468. }
  469. }
  470. }
  471. return $aliases;
  472. }
  473. /**
  474. * Set the attribute defined as "timestamp" to CURRENT_TIMESTAMP.
  475. * This is hooked in update() and updateWithKeys() to update "modified".
  476. *
  477. * @access private
  478. * @return void
  479. */
  480. private function updateAutoTimestamps(): void
  481. {
  482. $table = static::schemaDef();
  483. foreach ($table['fields'] as $name => $col) {
  484. if ($col['type'] === 'timestamp'
  485. && !array_key_exists('default', $col)
  486. && !isset($this->$name)) {
  487. $this->$name = common_sql_now();
  488. }
  489. }
  490. }
  491. /**
  492. * update() won't write key columns, so we have to do it ourselves.
  493. * This also automatically calls "update" _before_ it sets the keys.
  494. * FIXME: This only works with single-column primary keys so far! Beware!
  495. *
  496. * @param Managed_DataObject $orig Must be "instanceof" $this
  497. * @param string $pid Primary ID column (no escaping is done on column name!)
  498. * @return bool|void
  499. * @throws MethodNotImplementedException
  500. * @throws ServerException
  501. */
  502. public function updateWithKeys(Managed_DataObject $orig, ?string $pid = null)
  503. {
  504. if (!$orig instanceof $this) {
  505. throw new ServerException('Tried updating a DataObject with a different class than itself.');
  506. }
  507. if ($this->N <1) {
  508. throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
  509. }
  510. $this->onUpdateKeys($orig);
  511. // do it in a transaction
  512. $this->query('START TRANSACTION');
  513. // ON UPDATE CURRENT_TIMESTAMP behaviour
  514. // @fixme Should the value be reverted back if transaction failed?
  515. $this->updateAutoTimestamps();
  516. $parts = [];
  517. foreach ($this->keys() as $k) {
  518. $v = $this->table()[$k];
  519. if ($this->$k !== $orig->$k) {
  520. if (is_object($this->$k) && $this->$k instanceof DB_DataObject_Cast) {
  521. $value = $this->$k->toString($v, $this->getDatabaseConnection());
  522. } elseif (DB_DataObject::_is_null($this, $k)) {
  523. $value = 'NULL';
  524. } elseif ($v & DB_DATAOBJECT_STR) { // if a string
  525. $value = $this->_quote((string) $this->$k);
  526. } else {
  527. $value = (int) $this->$k;
  528. }
  529. $parts[] = "{$k} = {$value}";
  530. }
  531. }
  532. if (count($parts) == 0) {
  533. // No changes to keys, it's safe to run ->update(...)
  534. if ($this->update($orig) === false) {
  535. common_log_db_error($this, 'UPDATE', __FILE__);
  536. // rollback as something bad occurred
  537. $this->query('ROLLBACK');
  538. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  539. }
  540. $orig->decache();
  541. $this->encache();
  542. // commit our db transaction since we won't reach the COMMIT below
  543. $this->query('COMMIT');
  544. // @FIXME return true only if something changed (otherwise 0)
  545. return true;
  546. }
  547. if ($pid === null) {
  548. $schema = static::schemaDef();
  549. $pid = $schema['primary key'];
  550. unset($schema);
  551. }
  552. $pidWhere = [];
  553. foreach ((array) $pid as $pidCol) {
  554. $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
  555. }
  556. if (empty($pidWhere)) {
  557. throw new ServerException('No primary ID column(s) set for updateWithKeys');
  558. }
  559. $qry = sprintf(
  560. 'UPDATE %1$s SET %2$s WHERE %3$s',
  561. $this->escapedTableName(),
  562. implode(', ', $parts),
  563. implode(' AND ', $pidWhere)
  564. );
  565. $result = $this->query($qry);
  566. if ($result === false) {
  567. common_log_db_error($this, 'UPDATE', __FILE__);
  568. // rollback as something bad occurred
  569. $this->query('ROLLBACK');
  570. throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
  571. }
  572. // Update non-keys too, if the previous endeavour worked.
  573. // The ->update call uses "$this" values for keys, that's why we can't do this until
  574. // the keys are updated (because they might differ from $orig and update the wrong entries).
  575. if ($this->update($orig) === false) {
  576. common_log_db_error($this, 'UPDATE', __FILE__);
  577. // rollback as something bad occurred
  578. $this->query('ROLLBACK');
  579. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  580. }
  581. $orig->decache();
  582. $this->encache();
  583. // commit our db transaction
  584. $this->query('COMMIT');
  585. // @FIXME return true only if something changed (otherwise 0)
  586. return $result;
  587. }
  588. public static function beforeSchemaUpdate()
  589. {
  590. // NOOP
  591. }
  592. public static function newUri(Profile $actor, Managed_DataObject $object, $created = null)
  593. {
  594. if (is_null($created)) {
  595. $created = common_sql_now();
  596. }
  597. return TagURI::mint(
  598. strtolower(get_called_class()) . ':%d:%s:%d:%s',
  599. $actor->getID(),
  600. ActivityUtils::resolveUri($object->getObjectType(), true),
  601. $object->getID(),
  602. common_date_iso8601($created)
  603. );
  604. }
  605. protected function onInsert()
  606. {
  607. // NOOP by default
  608. }
  609. protected function onUpdate($dataObject=false)
  610. {
  611. // NOOP by default
  612. }
  613. protected function onUpdateKeys(Managed_DataObject $orig)
  614. {
  615. // NOOP by default
  616. }
  617. public function insert()
  618. {
  619. $this->onInsert();
  620. $result = parent::insert();
  621. // Make this object aware of the changed "modified" attribute.
  622. // Sets it approximately to the same value as DEFAULT CURRENT_TIMESTAMP
  623. // just did (@fixme).
  624. if ($result) {
  625. $this->updateAutoTimestamps();
  626. }
  627. return $result;
  628. }
  629. public function update($dataObject = false)
  630. {
  631. $this->onUpdate($dataObject);
  632. // ON UPDATE CURRENT_TIMESTAMP behaviour
  633. // @fixme Should the value be reverted back if transaction failed?
  634. $this->updateAutoTimestamps();
  635. return parent::update($dataObject);
  636. }
  637. }