Merge "[MCR] RevisionStore, enable insertions for new schema"
[lhc/web/wiklou.git] / includes / Storage / SlotRecord.php
1 <?php
2 /**
3 * Value object representing a content slot associated with a page revision.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace MediaWiki\Storage;
24
25 use Content;
26 use InvalidArgumentException;
27 use LogicException;
28 use OutOfBoundsException;
29 use Wikimedia\Assert\Assert;
30
31 /**
32 * Value object representing a content slot associated with a page revision.
33 * SlotRecord provides direct access to a Content object.
34 * That access may be implemented through a callback.
35 *
36 * @since 1.31
37 */
38 class SlotRecord {
39
40 /**
41 * @var object database result row, as a raw object. Callbacks are supported for field values,
42 * to enable on-demand emulation of these values. This is primarily intended for use
43 * during schema migration.
44 */
45 private $row;
46
47 /**
48 * @var Content|callable
49 */
50 private $content;
51
52 /**
53 * Returns a new SlotRecord just like the given $slot, except that calling getContent()
54 * will fail with an exception.
55 *
56 * @param SlotRecord $slot
57 *
58 * @return SlotRecord
59 */
60 public static function newWithSuppressedContent( SlotRecord $slot ) {
61 $row = $slot->row;
62
63 return new SlotRecord( $row, function () {
64 throw new SuppressedDataException( 'Content suppressed!' );
65 } );
66 }
67
68 /**
69 * Constructs a new SlotRecord from an existing SlotRecord, overriding some fields.
70 * The slot's content cannot be overwritten.
71 *
72 * @param SlotRecord $slot
73 * @param array $overrides
74 *
75 * @return SlotRecord
76 */
77 private static function newDerived( SlotRecord $slot, array $overrides = [] ) {
78 $row = clone $slot->row;
79 $row->slot_id = null; // never copy the row ID!
80
81 foreach ( $overrides as $key => $value ) {
82 $row->$key = $value;
83 }
84
85 return new SlotRecord( $row, $slot->content );
86 }
87
88 /**
89 * Constructs a new SlotRecord for a new revision, inheriting the content of the given SlotRecord
90 * of a previous revision.
91 *
92 * Note that a SlotRecord constructed this way are intended as prototypes,
93 * to be used wit newSaved(). They are incomplete, so some getters such as
94 * getRevision() will fail.
95 *
96 * @param SlotRecord $slot
97 *
98 * @return SlotRecord
99 */
100 public static function newInherited( SlotRecord $slot ) {
101 // Sanity check - we can't inherit from a Slot that's not attached to a revision.
102 $slot->getRevision();
103 $slot->getOrigin();
104 $slot->getAddress();
105
106 // NOTE: slot_origin and content_address are copied from $slot.
107 return self::newDerived( $slot, [
108 'slot_revision_id' => null,
109 ] );
110 }
111
112 /**
113 * Constructs a new Slot from a Content object for a new revision.
114 * This is the preferred way to construct a slot for storing Content that
115 * resulted from a user edit. The slot is assumed to be not inherited.
116 *
117 * Note that a SlotRecord constructed this way are intended as prototypes,
118 * to be used wit newSaved(). They are incomplete, so some getters such as
119 * getAddress() will fail.
120 *
121 * @param string $role
122 * @param Content $content
123 *
124 * @return SlotRecord An incomplete proto-slot object, to be used with newSaved() later.
125 */
126 public static function newUnsaved( $role, Content $content ) {
127 Assert::parameterType( 'string', $role, '$role' );
128
129 $row = [
130 'slot_id' => null, // not yet known
131 'slot_revision_id' => null, // not yet known
132 'slot_origin' => null, // not yet known, will be set in newSaved()
133 'content_size' => null, // compute later
134 'content_sha1' => null, // compute later
135 'slot_content_id' => null, // not yet known, will be set in newSaved()
136 'content_address' => null, // not yet known, will be set in newSaved()
137 'role_name' => $role,
138 'model_name' => $content->getModel(),
139 ];
140
141 return new SlotRecord( (object)$row, $content );
142 }
143
144 /**
145 * Constructs a complete SlotRecord for a newly saved revision, based on the incomplete
146 * proto-slot. This adds information that has only become available during saving,
147 * particularly the revision ID, content ID and content address.
148 *
149 * @param int $revisionId the revision the slot is to be associated with (field slot_revision_id).
150 * If $protoSlot already has a revision, it must be the same.
151 * @param int|null $contentId the ID of the row in the content table describing the content
152 * referenced by $contentAddress (field slot_content_id).
153 * If $protoSlot already has a content ID, it must be the same.
154 * @param string $contentAddress the slot's content address (field content_address).
155 * If $protoSlot already has an address, it must be the same.
156 * @param SlotRecord $protoSlot The proto-slot that was provided as input for creating a new
157 * revision. $protoSlot must have a content address if inherited.
158 *
159 * @return SlotRecord If the state of $protoSlot is inappropriate for saving a new revision.
160 */
161 public static function newSaved(
162 $revisionId,
163 $contentId,
164 $contentAddress,
165 SlotRecord $protoSlot
166 ) {
167 Assert::parameterType( 'integer', $revisionId, '$revisionId' );
168 // TODO once migration is over $contentId must be an integer
169 Assert::parameterType( 'integer|null', $contentId, '$contentId' );
170 Assert::parameterType( 'string', $contentAddress, '$contentAddress' );
171
172 if ( $protoSlot->hasRevision() && $protoSlot->getRevision() !== $revisionId ) {
173 throw new LogicException(
174 "Mismatching revision ID $revisionId: "
175 . "The slot already belongs to revision {$protoSlot->getRevision()}. "
176 . "Use SlotRecord::newInherited() to re-use content between revisions."
177 );
178 }
179
180 if ( $protoSlot->hasAddress() && $protoSlot->getAddress() !== $contentAddress ) {
181 throw new LogicException(
182 "Mismatching blob address $contentAddress: "
183 . "The slot already has content at {$protoSlot->getAddress()}."
184 );
185 }
186
187 if ( $protoSlot->hasContentId() && $protoSlot->getContentId() !== $contentId ) {
188 throw new LogicException(
189 "Mismatching content ID $contentId: "
190 . "The slot already has content row {$protoSlot->getContentId()} associated."
191 );
192 }
193
194 if ( $protoSlot->isInherited() ) {
195 if ( !$protoSlot->hasAddress() ) {
196 throw new InvalidArgumentException(
197 "An inherited blob should have a content address!"
198 );
199 }
200 if ( !$protoSlot->hasField( 'slot_origin' ) ) {
201 throw new InvalidArgumentException(
202 "A saved inherited slot should have an origin set!"
203 );
204 }
205 $origin = $protoSlot->getOrigin();
206 } else {
207 $origin = $revisionId;
208 }
209
210 return self::newDerived( $protoSlot, [
211 'slot_revision_id' => $revisionId,
212 'slot_content_id' => $contentId,
213 'slot_origin' => $origin,
214 'content_address' => $contentAddress,
215 ] );
216 }
217
218 /**
219 * SlotRecord constructor.
220 *
221 * The following fields are supported by the $row parameter:
222 *
223 * $row->blob_data
224 * $row->blob_address
225 *
226 * @param object $row A database row composed of fields of the slot and content tables,
227 * as a raw object. Any field value can be a callback that produces the field value
228 * given this SlotRecord as a parameter. However, plain strings cannot be used as
229 * callbacks here, for security reasons.
230 * @param Content|callable $content The content object associated with the slot, or a
231 * callback that will return that Content object, given this SlotRecord as a parameter.
232 */
233 public function __construct( $row, $content ) {
234 Assert::parameterType( 'object', $row, '$row' );
235 Assert::parameterType( 'Content|callable', $content, '$content' );
236
237 Assert::parameter(
238 property_exists( $row, 'slot_id' ),
239 '$row->slot_id',
240 'must exist'
241 );
242 Assert::parameter(
243 property_exists( $row, 'slot_revision_id' ),
244 '$row->slot_revision_id',
245 'must exist'
246 );
247 Assert::parameter(
248 property_exists( $row, 'slot_content_id' ),
249 '$row->slot_content_id',
250 'must exist'
251 );
252 Assert::parameter(
253 property_exists( $row, 'content_address' ),
254 '$row->content_address',
255 'must exist'
256 );
257 Assert::parameter(
258 property_exists( $row, 'model_name' ),
259 '$row->model_name',
260 'must exist'
261 );
262 Assert::parameter(
263 property_exists( $row, 'slot_origin' ),
264 '$row->slot_origin',
265 'must exist'
266 );
267 Assert::parameter(
268 !property_exists( $row, 'slot_inherited' ),
269 '$row->slot_inherited',
270 'must not exist'
271 );
272 Assert::parameter(
273 !property_exists( $row, 'slot_revision' ),
274 '$row->slot_revision',
275 'must not exist'
276 );
277
278 $this->row = $row;
279 $this->content = $content;
280 }
281
282 /**
283 * Implemented to defy serialization.
284 *
285 * @throws LogicException always
286 */
287 public function __sleep() {
288 throw new LogicException( __CLASS__ . ' is not serializable.' );
289 }
290
291 /**
292 * Returns the Content of the given slot.
293 *
294 * @note This is free to load Content from whatever subsystem is necessary,
295 * performing potentially expensive operations and triggering I/O-related
296 * failure modes.
297 *
298 * @note This method does not apply audience filtering.
299 *
300 * @throws SuppressedDataException if access to the content is not allowed according
301 * to the audience check performed by RevisionRecord::getSlot().
302 *
303 * @return Content The slot's content. This is a direct reference to the internal instance,
304 * copy before exposing to application logic!
305 */
306 public function getContent() {
307 if ( $this->content instanceof Content ) {
308 return $this->content;
309 }
310
311 $obj = call_user_func( $this->content, $this );
312
313 Assert::postcondition(
314 $obj instanceof Content,
315 'Slot content callback should return a Content object'
316 );
317
318 $this->content = $obj;
319
320 return $this->content;
321 }
322
323 /**
324 * Returns the string value of a data field from the database row supplied to the constructor.
325 * If the field was set to a callback, that callback is invoked and the result returned.
326 *
327 * @param string $name
328 *
329 * @throws OutOfBoundsException
330 * @throws IncompleteRevisionException
331 * @return mixed Returns the field's value, never null.
332 */
333 private function getField( $name ) {
334 if ( !isset( $this->row->$name ) ) {
335 // distinguish between unknown and uninitialized fields
336 if ( property_exists( $this->row, $name ) ) {
337 throw new IncompleteRevisionException( 'Uninitialized field: ' . $name );
338 } else {
339 throw new OutOfBoundsException( 'No such field: ' . $name );
340 }
341 }
342
343 $value = $this->row->$name;
344
345 // NOTE: allow callbacks, but don't trust plain string callables from the database!
346 if ( !is_string( $value ) && is_callable( $value ) ) {
347 $value = call_user_func( $value, $this );
348 $this->setField( $name, $value );
349 }
350
351 return $value;
352 }
353
354 /**
355 * Returns the string value of a data field from the database row supplied to the constructor.
356 *
357 * @param string $name
358 *
359 * @throws OutOfBoundsException
360 * @throws IncompleteRevisionException
361 * @return string Returns the string value
362 */
363 private function getStringField( $name ) {
364 return strval( $this->getField( $name ) );
365 }
366
367 /**
368 * Returns the int value of a data field from the database row supplied to the constructor.
369 *
370 * @param string $name
371 *
372 * @throws OutOfBoundsException
373 * @throws IncompleteRevisionException
374 * @return int Returns the int value
375 */
376 private function getIntField( $name ) {
377 return intval( $this->getField( $name ) );
378 }
379
380 /**
381 * @param string $name
382 * @return bool whether this record contains the given field
383 */
384 private function hasField( $name ) {
385 if ( isset( $this->row->$name ) ) {
386 // if the field is a callback, resolve first, then re-check
387 if ( !is_string( $this->row->$name ) && is_callable( $this->row->$name ) ) {
388 $this->getField( $name );
389 }
390 }
391
392 return isset( $this->row->$name );
393 }
394
395 /**
396 * Returns the ID of the revision this slot is associated with.
397 *
398 * @return int
399 */
400 public function getRevision() {
401 return $this->getIntField( 'slot_revision_id' );
402 }
403
404 /**
405 * Returns the revision ID of the revision that originated the slot's content.
406 *
407 * @return int
408 */
409 public function getOrigin() {
410 return $this->getIntField( 'slot_origin' );
411 }
412
413 /**
414 * Whether this slot was inherited from an older revision.
415 *
416 * If this SlotRecord is already attached to a revision, this returns true
417 * if the slot's revision of origin is the same as the revision it belongs to.
418 *
419 * If this SlotRecord is not yet attached to a revision, this returns true
420 * if the slot already has an address.
421 *
422 * @return bool
423 */
424 public function isInherited() {
425 if ( $this->hasRevision() ) {
426 return $this->getRevision() !== $this->getOrigin();
427 } else {
428 return $this->hasAddress();
429 }
430 }
431
432 /**
433 * Whether this slot has an address. Slots will have an address if their
434 * content has been stored. While building a new revision,
435 * SlotRecords will not have an address associated.
436 *
437 * @return bool
438 */
439 public function hasAddress() {
440 return $this->hasField( 'content_address' );
441 }
442
443 /**
444 * Whether this slot has an origin (revision ID that originated the slot's content.
445 *
446 * @since 1.32
447 *
448 * @return bool
449 */
450 public function hasOrigin() {
451 return $this->hasField( 'slot_origin' );
452 }
453
454 /**
455 * Whether this slot has a content ID. Slots will have a content ID if their
456 * content has been stored in the content table. While building a new revision,
457 * SlotRecords will not have an ID associated.
458 *
459 * @since 1.32
460 *
461 * @return bool
462 */
463 public function hasContentId() {
464 return $this->hasField( 'slot_content_id' );
465 }
466
467 /**
468 * Whether this slot has revision ID associated. Slots will have a revision ID associated
469 * only if they were loaded as part of an existing revision. While building a new revision,
470 * Slotrecords will not have a revision ID associated.
471 *
472 * @return bool
473 */
474 public function hasRevision() {
475 return $this->hasField( 'slot_revision_id' );
476 }
477
478 /**
479 * Returns the role of the slot.
480 *
481 * @return string
482 */
483 public function getRole() {
484 return $this->getStringField( 'role_name' );
485 }
486
487 /**
488 * Returns the address of this slot's content.
489 * This address can be used with BlobStore to load the Content object.
490 *
491 * @return string
492 */
493 public function getAddress() {
494 return $this->getStringField( 'content_address' );
495 }
496
497 /**
498 * Returns the ID of the content meta data row associated with the slot.
499 * This information should be irrelevant to application logic, it is here to allow
500 * the construction of a full row for the revision table.
501 *
502 * @return int
503 */
504 public function getContentId() {
505 return $this->getIntField( 'slot_content_id' );
506 }
507
508 /**
509 * Returns the content size
510 *
511 * @return int size of the content, in bogo-bytes, as reported by Content::getSize.
512 */
513 public function getSize() {
514 try {
515 $size = $this->getIntField( 'content_size' );
516 } catch ( IncompleteRevisionException $ex ) {
517 $size = $this->getContent()->getSize();
518 $this->setField( 'content_size', $size );
519 }
520
521 return $size;
522 }
523
524 /**
525 * Returns the content size
526 *
527 * @return string hash of the content.
528 */
529 public function getSha1() {
530 try {
531 $sha1 = $this->getStringField( 'content_sha1' );
532 } catch ( IncompleteRevisionException $ex ) {
533 $format = $this->hasField( 'format_name' )
534 ? $this->getStringField( 'format_name' )
535 : null;
536
537 $data = $this->getContent()->serialize( $format );
538 $sha1 = self::base36Sha1( $data );
539 $this->setField( 'content_sha1', $sha1 );
540 }
541
542 return $sha1;
543 }
544
545 /**
546 * Returns the content model. This is the model name that decides
547 * which ContentHandler is appropriate for interpreting the
548 * data of the blob referenced by the address returned by getAddress().
549 *
550 * @return string the content model of the content
551 */
552 public function getModel() {
553 try {
554 $model = $this->getStringField( 'model_name' );
555 } catch ( IncompleteRevisionException $ex ) {
556 $model = $this->getContent()->getModel();
557 $this->setField( 'model_name', $model );
558 }
559
560 return $model;
561 }
562
563 /**
564 * Returns the blob serialization format as a MIME type.
565 *
566 * @note When this method returns null, the caller is expected
567 * to auto-detect the serialization format, or to rely on
568 * the default format associated with the content model.
569 *
570 * @return string|null
571 */
572 public function getFormat() {
573 // XXX: we currently do not plan to store the format for each slot!
574
575 if ( $this->hasField( 'format_name' ) ) {
576 return $this->getStringField( 'format_name' );
577 }
578
579 return null;
580 }
581
582 /**
583 * @param string $name
584 * @param string|int|null $value
585 */
586 private function setField( $name, $value ) {
587 $this->row->$name = $value;
588 }
589
590 /**
591 * Get the base 36 SHA-1 value for a string of text
592 *
593 * MCR migration note: this replaces Revision::base36Sha1
594 *
595 * @param string $blob
596 * @return string
597 */
598 public static function base36Sha1( $blob ) {
599 return \Wikimedia\base_convert( sha1( $blob ), 16, 36, 31 );
600 }
601
602 /**
603 * Returns true if $other has the same content as this slot.
604 * The check is performed based on the model, address size, and hash.
605 * Two slots can have the same content if they use different content addresses,
606 * but if they have the same address and the same model, they have the same content.
607 * Two slots can have the same content if they belong to different
608 * revisions or pages.
609 *
610 * Note that hasSameContent() may return false even if Content::equals returns true for
611 * the content of two slots. This may happen if the two slots have different serializations
612 * representing equivalent Content. Such false negatives are considered acceptable. Code
613 * that has to be absolutely sure the Content is really not the same if hasSameContent()
614 * returns false should call getContent() and compare the Content objects directly.
615 *
616 * @since 1.32
617 *
618 * @param SlotRecord $other
619 * @return bool
620 */
621 public function hasSameContent( SlotRecord $other ) {
622 if ( $other === $this ) {
623 return true;
624 }
625
626 if ( $this->getModel() !== $other->getModel() ) {
627 return false;
628 }
629
630 if ( $this->hasAddress()
631 && $other->hasAddress()
632 && $this->getAddress() == $other->getAddress()
633 ) {
634 return true;
635 }
636
637 if ( $this->getSize() !== $other->getSize() ) {
638 return false;
639 }
640
641 if ( $this->getSha1() !== $other->getSha1() ) {
642 return false;
643 }
644
645 return true;
646 }
647
648 }