added optional $db param to newFromId( $id, $db = null )
[lhc/web/wiklou.git] / includes / Revision.php
1 <?php
2 /**
3 * @package MediaWiki
4 * @todo document
5 */
6
7 /** */
8 require_once( 'Database.php' );
9
10 /**
11 * @package MediaWiki
12 * @todo document
13 */
14 class Revision {
15 const DELETED_TEXT = 1;
16 const DELETED_COMMENT = 2;
17 const DELETED_USER = 4;
18 const DELETED_RESTRICTED = 8;
19
20 /**
21 * Load a page revision from a given revision ID number.
22 * Returns null if no such revision can be found.
23 *
24 * @param int $id
25 * @param Database $db
26 * @access public
27 * @static
28 */
29 public static function newFromId( $id, $db = null ) {
30 $conditions = array( 'page_id=rev_page', 'rev_id' => intval( $id ));
31 if (is_null($db))
32 return Revision::newFromConds( $conditions );
33 else
34 return Revision::loadFromConds( $db, $conditions );
35 }
36
37 /**
38 * Load either the current, or a specified, revision
39 * that's attached to a given title. If not attached
40 * to that title, will return null.
41 *
42 * @param Title $title
43 * @param int $id
44 * @return Revision
45 * @access public
46 * @static
47 */
48 public static function newFromTitle( &$title, $id = 0 ) {
49 if( $id ) {
50 $matchId = intval( $id );
51 } else {
52 $matchId = 'page_latest';
53 }
54 return Revision::newFromConds(
55 array( "rev_id=$matchId",
56 'page_id=rev_page',
57 'page_namespace' => $title->getNamespace(),
58 'page_title' => $title->getDbkey() ) );
59 }
60
61 /**
62 * Load either the current, or a specified, revision
63 * that's attached to a given page. If not attached
64 * to that page, will return null.
65 *
66 * @param Database $db
67 * @param int $pageid
68 * @param int $id
69 * @return Revision
70 * @access public
71 * @static
72 */
73 public static function loadFromPageId( &$db, $pageid, $id = 0 ) {
74 $conds=array('page_id=rev_page','rev_page'=>intval( $pageid ), 'page_id'=>intval( $pageid ));
75 if( $id ) {
76 $conds['rev_id']=intval($id);
77 } else {
78 $conds[]='rev_id=page_latest';
79 }
80 return Revision::loadFromConds( $db, $conds );
81 }
82
83 /**
84 * Load either the current, or a specified, revision
85 * that's attached to a given page. If not attached
86 * to that page, will return null.
87 *
88 * @param Database $db
89 * @param Title $title
90 * @param int $id
91 * @return Revision
92 * @access public
93 * @static
94 */
95 public static function loadFromTitle( &$db, $title, $id = 0 ) {
96 if( $id ) {
97 $matchId = intval( $id );
98 } else {
99 $matchId = 'page_latest';
100 }
101 return Revision::loadFromConds(
102 $db,
103 array( "rev_id=$matchId",
104 'page_id=rev_page',
105 'page_namespace' => $title->getNamespace(),
106 'page_title' => $title->getDbkey() ) );
107 }
108
109 /**
110 * Load the revision for the given title with the given timestamp.
111 * WARNING: Timestamps may in some circumstances not be unique,
112 * so this isn't the best key to use.
113 *
114 * @param Database $db
115 * @param Title $title
116 * @param string $timestamp
117 * @return Revision
118 * @access public
119 * @static
120 */
121 public static function loadFromTimestamp( &$db, &$title, $timestamp ) {
122 return Revision::loadFromConds(
123 $db,
124 array( 'rev_timestamp' => $db->timestamp( $timestamp ),
125 'page_id=rev_page',
126 'page_namespace' => $title->getNamespace(),
127 'page_title' => $title->getDbkey() ) );
128 }
129
130 /**
131 * Given a set of conditions, fetch a revision.
132 *
133 * @param array $conditions
134 * @return Revision
135 * @access private
136 * @static
137 */
138 private static function newFromConds( $conditions ) {
139 $db =& wfGetDB( DB_SLAVE );
140 $row = Revision::loadFromConds( $db, $conditions );
141 if( is_null( $row ) ) {
142 $dbw =& wfGetDB( DB_MASTER );
143 $row = Revision::loadFromConds( $dbw, $conditions );
144 }
145 return $row;
146 }
147
148 /**
149 * Given a set of conditions, fetch a revision from
150 * the given database connection.
151 *
152 * @param Database $db
153 * @param array $conditions
154 * @return Revision
155 * @access private
156 * @static
157 */
158 private static function loadFromConds( &$db, $conditions ) {
159 $res = Revision::fetchFromConds( $db, $conditions );
160 if( $res ) {
161 $row = $res->fetchObject();
162 $res->free();
163 if( $row ) {
164 $ret = new Revision( $row );
165 return $ret;
166 }
167 }
168 $ret = null;
169 return $ret;
170 }
171
172 /**
173 * Return a wrapper for a series of database rows to
174 * fetch all of a given page's revisions in turn.
175 * Each row can be fed to the constructor to get objects.
176 *
177 * @param Title $title
178 * @return ResultWrapper
179 * @access public
180 * @static
181 */
182 public static function fetchAllRevisions( &$title ) {
183 return Revision::fetchFromConds(
184 wfGetDB( DB_SLAVE ),
185 array( 'page_namespace' => $title->getNamespace(),
186 'page_title' => $title->getDbkey(),
187 'page_id=rev_page' ) );
188 }
189
190 /**
191 * Return a wrapper for a series of database rows to
192 * fetch all of a given page's revisions in turn.
193 * Each row can be fed to the constructor to get objects.
194 *
195 * @param Title $title
196 * @return ResultWrapper
197 * @access public
198 * @static
199 */
200 public static function fetchRevision( &$title ) {
201 return Revision::fetchFromConds(
202 wfGetDB( DB_SLAVE ),
203 array( 'rev_id=page_latest',
204 'page_namespace' => $title->getNamespace(),
205 'page_title' => $title->getDbkey(),
206 'page_id=rev_page' ) );
207 }
208
209 /**
210 * Given a set of conditions, return a ResultWrapper
211 * which will return matching database rows with the
212 * fields necessary to build Revision objects.
213 *
214 * @param Database $db
215 * @param array $conditions
216 * @return ResultWrapper
217 * @access private
218 * @static
219 */
220 private static function fetchFromConds( &$db, $conditions ) {
221 $res = $db->select(
222 array( 'page', 'revision' ),
223 array( 'page_namespace',
224 'page_title',
225 'page_latest',
226 'rev_id',
227 'rev_page',
228 'rev_text_id',
229 'rev_comment',
230 'rev_user_text',
231 'rev_user',
232 'rev_minor_edit',
233 'rev_timestamp',
234 'rev_deleted' ),
235 $conditions,
236 'Revision::fetchRow',
237 array( 'LIMIT' => 1 ) );
238 $ret = $db->resultObject( $res );
239 return $ret;
240 }
241
242 /**
243 * @param object $row
244 * @access private
245 */
246 function Revision( $row ) {
247 if( is_object( $row ) ) {
248 $this->mId = intval( $row->rev_id );
249 $this->mPage = intval( $row->rev_page );
250 $this->mTextId = intval( $row->rev_text_id );
251 $this->mComment = $row->rev_comment;
252 $this->mUserText = $row->rev_user_text;
253 $this->mUser = intval( $row->rev_user );
254 $this->mMinorEdit = intval( $row->rev_minor_edit );
255 $this->mTimestamp = $row->rev_timestamp;
256 $this->mDeleted = intval( $row->rev_deleted );
257
258 if( isset( $row->page_latest ) ) {
259 $this->mCurrent = ( $row->rev_id == $row->page_latest );
260 $this->mTitle = Title::makeTitle( $row->page_namespace,
261 $row->page_title );
262 } else {
263 $this->mCurrent = false;
264 $this->mTitle = null;
265 }
266
267 // Lazy extraction...
268 $this->mText = null;
269 if( isset( $row->old_text ) ) {
270 $this->mTextRow = $row;
271 } else {
272 // 'text' table row entry will be lazy-loaded
273 $this->mTextRow = null;
274 }
275 } elseif( is_array( $row ) ) {
276 // Build a new revision to be saved...
277 global $wgUser;
278
279 $this->mId = isset( $row['id'] ) ? intval( $row['id'] ) : null;
280 $this->mPage = isset( $row['page'] ) ? intval( $row['page'] ) : null;
281 $this->mTextId = isset( $row['text_id'] ) ? intval( $row['text_id'] ) : null;
282 $this->mUserText = isset( $row['user_text'] ) ? strval( $row['user_text'] ) : $wgUser->getName();
283 $this->mUser = isset( $row['user'] ) ? intval( $row['user'] ) : $wgUser->getId();
284 $this->mMinorEdit = isset( $row['minor_edit'] ) ? intval( $row['minor_edit'] ) : 0;
285 $this->mTimestamp = isset( $row['timestamp'] ) ? strval( $row['timestamp'] ) : wfTimestamp( TS_MW );
286 $this->mDeleted = isset( $row['deleted'] ) ? intval( $row['deleted'] ) : 0;
287
288 // Enforce spacing trimming on supplied text
289 $this->mComment = isset( $row['comment'] ) ? trim( strval( $row['comment'] ) ) : null;
290 $this->mText = isset( $row['text'] ) ? rtrim( strval( $row['text'] ) ) : null;
291
292 $this->mTitle = null; # Load on demand if needed
293 $this->mCurrent = false;
294 } else {
295 throw new MWException( 'Revision constructor passed invalid row format.' );
296 }
297 }
298
299 /**#@+
300 * @access public
301 */
302
303 /**
304 * @return int
305 */
306 function getId() {
307 return $this->mId;
308 }
309
310 /**
311 * @return int
312 */
313 function getTextId() {
314 return $this->mTextId;
315 }
316
317 /**
318 * Returns the title of the page associated with this entry.
319 * @return Title
320 */
321 function getTitle() {
322 if( isset( $this->mTitle ) ) {
323 return $this->mTitle;
324 }
325 $dbr =& wfGetDB( DB_SLAVE );
326 $row = $dbr->selectRow(
327 array( 'page', 'revision' ),
328 array( 'page_namespace', 'page_title' ),
329 array( 'page_id=rev_page',
330 'rev_id' => $this->mId ),
331 'Revision::getTitle' );
332 if( $row ) {
333 $this->mTitle = Title::makeTitle( $row->page_namespace,
334 $row->page_title );
335 }
336 return $this->mTitle;
337 }
338
339 /**
340 * Set the title of the revision
341 * @param Title $title
342 */
343 function setTitle( $title ) {
344 $this->mTitle = $title;
345 }
346
347 /**
348 * @return int
349 */
350 function getPage() {
351 return $this->mPage;
352 }
353
354 /**
355 * Fetch revision's user id if it's available to all users
356 * @return int
357 */
358 function getUser() {
359 if( $this->isDeleted( self::DELETED_USER ) ) {
360 return 0;
361 } else {
362 return $this->mUser;
363 }
364 }
365
366 /**
367 * Fetch revision's user id without regard for the current user's permissions
368 * @return string
369 */
370 function getRawUser() {
371 return $this->mUser;
372 }
373
374 /**
375 * Fetch revision's username if it's available to all users
376 * @return string
377 */
378 function getUserText() {
379 if( $this->isDeleted( self::DELETED_USER ) ) {
380 return "";
381 } else {
382 return $this->mUserText;
383 }
384 }
385
386 /**
387 * Fetch revision's username without regard for view restrictions
388 * @return string
389 */
390 function getRawUserText() {
391 return $this->mUserText;
392 }
393
394 /**
395 * Fetch revision comment if it's available to all users
396 * @return string
397 */
398 function getComment() {
399 if( $this->isDeleted( self::DELETED_COMMENT ) ) {
400 return "";
401 } else {
402 return $this->mComment;
403 }
404 }
405
406 /**
407 * Fetch revision comment without regard for the current user's permissions
408 * @return string
409 */
410 function getRawComment() {
411 return $this->mComment;
412 }
413
414 /**
415 * @return bool
416 */
417 function isMinor() {
418 return (bool)$this->mMinorEdit;
419 }
420
421 /**
422 * int $field one of DELETED_* bitfield constants
423 * @return bool
424 */
425 function isDeleted( $field ) {
426 return ($this->mDeleted & $field) == $field;
427 }
428
429 /**
430 * Fetch revision text if it's available to all users
431 * @return string
432 */
433 function getText() {
434 if( $this->isDeleted( self::DELETED_TEXT ) ) {
435 return "";
436 } else {
437 return $this->getRawText();
438 }
439 }
440
441 /**
442 * Fetch revision text without regard for view restrictions
443 * @return string
444 */
445 function getRawText() {
446 if( is_null( $this->mText ) ) {
447 // Revision text is immutable. Load on demand:
448 $this->mText = $this->loadText();
449 }
450 return $this->mText;
451 }
452
453 /**
454 * @return string
455 */
456 function getTimestamp() {
457 return wfTimestamp(TS_MW, $this->mTimestamp);
458 }
459
460 /**
461 * @return bool
462 */
463 function isCurrent() {
464 return $this->mCurrent;
465 }
466
467 /**
468 * @return Revision
469 */
470 function getPrevious() {
471 $prev = $this->mTitle->getPreviousRevisionID( $this->mId );
472 if ( $prev ) {
473 return Revision::newFromTitle( $this->mTitle, $prev );
474 } else {
475 return null;
476 }
477 }
478
479 /**
480 * @return Revision
481 */
482 function getNext() {
483 $next = $this->mTitle->getNextRevisionID( $this->mId );
484 if ( $next ) {
485 return Revision::newFromTitle( $this->mTitle, $next );
486 } else {
487 return null;
488 }
489 }
490 /**#@-*/
491
492 /**
493 * Get revision text associated with an old or archive row
494 * $row is usually an object from wfFetchRow(), both the flags and the text
495 * field must be included
496 * @static
497 * @param integer $row Id of a row
498 * @param string $prefix table prefix (default 'old_')
499 * @return string $text|false the text requested
500 */
501 function getRevisionText( $row, $prefix = 'old_' ) {
502 $fname = 'Revision::getRevisionText';
503 wfProfileIn( $fname );
504
505 # Get data
506 $textField = $prefix . 'text';
507 $flagsField = $prefix . 'flags';
508
509 if( isset( $row->$flagsField ) ) {
510 $flags = explode( ',', $row->$flagsField );
511 } else {
512 $flags = array();
513 }
514
515 if( isset( $row->$textField ) ) {
516 $text = $row->$textField;
517 } else {
518 wfProfileOut( $fname );
519 return false;
520 }
521
522 # Use external methods for external objects, text in table is URL-only then
523 if ( in_array( 'external', $flags ) ) {
524 $url=$text;
525 @list($proto,$path)=explode('://',$url,2);
526 if ($path=="") {
527 wfProfileOut( $fname );
528 return false;
529 }
530 require_once('ExternalStore.php');
531 $text=ExternalStore::fetchFromURL($url);
532 }
533
534 // If the text was fetched without an error, convert it
535 if ( $text !== false ) {
536 if( in_array( 'gzip', $flags ) ) {
537 # Deal with optional compression of archived pages.
538 # This can be done periodically via maintenance/compressOld.php, and
539 # as pages are saved if $wgCompressRevisions is set.
540 $text = gzinflate( $text );
541 }
542
543 if( in_array( 'object', $flags ) ) {
544 # Generic compressed storage
545 $obj = unserialize( $text );
546 if ( !is_object( $obj ) ) {
547 // Invalid object
548 wfProfileOut( $fname );
549 return false;
550 }
551 $text = $obj->getText();
552 }
553
554 global $wgLegacyEncoding;
555 if( $wgLegacyEncoding && !in_array( 'utf-8', $flags ) ) {
556 # Old revisions kept around in a legacy encoding?
557 # Upconvert on demand.
558 global $wgInputEncoding, $wgContLang;
559 $text = $wgContLang->iconv( $wgLegacyEncoding, $wgInputEncoding . '//IGNORE', $text );
560 }
561 }
562 wfProfileOut( $fname );
563 return $text;
564 }
565
566 /**
567 * If $wgCompressRevisions is enabled, we will compress data.
568 * The input string is modified in place.
569 * Return value is the flags field: contains 'gzip' if the
570 * data is compressed, and 'utf-8' if we're saving in UTF-8
571 * mode.
572 *
573 * @static
574 * @param mixed $text reference to a text
575 * @return string
576 */
577 function compressRevisionText( &$text ) {
578 global $wgCompressRevisions;
579 $flags = array();
580
581 # Revisions not marked this way will be converted
582 # on load if $wgLegacyCharset is set in the future.
583 $flags[] = 'utf-8';
584
585 if( $wgCompressRevisions ) {
586 if( function_exists( 'gzdeflate' ) ) {
587 $text = gzdeflate( $text );
588 $flags[] = 'gzip';
589 } else {
590 wfDebug( "Revision::compressRevisionText() -- no zlib support, not compressing\n" );
591 }
592 }
593 return implode( ',', $flags );
594 }
595
596 /**
597 * Insert a new revision into the database, returning the new revision ID
598 * number on success and dies horribly on failure.
599 *
600 * @param Database $dbw
601 * @return int
602 */
603 function insertOn( &$dbw ) {
604 global $wgDefaultExternalStore;
605
606 $fname = 'Revision::insertOn';
607 wfProfileIn( $fname );
608
609 $data = $this->mText;
610 $flags = Revision::compressRevisionText( $data );
611
612 # Write to external storage if required
613 if ( $wgDefaultExternalStore ) {
614 if ( is_array( $wgDefaultExternalStore ) ) {
615 // Distribute storage across multiple clusters
616 $store = $wgDefaultExternalStore[mt_rand(0, count( $wgDefaultExternalStore ) - 1)];
617 } else {
618 $store = $wgDefaultExternalStore;
619 }
620 require_once('ExternalStore.php');
621 // Store and get the URL
622 $data = ExternalStore::insert( $store, $data );
623 if ( !$data ) {
624 # This should only happen in the case of a configuration error, where the external store is not valid
625 throw new MWException( "Unable to store text to external storage $store" );
626 }
627 if ( $flags ) {
628 $flags .= ',';
629 }
630 $flags .= 'external';
631 }
632
633 # Record the text (or external storage URL) to the text table
634 if( !isset( $this->mTextId ) ) {
635 $old_id = $dbw->nextSequenceValue( 'text_old_id_val' );
636 $dbw->insert( 'text',
637 array(
638 'old_id' => $old_id,
639 'old_text' => $data,
640 'old_flags' => $flags,
641 ), $fname
642 );
643 $this->mTextId = $dbw->insertId();
644 }
645
646 # Record the edit in revisions
647 $rev_id = isset( $this->mId )
648 ? $this->mId
649 : $dbw->nextSequenceValue( 'rev_rev_id_val' );
650 $dbw->insert( 'revision',
651 array(
652 'rev_id' => $rev_id,
653 'rev_page' => $this->mPage,
654 'rev_text_id' => $this->mTextId,
655 'rev_comment' => $this->mComment,
656 'rev_minor_edit' => $this->mMinorEdit ? 1 : 0,
657 'rev_user' => $this->mUser,
658 'rev_user_text' => $this->mUserText,
659 'rev_timestamp' => $dbw->timestamp( $this->mTimestamp ),
660 'rev_deleted' => $this->mDeleted,
661 ), $fname
662 );
663
664 $this->mId = !is_null($rev_id) ? $rev_id : $dbw->insertId();
665 wfProfileOut( $fname );
666 return $this->mId;
667 }
668
669 /**
670 * Lazy-load the revision's text.
671 * Currently hardcoded to the 'text' table storage engine.
672 *
673 * @return string
674 * @access private
675 */
676 function loadText() {
677 $fname = 'Revision::loadText';
678 wfProfileIn( $fname );
679
680 // Caching may be beneficial for massive use of external storage
681 global $wgRevisionCacheExpiry, $wgMemc, $wgDBname;
682 $key = "$wgDBname:revisiontext:textid:" . $this->getTextId();
683 if( $wgRevisionCacheExpiry ) {
684 $text = $wgMemc->get( $key );
685 if( is_string( $text ) ) {
686 wfProfileOut( $fname );
687 return $text;
688 }
689 }
690
691 // If we kept data for lazy extraction, use it now...
692 $row = $this->mTextRow;
693 $this->mTextRow = null;
694
695 if( !$row ) {
696 // Text data is immutable; check slaves first.
697 $dbr =& wfGetDB( DB_SLAVE );
698 $row = $dbr->selectRow( 'text',
699 array( 'old_text', 'old_flags' ),
700 array( 'old_id' => $this->getTextId() ),
701 $fname);
702 }
703
704 if( !$row ) {
705 // Possible slave lag!
706 $dbw =& wfGetDB( DB_MASTER );
707 $row = $dbw->selectRow( 'text',
708 array( 'old_text', 'old_flags' ),
709 array( 'old_id' => $this->getTextId() ),
710 $fname);
711 }
712
713 $text = Revision::getRevisionText( $row );
714
715 if( $wgRevisionCacheExpiry ) {
716 $wgMemc->set( $key, $text, $wgRevisionCacheExpiry );
717 }
718
719 wfProfileOut( $fname );
720
721 return $text;
722 }
723
724 /**
725 * Create a new null-revision for insertion into a page's
726 * history. This will not re-save the text, but simply refer
727 * to the text from the previous version.
728 *
729 * Such revisions can for instance identify page rename
730 * operations and other such meta-modifications.
731 *
732 * @param Database $dbw
733 * @param int $pageId ID number of the page to read from
734 * @param string $summary
735 * @param bool $minor
736 * @return Revision
737 */
738 function newNullRevision( &$dbw, $pageId, $summary, $minor ) {
739 $fname = 'Revision::newNullRevision';
740 wfProfileIn( $fname );
741
742 $current = $dbw->selectRow(
743 array( 'page', 'revision' ),
744 array( 'page_latest', 'rev_text_id' ),
745 array(
746 'page_id' => $pageId,
747 'page_latest=rev_id',
748 ),
749 $fname );
750
751 if( $current ) {
752 $revision = new Revision( array(
753 'page' => $pageId,
754 'comment' => $summary,
755 'minor_edit' => $minor,
756 'text_id' => $current->rev_text_id,
757 ) );
758 } else {
759 $revision = null;
760 }
761
762 wfProfileOut( $fname );
763 return $revision;
764 }
765
766 /**
767 * Determine if the current user is allowed to view a particular
768 * field of this revision, if it's marked as deleted.
769 * @param int $field one of self::DELETED_TEXT,
770 * self::DELETED_COMMENT,
771 * self::DELETED_USER
772 * @return bool
773 */
774 function userCan( $field ) {
775 if( ( $this->mDeleted & $field ) == $field ) {
776 global $wgUser;
777 $permission = ( $this->mDeleted & self::DELETED_RESTRICTED ) == self::DELETED_RESTRICTED
778 ? 'hiderevision'
779 : 'deleterevision';
780 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
781 return $wgUser->isAllowed( $permission );
782 } else {
783 return true;
784 }
785 }
786
787
788 /**
789 * Get rev_timestamp from rev_id, without loading the rest of the row
790 * @param integer $id
791 */
792 static function getTimestampFromID( $id ) {
793 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
794 array( 'rev_id' => $id ), __METHOD__ );
795 if ( $timestamp === false ) {
796 # Not in slave, try master
797 $dbw =& wfGetDB( DB_MASTER );
798 $timestamp = $dbw->selectField( 'revision', 'rev_timestamp',
799 array( 'rev_id' => $id ), __METHOD__ );
800 }
801 return $timestamp;
802 }
803
804 static function countByPageId( $db, $id ) {
805 $row = $db->selectRow( 'revision', 'COUNT(*) AS revCount',
806 array( 'rev_page' => $id ), __METHOD__ );
807 if( $row ) {
808 return $row->revCount;
809 }
810 return 0;
811 }
812
813 static function countByTitle( $db, $title ) {
814 $id = $title->getArticleId();
815 if( $id ) {
816 return Revision::countByPageId( $db, $id );
817 }
818 return 0;
819 }
820 }
821
822 /**
823 * Aliases for backwards compatibility with 1.6
824 */
825 define( 'MW_REV_DELETED_TEXT', Revision::DELETED_TEXT );
826 define( 'MW_REV_DELETED_COMMENT', Revision::DELETED_COMMENT );
827 define( 'MW_REV_DELETED_USER', Revision::DELETED_USER );
828 define( 'MW_REV_DELETED_RESTRICTED', Revision::DELETED_RESTRICTED );
829
830
831 ?>