Managed_DataObject.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 (empty($id)) {
  349. throw new EmptyIdException(get_called_class());
  350. }
  351. // getByPK throws exception if id is null
  352. // or if the class does not have a single 'id' column as primary key
  353. return static::getByPK(array('id' => $id));
  354. }
  355. /**
  356. * Returns an ID, checked that it is set and reasonably valid
  357. *
  358. * If this dataobject uses a special id field (not 'id'), just
  359. * implement your ID getting method in the child class.
  360. *
  361. * @return int ID of dataobject
  362. * @throws Exception (when ID is not available or not set yet)
  363. */
  364. public function getID()
  365. {
  366. // FIXME: Make these exceptions more specific (their own classes)
  367. if (!isset($this->id)) {
  368. throw new Exception('No ID set.');
  369. } elseif (empty($this->id)) {
  370. throw new Exception('Empty ID for object! (not inserted yet?).');
  371. }
  372. return intval($this->id);
  373. }
  374. /**
  375. * WARNING: Only use this on Profile and Notice. We should probably do
  376. * this with traits/"implements" or whatever, but that's over the top
  377. * right now, I'm just throwing this in here to avoid code duplication
  378. * in Profile and Notice classes.
  379. */
  380. public function getAliases()
  381. {
  382. return array_keys($this->getAliasesWithIDs());
  383. }
  384. public function getAliasesWithIDs()
  385. {
  386. $aliases = array();
  387. $aliases[$this->getUri()] = $this->getID();
  388. try {
  389. $aliases[$this->getUrl()] = $this->getID();
  390. } catch (InvalidUrlException $e) {
  391. // getUrl failed because no valid URL could be returned, just ignore it
  392. }
  393. if (common_config('fix', 'fancyurls')) {
  394. /**
  395. * Here we add some hacky hotfixes for remote lookups that have been taught the
  396. * (at least now) wrong URI but it's still obviously the same user. Such as:
  397. * - https://site.example/user/1 even if the client requests https://site.example/index.php/user/1
  398. * - https://site.example/user/1 even if the client requests https://site.example//index.php/user/1
  399. * - https://site.example/index.php/user/1 even if the client requests https://site.example/user/1
  400. * - https://site.example/index.php/user/1 even if the client requests https://site.example///index.php/user/1
  401. */
  402. foreach ($aliases as $alias=>$id) {
  403. try {
  404. // get a "fancy url" version of the alias, even without index.php/
  405. $alt_url = common_fake_local_fancy_url($alias);
  406. // store this as well so remote sites can be sure we really are the same profile
  407. $aliases[$alt_url] = $id;
  408. } catch (Exception $e) {
  409. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  410. }
  411. try {
  412. // get a non-"fancy url" version of the alias, i.e. add index.php/
  413. $alt_url = common_fake_local_nonfancy_url($alias);
  414. // store this as well so remote sites can be sure we really are the same profile
  415. $aliases[$alt_url] = $id;
  416. } catch (Exception $e) {
  417. // Apparently we couldn't rewrite that, the $alias was as the function wanted it to be
  418. }
  419. }
  420. }
  421. return $aliases;
  422. }
  423. // 'update' won't write key columns, so we have to do it ourselves.
  424. // This also automatically calls "update" _before_ it sets the keys.
  425. // FIXME: This only works with single-column primary keys so far! Beware!
  426. /**
  427. * @param DB_DataObject &$orig Must be "instanceof" $this
  428. * @param string $pid Primary ID column (no escaping is done on column name!)
  429. */
  430. public function updateWithKeys(Managed_DataObject $orig, $pid=null)
  431. {
  432. if (!$orig instanceof $this) {
  433. throw new ServerException('Tried updating a DataObject with a different class than itself.');
  434. }
  435. if ($this->N <1) {
  436. throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
  437. }
  438. // do it in a transaction
  439. $this->query('BEGIN');
  440. $parts = array();
  441. foreach ($this->keys() as $k) {
  442. if (strcmp($this->$k, $orig->$k) != 0) {
  443. $parts[] = $k . ' = ' . $this->_quote($this->$k);
  444. }
  445. }
  446. if (count($parts) == 0) {
  447. // No changes to keys, it's safe to run ->update(...)
  448. if ($this->update($orig) === false) {
  449. common_log_db_error($this, 'UPDATE', __FILE__);
  450. // rollback as something bad occurred
  451. $this->query('ROLLBACK');
  452. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  453. }
  454. $orig->decache();
  455. $this->encache();
  456. // commit our db transaction since we won't reach the COMMIT below
  457. $this->query('COMMIT');
  458. // @FIXME return true only if something changed (otherwise 0)
  459. return true;
  460. }
  461. if ($pid === null) {
  462. $schema = static::schemaDef();
  463. $pid = $schema['primary key'];
  464. unset($schema);
  465. }
  466. $pidWhere = array();
  467. foreach((array)$pid as $pidCol) {
  468. $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
  469. }
  470. if (empty($pidWhere)) {
  471. throw new ServerException('No primary ID column(s) set for updateWithKeys');
  472. }
  473. $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s',
  474. common_database_tablename($this->tableName()),
  475. implode(', ', $parts),
  476. implode(' AND ', $pidWhere));
  477. $result = $this->query($qry);
  478. if ($result === false) {
  479. common_log_db_error($this, 'UPDATE', __FILE__);
  480. // rollback as something bad occurred
  481. $this->query('ROLLBACK');
  482. throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
  483. }
  484. // Update non-keys too, if the previous endeavour worked.
  485. // The ->update call uses "$this" values for keys, that's why we can't do this until
  486. // the keys are updated (because they might differ from $orig and update the wrong entries).
  487. if ($this->update($orig) === false) {
  488. common_log_db_error($this, 'UPDATE', __FILE__);
  489. // rollback as something bad occurred
  490. $this->query('ROLLBACK');
  491. throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
  492. }
  493. $orig->decache();
  494. $this->encache();
  495. // commit our db transaction
  496. $this->query('COMMIT');
  497. // @FIXME return true only if something changed (otherwise 0)
  498. return $result;
  499. }
  500. static public function beforeSchemaUpdate()
  501. {
  502. // NOOP
  503. }
  504. static function newUri(Profile $actor, Managed_DataObject $object, $created=null)
  505. {
  506. if (is_null($created)) {
  507. $created = common_sql_now();
  508. }
  509. return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
  510. $actor->getID(),
  511. ActivityUtils::resolveUri($object->getObjectType(), true),
  512. $object->getID(),
  513. common_date_iso8601($created));
  514. }
  515. protected function onInsert()
  516. {
  517. // NOOP by default
  518. }
  519. protected function onUpdate($dataObject=false)
  520. {
  521. // NOOP by default
  522. }
  523. public function insert()
  524. {
  525. $this->onInsert();
  526. return parent::insert();
  527. }
  528. public function update($dataObject=false)
  529. {
  530. $this->onUpdate($dataObject);
  531. return parent::update($dataObject);
  532. }
  533. }