Managed_DataObject.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. */
  258. public function _allCacheKeys()
  259. {
  260. $table = static::schemaDef();
  261. $ckeys = array();
  262. if (!empty($table['unique keys'])) {
  263. $keyNames = $table['unique keys'];
  264. foreach ($keyNames as $idx => $fields) {
  265. $val = array();
  266. foreach ($fields as $name) {
  267. $val[$name] = self::valueString($this->$name);
  268. }
  269. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  270. }
  271. }
  272. if (!empty($table['primary key'])) {
  273. $fields = $table['primary key'];
  274. $val = array();
  275. foreach ($fields as $name) {
  276. $val[$name] = self::valueString($this->$name);
  277. }
  278. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  279. }
  280. return $ckeys;
  281. }
  282. public function escapedTableName()
  283. {
  284. return common_database_tablename($this->tableName());
  285. }
  286. /**
  287. * Returns an object by looking at the primary key column(s).
  288. *
  289. * Will require all primary key columns to be defined in an associative array
  290. * and ignore any keys which are not part of the primary key.
  291. *
  292. * Will NOT accept NULL values as part of primary key.
  293. *
  294. * @param array $vals Must match all primary key columns for the dataobject.
  295. *
  296. * @return Managed_DataObject of the get_called_class() type
  297. * @throws NoResultException if no object with that primary key
  298. */
  299. public static function getByPK(array $vals)
  300. {
  301. $classname = get_called_class();
  302. $pkey = static::pkeyCols();
  303. if (is_null($pkey)) {
  304. throw new ServerException("Failed to get primary key columns for class '{$classname}'");
  305. }
  306. $object = new $classname();
  307. foreach ($pkey as $col) {
  308. if (!array_key_exists($col, $vals)) {
  309. throw new ServerException("Missing primary key column '{$col}' for ".get_called_class()." among provided keys: ".implode(',', array_keys($vals)));
  310. } elseif (is_null($vals[$col])) {
  311. throw new ServerException("NULL values not allowed in getByPK for column '{$col}'");
  312. }
  313. $object->$col = $vals[$col];
  314. }
  315. if (!$object->find(true)) {
  316. throw new NoResultException($object);
  317. }
  318. return $object;
  319. }
  320. /**
  321. * Returns an object by looking at given unique key columns.
  322. *
  323. * Will NOT accept NULL values for a unique key column. Ignores non-key values.
  324. *
  325. * @param array $vals All array keys which are set must be non-null.
  326. *
  327. * @return Managed_DataObject of the get_called_class() type
  328. * @throws NoResultException if no object with that primary key
  329. */
  330. public static function getByKeys(array $vals)
  331. {
  332. $classname = get_called_class();
  333. $object = new $classname();
  334. $keys = $object->keys();
  335. if (is_null($keys)) {
  336. throw new ServerException("Failed to get key columns for class '{$classname}'");
  337. }
  338. foreach ($keys as $col) {
  339. if (!array_key_exists($col, $vals)) {
  340. continue;
  341. } elseif (is_null($vals[$col])) {
  342. throw new ServerException("NULL values not allowed in getByKeys for column '{$col}'");
  343. }
  344. $object->$col = $vals[$col];
  345. }
  346. if (!$object->find(true)) {
  347. throw new NoResultException($object);
  348. }
  349. return $object;
  350. }
  351. public static function getByID($id)
  352. {
  353. if (!property_exists(get_called_class(), 'id')) {
  354. throw new ServerException('Trying to get undefined property of dataobject class.');
  355. }
  356. if (empty($id)) {
  357. throw new EmptyPkeyValueException(get_called_class(), 'id');
  358. }
  359. // getByPK throws exception if id is null
  360. // or if the class does not have a single 'id' column as primary key
  361. return static::getByPK(array('id' => $id));
  362. }
  363. public static function getByUri($uri)
  364. {
  365. if (!property_exists(get_called_class(), 'uri')) {
  366. throw new ServerException('Trying to get undefined property of dataobject class.');
  367. }
  368. if (empty($uri)) {
  369. throw new EmptyPkeyValueException(get_called_class(), 'uri');
  370. }
  371. $class = get_called_class();
  372. $obj = new $class();
  373. $obj->uri = $uri;
  374. if (!$obj->find(true)) {
  375. throw new NoResultException($obj);
  376. }
  377. return $obj;
  378. }
  379. /**
  380. * Returns an ID, checked that it is set and reasonably valid
  381. *
  382. * If this dataobject uses a special id field (not 'id'), just
  383. * implement your ID getting method in the child class.
  384. *
  385. * @return int ID of dataobject
  386. * @throws Exception (when ID is not available or not set yet)
  387. */
  388. public function getID()
  389. {
  390. // FIXME: Make these exceptions more specific (their own classes)
  391. if (!isset($this->id)) {
  392. throw new Exception('No ID set.');
  393. } elseif (empty($this->id)) {
  394. throw new Exception('Empty ID for object! (not inserted yet?).');
  395. }
  396. return intval($this->id);
  397. }
  398. /**
  399. * WARNING: Only use this on Profile and Notice. We should probably do
  400. * this with traits/"implements" or whatever, but that's over the top
  401. * right now, I'm just throwing this in here to avoid code duplication
  402. * in Profile and Notice classes.
  403. */
  404. public function getAliases()
  405. {
  406. return array_keys($this->getAliasesWithIDs());
  407. }
  408. public function getAliasesWithIDs()
  409. {
  410. $aliases = array();
  411. $aliases[$this->getUri()] = $this->getID();
  412. try {
  413. $aliases[$this->getUrl()] = $this->getID();
  414. } catch (InvalidUrlException $e) {
  415. // getUrl failed because no valid URL could be returned, just ignore it
  416. }
  417. if (common_config('fix', 'fancyurls')) {
  418. /**
  419. * Here we add some hacky hotfixes for remote lookups that have been taught the
  420. * (at least now) wrong URI but it's still obviously the same user. Such as:
  421. * - https://site.example/user/1 even if the client requests https://site.example/index.php/user/1
  422. * - https://site.example/user/1 even if the client requests https://site.example//index.php/user/1
  423. * - https://site.example/index.php/user/1 even if the client requests https://site.example/user/1
  424. * - https://site.example/index.php/user/1 even if the client requests https://site.example///index.php/user/1
  425. */
  426. foreach ($aliases as $alias=>$id) {
  427. try {
  428. // get a "fancy url" version of the alias, even without index.php/
  429. $alt_url = common_fake_local_fancy_url($alias);
  430. // store this as well so remote sites can be sure we really are the same profile
  431. $aliases[$alt_url] = $id;
  432. } catch (Exception $e) {
  433. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  434. }
  435. try {
  436. // get a non-"fancy url" version of the alias, i.e. add index.php/
  437. $alt_url = common_fake_local_nonfancy_url($alias);
  438. // store this as well so remote sites can be sure we really are the same profile
  439. $aliases[$alt_url] = $id;
  440. } catch (Exception $e) {
  441. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  442. }
  443. }
  444. }
  445. return $aliases;
  446. }
  447. // 'update' won't write key columns, so we have to do it ourselves.
  448. // This also automatically calls "update" _before_ it sets the keys.
  449. // FIXME: This only works with single-column primary keys so far! Beware!
  450. /**
  451. * @param DB_DataObject &$orig Must be "instanceof" $this
  452. * @param string $pid Primary ID column (no escaping is done on column name!)
  453. */
  454. public function updateWithKeys(Managed_DataObject $orig, $pid=null)
  455. {
  456. if (!$orig instanceof $this) {
  457. throw new ServerException('Tried updating a DataObject with a different class than itself.');
  458. }
  459. if ($this->N <1) {
  460. throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
  461. }
  462. $this->onUpdateKeys($orig);
  463. // do it in a transaction
  464. $this->query('BEGIN');
  465. $parts = array();
  466. foreach ($this->keys() as $k) {
  467. if (strcmp($this->$k, $orig->$k) != 0) {
  468. $parts[] = $k . ' = ' . $this->_quote($this->$k);
  469. }
  470. }
  471. if (count($parts) == 0) {
  472. // No changes to keys, it's safe to run ->update(...)
  473. if ($this->update($orig) === false) {
  474. common_log_db_error($this, 'UPDATE', __FILE__);
  475. // rollback as something bad occurred
  476. $this->query('ROLLBACK');
  477. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  478. }
  479. $orig->decache();
  480. $this->encache();
  481. // commit our db transaction since we won't reach the COMMIT below
  482. $this->query('COMMIT');
  483. // @FIXME return true only if something changed (otherwise 0)
  484. return true;
  485. }
  486. if ($pid === null) {
  487. $schema = static::schemaDef();
  488. $pid = $schema['primary key'];
  489. unset($schema);
  490. }
  491. $pidWhere = [];
  492. foreach ((array) $pid as $pidCol) {
  493. $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
  494. }
  495. if (empty($pidWhere)) {
  496. throw new ServerException('No primary ID column(s) set for updateWithKeys');
  497. }
  498. $qry = sprintf(
  499. 'UPDATE %1$s SET %2$s WHERE %3$s',
  500. $this->escapedTableName(),
  501. implode(', ', $parts),
  502. implode(' AND ', $pidWhere)
  503. );
  504. $result = $this->query($qry);
  505. if ($result === false) {
  506. common_log_db_error($this, 'UPDATE', __FILE__);
  507. // rollback as something bad occurred
  508. $this->query('ROLLBACK');
  509. throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
  510. }
  511. // Update non-keys too, if the previous endeavour worked.
  512. // The ->update call uses "$this" values for keys, that's why we can't do this until
  513. // the keys are updated (because they might differ from $orig and update the wrong entries).
  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
  523. $this->query('COMMIT');
  524. // @FIXME return true only if something changed (otherwise 0)
  525. return $result;
  526. }
  527. public static function beforeSchemaUpdate()
  528. {
  529. // NOOP
  530. }
  531. public static function newUri(Profile $actor, Managed_DataObject $object, $created = null)
  532. {
  533. if (is_null($created)) {
  534. $created = common_sql_now();
  535. }
  536. return TagURI::mint(
  537. strtolower(get_called_class()) . ':%d:%s:%d:%s',
  538. $actor->getID(),
  539. ActivityUtils::resolveUri($object->getObjectType(), true),
  540. $object->getID(),
  541. common_date_iso8601($created)
  542. );
  543. }
  544. protected function onInsert()
  545. {
  546. // NOOP by default
  547. }
  548. protected function onUpdate($dataObject=false)
  549. {
  550. // NOOP by default
  551. }
  552. protected function onUpdateKeys(Managed_DataObject $orig)
  553. {
  554. // NOOP by default
  555. }
  556. public function insert()
  557. {
  558. $this->onInsert();
  559. return parent::insert();
  560. }
  561. public function update($dataObject=false)
  562. {
  563. $this->onUpdate($dataObject);
  564. return parent::update($dataObject);
  565. }
  566. }