Managed_DataObject.php 20 KB

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