Managed_DataObject.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. * Check whether the column is NULL in SQL
  402. *
  403. * @param string $key column property name
  404. *
  405. * @return bool
  406. */
  407. public function isNull(string $key): bool
  408. {
  409. if (array_key_exists($key, get_object_vars($this))
  410. && is_null($this->$key)) {
  411. // If there was no fetch, this is a false positive.
  412. return true;
  413. } elseif (is_object($this->$key)
  414. && $this->$key instanceof DB_DataObject_Cast
  415. && $this->$key->type === 'sql') {
  416. // This is cast to raw SQL, let's see if it's NULL.
  417. return (strcasecmp($this->$key->value, 'NULL') == 0);
  418. } elseif (DB_DataObject::_is_null($this, $key)) {
  419. // DataObject's NULL magic should be disabled,
  420. // this is just for completeness.
  421. return true;
  422. }
  423. return false;
  424. }
  425. /**
  426. * WARNING: Only use this on Profile and Notice. We should probably do
  427. * this with traits/"implements" or whatever, but that's over the top
  428. * right now, I'm just throwing this in here to avoid code duplication
  429. * in Profile and Notice classes.
  430. */
  431. public function getAliases()
  432. {
  433. return array_keys($this->getAliasesWithIDs());
  434. }
  435. public function getAliasesWithIDs()
  436. {
  437. $aliases = array();
  438. $aliases[$this->getUri()] = $this->getID();
  439. try {
  440. $aliases[$this->getUrl()] = $this->getID();
  441. } catch (InvalidUrlException $e) {
  442. // getUrl failed because no valid URL could be returned, just ignore it
  443. }
  444. if (common_config('fix', 'fancyurls')) {
  445. /**
  446. * Here we add some hacky hotfixes for remote lookups that have been taught the
  447. * (at least now) wrong URI but it's still obviously the same user. Such as:
  448. * - https://site.example/user/1 even if the client requests https://site.example/index.php/user/1
  449. * - https://site.example/user/1 even if the client requests https://site.example//index.php/user/1
  450. * - https://site.example/index.php/user/1 even if the client requests https://site.example/user/1
  451. * - https://site.example/index.php/user/1 even if the client requests https://site.example///index.php/user/1
  452. */
  453. foreach ($aliases as $alias=>$id) {
  454. try {
  455. // get a "fancy url" version of the alias, even without index.php/
  456. $alt_url = common_fake_local_fancy_url($alias);
  457. // store this as well so remote sites can be sure we really are the same profile
  458. $aliases[$alt_url] = $id;
  459. } catch (Exception $e) {
  460. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  461. }
  462. try {
  463. // get a non-"fancy url" version of the alias, i.e. add index.php/
  464. $alt_url = common_fake_local_nonfancy_url($alias);
  465. // store this as well so remote sites can be sure we really are the same profile
  466. $aliases[$alt_url] = $id;
  467. } catch (Exception $e) {
  468. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  469. }
  470. }
  471. }
  472. return $aliases;
  473. }
  474. /**
  475. * update() won't write key columns, so we have to do it ourselves.
  476. * This also automatically calls "update" _before_ it sets the keys.
  477. * FIXME: This only works with single-column primary keys so far! Beware!
  478. *
  479. * @param Managed_DataObject $orig Must be "instanceof" $this
  480. * @param string $pid Primary ID column (no escaping is done on column name!)
  481. * @return bool|void
  482. * @throws MethodNotImplementedException
  483. * @throws ServerException
  484. */
  485. public function updateWithKeys(Managed_DataObject $orig, ?string $pid = null)
  486. {
  487. if (!$orig instanceof $this) {
  488. throw new ServerException('Tried updating a DataObject with a different class than itself.');
  489. }
  490. if ($this->N <1) {
  491. throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
  492. }
  493. $this->onUpdateKeys($orig);
  494. // do it in a transaction
  495. $this->query('BEGIN');
  496. $parts = [];
  497. foreach ($this->keys() as $k) {
  498. $v = $this->table()[$k];
  499. if ($this->$k !== $orig->$k) {
  500. if (is_object($this->$k) && $this->$k instanceof DB_DataObject_Cast) {
  501. $value = $this->$k->toString($v, $this->getDatabaseConnection());
  502. } elseif (DB_DataObject::_is_null($this, $k)) {
  503. $value = 'NULL';
  504. } elseif ($v & DB_DATAOBJECT_STR) { // if a string
  505. $value = $this->_quote((string) $this->$k);
  506. } else {
  507. $value = (int) $this->$k;
  508. }
  509. $parts[] = "{$k} = {$value}";
  510. }
  511. }
  512. if (count($parts) == 0) {
  513. // No changes to keys, it's safe to run ->update(...)
  514. if ($this->update($orig) === false) {
  515. common_log_db_error($this, 'UPDATE', __FILE__);
  516. // rollback as something bad occurred
  517. $this->query('ROLLBACK');
  518. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  519. }
  520. $orig->decache();
  521. $this->encache();
  522. // commit our db transaction since we won't reach the COMMIT below
  523. $this->query('COMMIT');
  524. // @FIXME return true only if something changed (otherwise 0)
  525. return true;
  526. }
  527. if ($pid === null) {
  528. $schema = static::schemaDef();
  529. $pid = $schema['primary key'];
  530. unset($schema);
  531. }
  532. $pidWhere = [];
  533. foreach ((array) $pid as $pidCol) {
  534. $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
  535. }
  536. if (empty($pidWhere)) {
  537. throw new ServerException('No primary ID column(s) set for updateWithKeys');
  538. }
  539. $qry = sprintf(
  540. 'UPDATE %1$s SET %2$s WHERE %3$s',
  541. $this->escapedTableName(),
  542. implode(', ', $parts),
  543. implode(' AND ', $pidWhere)
  544. );
  545. $result = $this->query($qry);
  546. if ($result === false) {
  547. common_log_db_error($this, 'UPDATE', __FILE__);
  548. // rollback as something bad occurred
  549. $this->query('ROLLBACK');
  550. throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
  551. }
  552. // Update non-keys too, if the previous endeavour worked.
  553. // The ->update call uses "$this" values for keys, that's why we can't do this until
  554. // the keys are updated (because they might differ from $orig and update the wrong entries).
  555. if ($this->update($orig) === false) {
  556. common_log_db_error($this, 'UPDATE', __FILE__);
  557. // rollback as something bad occurred
  558. $this->query('ROLLBACK');
  559. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  560. }
  561. $orig->decache();
  562. $this->encache();
  563. // commit our db transaction
  564. $this->query('COMMIT');
  565. // @FIXME return true only if something changed (otherwise 0)
  566. return $result;
  567. }
  568. public static function beforeSchemaUpdate()
  569. {
  570. // NOOP
  571. }
  572. public static function newUri(Profile $actor, Managed_DataObject $object, $created = null)
  573. {
  574. if (is_null($created)) {
  575. $created = common_sql_now();
  576. }
  577. return TagURI::mint(
  578. strtolower(get_called_class()) . ':%d:%s:%d:%s',
  579. $actor->getID(),
  580. ActivityUtils::resolveUri($object->getObjectType(), true),
  581. $object->getID(),
  582. common_date_iso8601($created)
  583. );
  584. }
  585. protected function onInsert()
  586. {
  587. // NOOP by default
  588. }
  589. protected function onUpdate($dataObject=false)
  590. {
  591. // NOOP by default
  592. }
  593. protected function onUpdateKeys(Managed_DataObject $orig)
  594. {
  595. // NOOP by default
  596. }
  597. public function insert()
  598. {
  599. $this->onInsert();
  600. return parent::insert();
  601. }
  602. public function update($dataObject=false)
  603. {
  604. $this->onUpdate($dataObject);
  605. return parent::update($dataObject);
  606. }
  607. }