8 * Need the CacheManager to be loaded
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
17 * Class representing a Wikipedia article and history.
19 * See design.doc for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mCountAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
40 * Constructor and clear the article
41 * @param mixed &$title
43 function Article( &$title ) {
44 $this->mTitle
=& $title;
49 * get the title object of the article
61 $this->mContentLoaded
= false;
62 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
63 $this->mRedirectedFrom
= $this->mUserText
=
64 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
65 $this->mCountAdjustment
= 0;
66 $this->mTouched
= '19700101000000';
67 $this->mForUpdate
= false;
71 * Note that getContent/loadContent may follow redirects if
72 * not told otherwise, and so may cause a change to mTitle.
75 * @return Return the text of this revision
77 function getContent( $noredir ) {
80 # Get variables from query string :P
81 $action = $wgRequest->getText( 'action', 'view' );
82 $section = $wgRequest->getText( 'section' );
84 $fname = 'Article::getContent';
85 wfProfileIn( $fname );
87 if ( 0 == $this->getID() ) {
88 if ( 'edit' == $action ) {
89 wfProfileOut( $fname );
90 return ''; # was "newarticletext", now moved above the box)
92 wfProfileOut( $fname );
93 return wfMsg( 'noarticletext' );
95 $this->loadContent( $noredir );
96 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
97 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
98 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle
->getText()) &&
101 wfProfileOut( $fname );
102 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
104 if($action=='edit') {
106 if($section=='new') {
107 wfProfileOut( $fname );
111 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
112 # comments to be stripped as well)
113 $rv=$this->getSection($this->mContent
,$section);
114 wfProfileOut( $fname );
118 wfProfileOut( $fname );
119 return $this->mContent
;
125 * This function returns the text of a section, specified by a number ($section).
126 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
127 * the first section before any such heading (section 0).
129 * If a section contains subsections, these are also returned.
131 * @param string $text text to look in
132 * @param integer $section section number
133 * @return string text of the requested section
135 function getSection($text,$section) {
137 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
138 # comments to be stripped as well)
140 $parser=new Parser();
141 $parser->mOutputType
=OT_WIKI
;
142 $striptext=$parser->strip($text, $striparray, true);
144 # now that we can be sure that no pseudo-sections are in the source,
145 # split it up by section
148 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
150 PREG_SPLIT_DELIM_CAPTURE
);
154 $headline=$secs[$section*2-1];
155 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
158 # translate wiki heading into level
159 if(strpos($hlevel,'=')!==false) {
160 $hlevel=strlen($hlevel);
163 $rv=$headline. $secs[$section*2];
167 while(!empty($secs[$count*2-1]) && !$break) {
169 $subheadline=$secs[$count*2-1];
170 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
171 $subhlevel=$matches[1];
172 if(strpos($subhlevel,'=')!==false) {
173 $subhlevel=strlen($subhlevel);
175 if($subhlevel > $hlevel) {
176 $rv.=$subheadline.$secs[$count*2];
178 if($subhlevel <= $hlevel) {
185 # reinsert stripped tags
186 $rv=$parser->unstrip($rv,$striparray);
187 $rv=$parser->unstripNoWiki($rv,$striparray);
194 * Return an array of the columns of the "cur"-table
196 function getContentFields() {
197 return $wgArticleContentFields = array(
198 'old_text','old_flags',
199 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
200 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
204 * Return the oldid of the article that is to be shown.
205 * For requests with a "direction", this is not the oldid of the
208 function getOldID() {
209 global $wgRequest, $wgOut;
212 if ( isset( $lastid ) ) {
216 $oldid = $wgRequest->getVal( 'oldid' );
217 if ( isset( $oldid ) ) {
218 $oldid = IntVal( $oldid );
219 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
220 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
224 $wgOut->redirect( $this->mTitle
->getFullURL( 'redirect=no' ) );
226 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
227 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
236 return @$oldid; # "@" to be able to return "unset" without PHP complaining
241 * Load the revision (including cur_text) into this object
243 function loadContent( $noredir = false ) {
244 global $wgOut, $wgRequest;
246 if ( $this->mContentLoaded
) return;
249 $oldid = $this->getOldID();
250 $redirect = $wgRequest->getVal( 'redirect' );
252 $fname = 'Article::loadContent';
254 # Pre-fill content with error message so that if something
255 # fails we'll have something telling us what we intended.
257 $t = $this->mTitle
->getPrefixedText();
259 $noredir = $noredir ||
($wgRequest->getVal( 'redirect' ) == 'no')
260 ||
$wgRequest->getCheck( 'rdfrom' );
261 $this->mOldId
= $oldid;
262 $this->fetchContent( $oldid, $noredir, true );
267 * Fetch a page record with the given conditions
268 * @param Database $dbr
269 * @param array $conditions
272 function pageData( &$dbr, $conditions ) {
273 return $dbr->selectRow( 'page',
287 'Article::pageData' );
290 function pageDataFromTitle( &$dbr, $title ) {
291 return $this->pageData( $dbr, array(
292 'page_namespace' => $title->getNamespace(),
293 'page_title' => $title->getDBkey() ) );
296 function pageDataFromId( &$dbr, $id ) {
297 return $this->pageData( $dbr, array(
298 'page_id' => IntVal( $id ) ) );
302 * Get text of an article from database
303 * @param int $oldid 0 for whatever the latest revision is
304 * @param bool $noredir Set to true to avoid following redirects
305 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
308 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
309 if ( $this->mContentLoaded
) {
310 return $this->mContent
;
312 $dbr =& $this->getDB();
313 $fname = 'Article::fetchContent';
315 # Pre-fill content with error message so that if something
316 # fails we'll have something telling us what we intended.
317 $t = $this->mTitle
->getPrefixedText();
319 $t .= ',oldid='.$oldid;
321 if( isset( $redirect ) ) {
322 $redirect = ($redirect == 'no') ?
'no' : 'yes';
323 $t .= ',redirect='.$redirect;
325 $this->mContent
= wfMsg( 'missingarticle', $t );
328 $revision = Revision
::newFromId( $oldid );
329 if( is_null( $revision ) ) {
332 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
336 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
338 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
339 $revision = Revision
::newFromId( $data->page_latest
);
342 # If we got a redirect, follow it (unless we've been told
343 # not to by either the function parameter or the query
344 if ( !$oldid && !$noredir ) {
345 $rt = Title
::newFromRedirect( $revision->getText() );
346 # process if title object is valid and not special:userlogout
347 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) ) {
348 # Gotta hand redirects to special pages differently:
349 # Fill the HTTP response "Location" header and ignore
350 # the rest of the page we're on.
353 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
354 $source = $this->mTitle
->getFullURL( 'redirect=no' );
355 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
358 if ( $rt->getNamespace() == NS_SPECIAL
) {
359 $wgOut->redirect( $rt->getFullURL() );
363 $redirData = $this->pageDataFromTitle( $dbr, $rt );
365 $redirRev = Revision
::newFromId( $redirData->page_latest
);
366 if( !is_null( $redirRev ) ) {
367 $this->mRedirectedFrom
= $this->mTitle
->getPrefixedText();
370 $revision = $redirRev;
376 # if the title's different from expected, update...
379 if( !$this->mTitle
->equals( $wgTitle ) ) {
380 $wgTitle = $this->mTitle
;
384 # Back to the business at hand...
385 $this->mCounter
= $data->page_counter
;
386 $this->mTitle
->mRestrictions
= explode( ',', trim( $data->page_restrictions
) );
387 $this->mTitle
->mRestrictionsLoaded
= true;
388 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
390 $this->mContent
= $revision->getText();
392 $this->mUser
= $revision->getUser();
393 $this->mUserText
= $revision->getUserText();
394 $this->mComment
= $revision->getComment();
395 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
397 $this->mContentLoaded
= true;
398 return $this->mContent
;
402 * Gets the article text without using so many damn globals
403 * Returns false on error
405 * @param integer $oldid
407 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
408 return $this->fetchContent( $oldid, $noredir, false );
412 * Read/write accessor to select FOR UPDATE
414 function forUpdate( $x = NULL ) {
415 return wfSetVar( $this->mForUpdate
, $x );
419 * Get the database which should be used for reads
422 #if ( $this->mForUpdate ) {
423 return wfGetDB( DB_MASTER
);
425 # return wfGetDB( DB_SLAVE );
430 * Get options for all SELECT statements
431 * Can pass an option array, to which the class-wide options will be appended
433 function getSelectOptions( $options = '' ) {
434 if ( $this->mForUpdate
) {
435 if ( is_array( $options ) ) {
436 $options[] = 'FOR UPDATE';
438 $options = 'FOR UPDATE';
445 * Return the Article ID
448 if( $this->mTitle
) {
449 return $this->mTitle
->getArticleID();
456 * Get the view count for this article
458 function getCount() {
459 if ( -1 == $this->mCounter
) {
460 $id = $this->getID();
461 $dbr =& $this->getDB();
462 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
463 'Article::getCount', $this->getSelectOptions() );
465 return $this->mCounter
;
469 * Would the given text make this article a "good" article (i.e.,
470 * suitable for including in the article count)?
471 * @param string $text Text to analyze
472 * @return integer 1 if it can be counted else 0
474 function isCountable( $text ) {
475 global $wgUseCommaCount;
477 if ( NS_MAIN
!= $this->mTitle
->getNamespace() ) { return 0; }
478 if ( $this->isRedirect( $text ) ) { return 0; }
479 $token = ($wgUseCommaCount ?
',' : '[[' );
480 if ( false === strstr( $text, $token ) ) { return 0; }
485 * Tests if the article text represents a redirect
487 function isRedirect( $text = false ) {
488 if ( $text === false ) {
489 $this->loadContent();
490 $titleObj = Title
::newFromRedirect( $this->mText
);
492 $titleObj = Title
::newFromRedirect( $text );
494 return $titleObj !== NULL;
498 * Loads everything except the text
499 * This isn't necessary for all uses, so it's only done if needed.
502 function loadLastEdit() {
505 if ( -1 != $this->mUser
)
508 # New or non-existent articles have no user information
509 $id = $this->getID();
510 if ( 0 == $id ) return;
512 $fname = 'Article::loadLastEdit';
514 $dbr =& $this->getDB();
515 $s = $dbr->selectRow( array( 'revision', 'page') ,
516 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
517 array( 'page_id' => $id, 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
519 if ( $s !== false ) {
520 $this->mUser
= $s->rev_user
;
521 $this->mUserText
= $s->rev_user_text
;
522 $this->mTimestamp
= wfTimestamp(TS_MW
,$s->rev_timestamp
);
523 $this->mComment
= $s->rev_comment
;
524 $this->mMinorEdit
= $s->rev_minor_edit
;
528 function getTimestamp() {
529 $this->loadLastEdit();
530 return $this->mTimestamp
;
534 $this->loadLastEdit();
538 function getUserText() {
539 $this->loadLastEdit();
540 return $this->mUserText
;
543 function getComment() {
544 $this->loadLastEdit();
545 return $this->mComment
;
548 function getMinorEdit() {
549 $this->loadLastEdit();
550 return $this->mMinorEdit
;
553 function getContributors($limit = 0, $offset = 0) {
554 $fname = 'Article::getContributors';
556 # XXX: this is expensive; cache this info somewhere.
558 $title = $this->mTitle
;
560 $dbr =& $this->getDB();
561 $revTable = $dbr->tableName( 'revision' );
562 $userTable = $dbr->tableName( 'user' );
563 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
564 $ns = $title->getNamespace();
565 $user = $this->getUser();
566 $pageId = $this->getId();
568 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
569 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
570 WHERE rev_page = $pageId
571 AND rev_user != $user
572 GROUP BY rev_user, rev_user_text, user_real_name
573 ORDER BY timestamp DESC";
575 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
576 $sql .= ' '. $this->getSelectOptions();
578 $res = $dbr->query($sql, $fname);
580 while ( $line = $dbr->fetchObject( $res ) ) {
581 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
584 $dbr->freeResult($res);
589 * This is the default action of the script: just view the page of
593 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
594 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
595 global $wgEnotif, $wgParser;
596 $sk = $wgUser->getSkin();
598 $fname = 'Article::view';
599 wfProfileIn( $fname );
600 # Get variables from query string
601 $oldid = $this->getOldID();
602 $diff = $wgRequest->getVal( 'diff' );
603 $rcid = $wgRequest->getVal( 'rcid' );
604 $rdfrom = $wgRequest->getVal( 'rdfrom' );
606 $wgOut->setArticleFlag( true );
607 $wgOut->setRobotpolicy( 'index,follow' );
608 # If we got diff and oldid in the query, we want to see a
609 # diff page instead of the article.
611 if ( !is_null( $diff ) ) {
612 require_once( 'DifferenceEngine.php' );
613 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
614 $de = new DifferenceEngine( $oldid, $diff, $rcid );
617 # Run view updates for current revision only
618 $this->viewUpdates();
620 wfProfileOut( $fname );
623 if ( empty( $oldid ) && $this->checkTouched() ) {
624 if( $wgOut->checkLastModified( $this->mTouched
) ){
625 wfProfileOut( $fname );
627 } else if ( $this->tryFileCache() ) {
628 # tell wgOut that output is taken care of
630 $this->viewUpdates();
631 wfProfileOut( $fname );
635 # Should the parser cache be used?
636 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
644 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
648 if ( !$outputDone ) {
649 $text = $this->getContent( false ); # May change mTitle by following a redirect
651 # Another whitelist check in case oldid or redirects are altering the title
652 if ( !$this->mTitle
->userCanRead() ) {
653 $wgOut->loginToUse();
659 # We're looking at an old revision
661 if ( !empty( $oldid ) ) {
662 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
663 $wgOut->setRobotpolicy( 'noindex,follow' );
665 if ( '' != $this->mRedirectedFrom
) {
666 $sk = $wgUser->getSkin();
667 $redir = $sk->makeKnownLink( $this->mRedirectedFrom
, '',
669 $s = wfMsg( 'redirectedfrom', $redir );
670 $wgOut->setSubtitle( $s );
672 # Can't cache redirects
674 } elseif ( !empty( $rdfrom ) ) {
675 global $wgRedirectSources;
676 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
677 $sk = $wgUser->getSkin();
678 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
679 $s = wfMsg( 'redirectedfrom', $redir );
680 $wgOut->setSubtitle( $s );
684 # wrap user css and user js in pre and don't parse
685 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
687 $this->mTitle
->getNamespace() == NS_USER
&&
688 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
690 $wgOut->addWikiText( wfMsg('clearyourcache'));
691 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
692 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
694 $imageUrl = $wgStylePath.'/common/images/redirect.png';
695 $targetUrl = $rt->escapeLocalURL();
696 $titleText = htmlspecialchars( $rt->getPrefixedText() );
697 $link = $sk->makeLinkObj( $rt );
699 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
700 '<span class="redirectText">'.$link.'</span>' );
702 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
703 $catlinks = $parseout->getCategoryLinks();
704 $wgOut->addCategoryLinks($catlinks);
705 $skin = $wgUser->getSkin();
706 } else if ( $pcache ) {
707 # Display content and save to parser cache
708 $wgOut->addPrimaryWikiText( $text, $this );
710 # Display content, don't attempt to save to parser cache
711 $wgOut->addWikiText( $text );
714 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
715 # If we have been passed an &rcid= parameter, we want to give the user a
716 # chance to mark this new article as patrolled.
717 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
718 ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
720 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
721 $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg ( 'markaspatrolledtext' ),
722 'action=markpatrolled&rcid='.$rcid )
726 # Put link titles into the link cache
727 $wgOut->transformBuffer();
729 # Add link titles as META keywords
730 $wgOut->addMetaTags() ;
732 $this->viewUpdates();
733 wfProfileOut( $fname );
737 * Insert a new empty page record for this article.
738 * This *must* be followed up by creating a revision
739 * and running $this->updateToLatest( $rev_id );
740 * or else the record will be left in a funky state.
741 * Best if all done inside a transaction.
743 * @param Database $dbw
744 * @return int The newly created page_id key
747 function insertOn( &$dbw ) {
748 $fname = 'Article::insertOn';
749 wfProfileIn( $fname );
751 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
752 $dbw->insert( 'page', array(
753 'page_id' => $page_id,
754 'page_namespace' => $this->mTitle
->getNamespace(),
755 'page_title' => $this->mTitle
->getDBkey(),
757 'page_restrictions' => '',
758 'page_is_redirect' => 0, # Will set this shortly...
760 'page_random' => wfRandom(),
761 'page_touched' => $dbw->timestamp(),
762 'page_latest' => 0, # Fill this in shortly...
764 $newid = $dbw->insertId();
766 $this->mTitle
->resetArticleId( $newid );
768 wfProfileOut( $fname );
773 * Update the page record to point to a newly saved revision.
775 * @param Database $dbw
776 * @param Revision $revision -- for ID number, and text used to set
777 length and redirect status fields
778 * @param int $lastRevision -- if given, will not overwrite the page field
779 * when different from the currently set value.
780 * Giving 0 indicates the new page flag should
782 * @return bool true on success, false on failure
785 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
786 $fname = 'Article::updateToRevision';
787 wfProfileIn( $fname );
789 $conditions = array( 'page_id' => $this->getId() );
790 if( !is_null( $lastRevision ) ) {
791 # An extra check against threads stepping on each other
792 $conditions['page_latest'] = $lastRevision;
794 $text = $revision->getText();
795 $dbw->update( 'page',
797 'page_latest' => $revision->getId(),
798 'page_touched' => $dbw->timestamp(),
799 'page_is_new' => ($lastRevision === 0) ?
0 : 1,
800 'page_is_redirect' => Article
::isRedirect( $text ),
801 'page_len' => strlen( $text ),
806 wfProfileOut( $fname );
807 return ( $dbw->affectedRows() != 0 );
811 * If the given revision is newer than the currently set page_latest,
812 * update the page record. Otherwise, do nothing.
814 * @param Database $dbw
815 * @param Revision $revision
817 function updateIfNewerOn( &$dbw, $revision ) {
818 $fname = 'Article::updateIfNewerOn';
819 wfProfileIn( $fname );
821 $row = $dbw->selectRow(
822 array( 'revision', 'page' ),
823 array( 'rev_id', 'rev_timestamp' ),
825 'page_id' => $this->getId(),
826 'page_latest=rev_id' ),
829 if( $row->rev_timestamp
>= $revision->getTimestamp() ) {
830 wfProfileOut( $fname );
833 $prev = $row->rev_id
;
835 # No or missing previous revision; mark the page as new
839 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
840 wfProfileOut( $fname );
845 * Theoretically we could defer these whole insert and update
846 * functions for after display, but that's taking a big leap
847 * of faith, and we want to be able to report database
848 * errors at some point.
851 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
852 global $wgOut, $wgUser;
853 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
855 $fname = 'Article::insertNewArticle';
857 $this->mCountAdjustment
= $this->isCountable( $text );
859 $ns = $this->mTitle
->getNamespace();
860 $ttl = $this->mTitle
->getDBkey();
861 $text = $this->preSaveTransform( $text );
862 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ?
1 : 0;
864 $dbw =& wfGetDB( DB_MASTER
);
866 # Add the page record; stake our claim on this title!
867 $newid = $this->insertOn( $dbw );
869 # Save the revision text...
870 $revision = new Revision( array(
872 'comment' => $summary,
873 'minor_edit' => $isminor,
876 $revisionId = $revision->insertOn( $dbw );
878 $this->mTitle
->resetArticleID( $newid );
880 # Update the page record with revision data
881 $this->updateRevisionOn( $dbw, $revision, 0 );
883 Article
::onArticleCreate( $this->mTitle
);
884 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary );
887 if(!$this->mTitle
->userIsWatching()) $this->watch();
889 if ( $this->mTitle
->userIsWatching() ) {
894 # The talk page isn't in the regular link tables, so we need to update manually:
895 $talkns = $ns ^
1; # talk -> normal; normal -> talk
896 $dbw->update( 'page',
897 array( 'page_touched' => $dbw->timestamp($now) ),
898 array( 'page_namespace' => $talkns,
899 'page_title' => $ttl ),
902 # standard deferred updates
903 $this->editUpdates( $text, $summary, $isminor, $now );
905 $oldid = 0; # new article
906 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
910 * Fetch and uncompress the text for a given revision.
911 * Can ask by rev_id number or timestamp (set $field)
913 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
914 $fname = 'Article::fetchRevisionText';
915 $dbw =& wfGetDB( DB_MASTER
);
917 $rev = $dbw->addQuotes( $revId );
919 $rev = 'page_latest';
921 $result = $dbw->query(
922 sprintf( "SELECT old_text, old_flags
924 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
926 $dbw->tableName( 'page' ),
927 $dbw->tableName( 'revision' ),
928 $dbw->tableName( 'text' ),
929 IntVal( $this->mTitle
->getArticleId() ),
933 $obj = $dbw->fetchObject( $result );
934 $dbw->freeResult( $result );
935 $oldtext = Revision
::getRevisionText( $obj );
939 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
940 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
941 if( is_null( $edittime ) ) {
942 $oldtext = $this->fetchRevisionText();
944 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
946 if ($section != '') {
947 if($section=='new') {
948 if($summary) $subject="== {$summary} ==\n\n";
949 $text=$oldtext."\n\n".$subject.$text;
952 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
953 # comments to be stripped as well)
955 $parser=new Parser();
956 $parser->mOutputType
=OT_WIKI
;
957 $oldtext=$parser->strip($oldtext, $striparray, true);
959 # now that we can be sure that no pseudo-sections are in the source,
961 # Unfortunately we can't simply do a preg_replace because that might
962 # replace the wrong section, so we have to use the section counter instead
963 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
964 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
965 $secs[$section*2]=$text."\n\n"; // replace with edited
967 # section 0 is top (intro) section
970 # headline of old section - we need to go through this section
971 # to determine if there are any subsections that now need to
972 # be erased, as the mother section has been replaced with
973 # the text of all subsections.
974 $headline=$secs[$section*2-1];
975 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
978 # determine headline level for wikimarkup headings
979 if(strpos($hlevel,'=')!==false) {
980 $hlevel=strlen($hlevel);
983 $secs[$section*2-1]=''; // erase old headline
986 while(!empty($secs[$count*2-1]) && !$break) {
988 $subheadline=$secs[$count*2-1];
990 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
991 $subhlevel=$matches[1];
992 if(strpos($subhlevel,'=')!==false) {
993 $subhlevel=strlen($subhlevel);
995 if($subhlevel > $hlevel) {
996 // erase old subsections
997 $secs[$count*2-1]='';
1000 if($subhlevel <= $hlevel) {
1008 $text=join('',$secs);
1009 # reinsert the stuff that we stripped out earlier
1010 $text=$parser->unstrip($text,$striparray);
1011 $text=$parser->unstripNoWiki($text,$striparray);
1019 * Change an existing article. Puts the previous version back into the old table, updates RC
1020 * and all necessary caches, mostly via the deferred update array.
1022 * It is possible to call this function from a command-line script, but note that you should
1023 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1025 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1026 global $wgOut, $wgUser;
1027 global $wgDBtransactions, $wgMwRedir;
1028 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1030 $fname = 'Article::updateArticle';
1033 $isminor = ( $minor && $wgUser->isLoggedIn() );
1034 if ( $this->isRedirect( $text ) ) {
1035 # Remove all content but redirect
1036 # This could be done by reconstructing the redirect from a title given by
1037 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1039 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1041 $text = $m[1] . "\n";
1044 else { $redir = 0; }
1046 $text = $this->preSaveTransform( $text );
1047 $dbw =& wfGetDB( DB_MASTER
);
1049 # Update article, but only if changed.
1051 # It's important that we either rollback or complete, otherwise an attacker could
1052 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1053 # could conceivably have the same effect, especially if cur is locked for long periods.
1054 if( $wgDBtransactions ) {
1055 $dbw->query( 'BEGIN', $fname );
1057 $userAbort = ignore_user_abort( true );
1060 $oldtext = $this->getContent( true );
1062 if ( 0 != strcmp( $text, $oldtext ) ) {
1063 $this->mCountAdjustment
= $this->isCountable( $text )
1064 - $this->isCountable( $oldtext );
1065 $now = wfTimestampNow();
1067 $lastRevision = $dbw->selectField(
1068 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1070 $revision = new Revision( array(
1071 'page' => $this->getId(),
1072 'comment' => $summary,
1073 'minor_edit' => $isminor,
1076 $revisionId = $revision->insertOn( $dbw );
1079 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1082 /* Belated edit conflict! Run away!! */
1085 # Update recentchanges and purge cache and whatnot
1086 $bot = (int)($wgUser->isBot() ||
$forceBot);
1087 RecentChange
::notifyEdit( $now, $this->mTitle
, $me2, $wgUser, $summary,
1088 $lastRevision, $this->getTimestamp(), $bot );
1089 Article
::onArticleEdit( $this->mTitle
);
1093 if( $wgDBtransactions ) {
1094 $dbw->query( 'COMMIT', $fname );
1096 ignore_user_abort( $userAbort );
1101 if (!$this->mTitle
->userIsWatching()) $this->watch();
1103 if ( $this->mTitle
->userIsWatching() ) {
1107 # standard deferred updates
1108 $this->editUpdates( $text, $summary, $minor, $now );
1112 # Template namespace
1113 # Purge all articles linking here
1114 if ( $this->mTitle
->getNamespace() == NS_TEMPLATE
) {
1115 $titles = $this->mTitle
->getLinksTo();
1116 Title
::touchArray( $titles );
1117 if ( $wgUseSquid ) {
1118 foreach ( $titles as $title ) {
1119 $urls[] = $title->getInternalURL();
1125 if ( $wgUseSquid ) {
1126 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1127 $u = new SquidUpdate( $urls );
1128 array_push( $wgPostCommitUpdateList, $u );
1131 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1137 * After we've either updated or inserted the article, update
1138 * the link tables and redirect to the new page.
1140 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1141 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1143 $wgLinkCache = new LinkCache();
1145 $wgLinkCache->forUpdate( true );
1147 # Get old version of link table to allow incremental link updates
1148 $wgLinkCache->preFill( $this->mTitle
);
1149 $wgLinkCache->clear();
1151 # Parse the text and replace links with placeholders
1152 $wgOut = new OutputPage();
1153 $wgOut->addWikiText( $text );
1155 # Look up the links in the DB and add them to the link cache
1156 $wgOut->transformBuffer( RLH_FOR_UPDATE
);
1158 if( $this->isRedirect( $text ) )
1162 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1164 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1165 # this will be improved later (to-do)
1167 include_once( "UserMailer.php" );
1168 $wgEnotif = new EmailNotification ();
1169 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle
->getDBkey(), $this->mTitle
->getNamespace(),$now, $summary, $me2, $oldid );
1173 * Mark this particular edit as patrolled
1175 function markpatrolled() {
1176 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1177 $wgOut->setRobotpolicy( 'noindex,follow' );
1179 if ( !$wgUseRCPatrol )
1181 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1184 if ( $wgUser->isAnon() )
1186 $wgOut->loginToUse();
1189 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1191 $wgOut->sysopRequired();
1194 $rcid = $wgRequest->getVal( 'rcid' );
1195 if ( !is_null ( $rcid ) )
1197 RecentChange
::markPatrolled( $rcid );
1198 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1199 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1201 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1202 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1206 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1213 function validate() {
1214 global $wgOut, $wgUser;
1215 $wgOut->setRobotpolicy( 'noindex,follow' );
1217 $wgOut->addWikiText ( "Not implemented yet" ) ;
1221 * Add this page to $wgUser's watchlist
1226 global $wgUser, $wgOut;
1228 if ( $wgUser->isAnon() ) {
1229 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1232 if ( wfReadOnly() ) {
1233 $wgOut->readOnlyPage();
1237 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1239 $wgUser->addWatch( $this->mTitle
);
1240 $wgUser->saveSettings();
1242 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1244 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1245 $wgOut->setRobotpolicy( 'noindex,follow' );
1247 $link = $this->mTitle
->getPrefixedText();
1248 $text = wfMsg( 'addedwatchtext', $link );
1249 $wgOut->addWikiText( $text );
1252 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1256 * Stop watching a page
1259 function unwatch() {
1261 global $wgUser, $wgOut;
1263 if ( $wgUser->isAnon() ) {
1264 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1267 if ( wfReadOnly() ) {
1268 $wgOut->readOnlyPage();
1272 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1274 $wgUser->removeWatch( $this->mTitle
);
1275 $wgUser->saveSettings();
1277 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1279 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1280 $wgOut->setRobotpolicy( 'noindex,follow' );
1282 $link = $this->mTitle
->getPrefixedText();
1283 $text = wfMsg( 'removedwatchtext', $link );
1284 $wgOut->addWikiText( $text );
1287 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1293 function protect( $limit = 'sysop' ) {
1294 global $wgUser, $wgOut, $wgRequest;
1296 if ( ! $wgUser->isAllowed('protect') ) {
1297 $wgOut->sysopRequired();
1300 if ( wfReadOnly() ) {
1301 $wgOut->readOnlyPage();
1304 $id = $this->mTitle
->getArticleID();
1306 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1310 $confirm = $wgRequest->wasPosted() &&
1311 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1312 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1313 $reason = $wgRequest->getText( 'wpReasonProtect' );
1316 $dbw =& wfGetDB( DB_MASTER
);
1317 $dbw->update( 'page',
1319 'page_touched' => $dbw->timestamp(),
1320 'page_restrictions' => (string)$limit
1321 ), array( /* WHERE */
1323 ), 'Article::protect'
1326 $restrictions = "move=" . $limit;
1328 $restrictions .= ":edit=" . $limit;
1330 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1332 $dbw =& wfGetDB( DB_MASTER
);
1333 $dbw->update( 'page',
1335 'page_touched' => $dbw->timestamp(),
1336 'page_restrictions' => $restrictions
1337 ), array( /* WHERE */
1339 ), 'Article::protect'
1342 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1344 $log = new LogPage( 'protect' );
1345 if ( $limit === '' ) {
1346 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1348 $log->addEntry( 'protect', $this->mTitle
, $reason );
1350 $wgOut->redirect( $this->mTitle
->getFullURL() );
1354 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1355 return $this->confirmProtect( '', $reason, $limit );
1360 * Output protection confirmation dialog
1362 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1363 global $wgOut, $wgUser;
1365 wfDebug( "Article::confirmProtect\n" );
1367 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1368 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1374 if ( $limit === '' ) {
1375 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1376 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1377 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1378 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1379 $formaction = $this->mTitle
->escapeLocalURL( 'action=unprotect' . $par );
1381 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1382 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1383 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1384 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1385 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1386 $formaction = $this->mTitle
->escapeLocalURL( 'action=protect' . $par );
1389 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1390 $token = htmlspecialchars( $wgUser->editToken() );
1393 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1397 <label for='wpReasonProtect'>{$protcom}:</label>
1400 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1406 if($moveonly != '') {
1410 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1413 <label for='wpMoveOnly'>{$moveonly}</label>
1421 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1425 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1428 $wgOut->returnToMain( false );
1432 * Unprotect the pages
1434 function unprotect() {
1435 return $this->protect( '' );
1439 * UI entry point for page deletion
1442 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1443 $fname = 'Article::delete';
1444 $confirm = $wgRequest->wasPosted() &&
1445 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1446 $reason = $wgRequest->getText( 'wpReason' );
1448 # This code desperately needs to be totally rewritten
1451 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1452 $wgOut->sysopRequired();
1455 if ( wfReadOnly() ) {
1456 $wgOut->readOnlyPage();
1460 # Better double-check that it hasn't been deleted yet!
1461 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1462 if ( ( '' == trim( $this->mTitle
->getText() ) )
1463 or ( $this->mTitle
->getArticleId() == 0 ) ) {
1464 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1469 $this->doDelete( $reason );
1473 # determine whether this page has earlier revisions
1474 # and insert a warning if it does
1475 # we select the text because it might be useful below
1476 $dbr =& $this->getDB();
1477 $ns = $this->mTitle
->getNamespace();
1478 $title = $this->mTitle
->getDBkey();
1479 $revisions = $dbr->select( array( 'page', 'revision' ),
1482 'page_namespace' => $ns,
1483 'page_title' => $title,
1484 'rev_page = page_id'
1485 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1488 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1489 $skin=$wgUser->getSkin();
1490 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1491 $wgOut->addHTML( $skin->historyLink() .'</b>');
1495 $s = $dbr->selectRow( array( 'page', 'text' ),
1496 array( 'old_text' ),
1498 'page_namespace' => $ns,
1499 'page_title' => $title,
1500 'page_latest = old_id'
1501 ), $fname, $this->getSelectOptions()
1504 if( $s !== false ) {
1505 # if this is a mini-text, we can paste part of it into the deletion reason
1507 #if this is empty, an earlier revision may contain "useful" text
1509 if($s->old_text
!= '') {
1513 $text = Revision
::getRevisionText( $old );
1519 $length=strlen($text);
1521 # this should not happen, since it is not possible to store an empty, new
1522 # page. Let's insert a standard text in case it does, though
1523 if($length == 0 && $reason === '') {
1524 $reason = wfMsg('exblank');
1527 if($length < 500 && $reason === '') {
1529 # comment field=255, let's grep the first 150 to have some user
1531 $text=substr($text,0,150);
1532 # let's strip out newlines and HTML tags
1533 $text=preg_replace('/\"/',"'",$text);
1534 $text=preg_replace('/\</','<',$text);
1535 $text=preg_replace('/\>/','>',$text);
1536 $text=preg_replace("/[\n\r]/",'',$text);
1538 $reason=wfMsg('excontent'). " '".$text;
1540 $reason=wfMsg('exbeforeblank') . " '".$text;
1542 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1547 return $this->confirmDelete( '', $reason );
1551 * Output deletion confirmation dialog
1553 function confirmDelete( $par, $reason ) {
1554 global $wgOut, $wgUser;
1556 wfDebug( "Article::confirmDelete\n" );
1558 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1559 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1560 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1561 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1563 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1565 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1566 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1567 $token = htmlspecialchars( $wgUser->editToken() );
1570 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1574 <label for='wpReason'>{$delcom}:</label>
1577 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1586 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1590 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1593 $wgOut->returnToMain( false );
1598 * Perform a deletion and output success or failure messages
1600 function doDelete( $reason ) {
1601 global $wgOut, $wgUser, $wgContLang;
1602 $fname = 'Article::doDelete';
1603 wfDebug( $fname."\n" );
1605 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1606 if ( $this->doDeleteArticle( $reason ) ) {
1607 $deleted = $this->mTitle
->getPrefixedText();
1609 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1610 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1612 $sk = $wgUser->getSkin();
1613 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT
) .
1614 ':' . wfMsgForContent( 'dellogpage' ),
1615 wfMsg( 'deletionlog' ) );
1617 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1619 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1620 $wgOut->returnToMain( false );
1621 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1623 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1629 * Back-end article deletion
1630 * Deletes the article with database consistency, writes logs, purges caches
1633 function doDeleteArticle( $reason ) {
1635 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1637 $fname = 'Article::doDeleteArticle';
1638 wfDebug( $fname."\n" );
1640 $dbw =& wfGetDB( DB_MASTER
);
1641 $ns = $this->mTitle
->getNamespace();
1642 $t = $this->mTitle
->getDBkey();
1643 $id = $this->mTitle
->getArticleID();
1645 if ( $t == '' ||
$id == 0 ) {
1649 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1650 array_push( $wgDeferredUpdateList, $u );
1652 $linksTo = $this->mTitle
->getLinksTo();
1655 if ( $wgUseSquid ) {
1657 $this->mTitle
->getInternalURL(),
1658 $this->mTitle
->getInternalURL( 'history' )
1660 foreach ( $linksTo as $linkTo ) {
1661 $urls[] = $linkTo->getInternalURL();
1664 $u = new SquidUpdate( $urls );
1665 array_push( $wgPostCommitUpdateList, $u );
1669 # Client and file cache invalidation
1670 Title
::touchArray( $linksTo );
1672 # Move article and history to the "archive" table
1674 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1676 'ar_namespace' => 'page_namespace',
1677 'ar_title' => 'page_title',
1678 'ar_text' => 'old_text',
1679 'ar_comment' => 'rev_comment',
1680 'ar_user' => 'rev_user',
1681 'ar_user_text' => 'rev_user_text',
1682 'ar_timestamp' => 'rev_timestamp',
1683 'ar_minor_edit' => 'rev_minor_edit',
1684 'ar_flags' => 'old_flags',
1685 'ar_rev_id' => 'rev_id',
1687 'page_namespace' => $ns,
1689 'page_id = rev_page AND old_id = rev_id'
1693 # Now that it's safely backed up, delete it
1695 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1696 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1697 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1699 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1701 # Finally, clean up the link tables
1702 $t = $this->mTitle
->getPrefixedDBkey();
1704 Article
::onArticleDelete( $this->mTitle
);
1706 # Insert broken links
1707 $brokenLinks = array();
1708 foreach ( $linksTo as $titleObj ) {
1709 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1710 $linkID = $titleObj->getArticleID();
1711 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1713 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1716 $dbw->delete( 'links', array( 'l_to' => $id ) );
1717 $dbw->delete( 'links', array( 'l_from' => $id ) );
1718 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1719 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1720 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1723 $log = new LogPage( 'delete' );
1724 $log->addEntry( 'delete', $this->mTitle
, $reason );
1726 # Clear the cached article id so the interface doesn't act like we exist
1727 $this->mTitle
->resetArticleID( 0 );
1728 $this->mTitle
->mArticleID
= 0;
1733 * Revert a modification
1735 function rollback() {
1736 global $wgUser, $wgOut, $wgRequest;
1737 $fname = 'Article::rollback';
1739 if ( ! $wgUser->isAllowed('rollback') ) {
1740 $wgOut->sysopRequired();
1743 if ( wfReadOnly() ) {
1744 $wgOut->readOnlyPage( $this->getContent( true ) );
1747 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1748 array( $this->mTitle
->getPrefixedText(),
1749 $wgRequest->getVal( 'from' ) ) ) ) {
1750 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1751 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1754 $dbw =& wfGetDB( DB_MASTER
);
1756 # Enhanced rollback, marks edits rc_bot=1
1757 $bot = $wgRequest->getBool( 'bot' );
1759 # Replace all this user's current edits with the next one down
1760 $tt = $this->mTitle
->getDBKey();
1761 $n = $this->mTitle
->getNamespace();
1763 # Get the last editor, lock table exclusively
1765 $current = Revision
::newFromTitle( $this->mTitle
);
1766 if( is_null( $current ) ) {
1767 # Something wrong... no page?
1769 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1773 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1774 if( $from != $current->getUserText() ) {
1775 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1776 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1777 htmlspecialchars( $this->mTitle
->getPrefixedText()),
1778 htmlspecialchars( $from ),
1779 htmlspecialchars( $current->getUserText() ) ) );
1780 if( $current->getComment() != '') {
1782 wfMsg( 'editcomment',
1783 htmlspecialchars( $current->getComment() ) ) );
1788 # Get the last edit not by this guy
1789 $user = IntVal( $current->getUser() );
1790 $user_text = $dbw->addQuotes( $current->getUserText() );
1791 $s = $dbw->selectRow( 'revision',
1792 array( 'rev_id', 'rev_timestamp' ),
1794 'rev_page' => $current->getPage(),
1795 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1798 'USE INDEX' => 'page_timestamp',
1799 'ORDER BY' => 'rev_timestamp DESC' )
1801 if( $s === false ) {
1804 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1805 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1810 # Mark all reverted edits as bot
1811 $dbw->update( 'recentchanges',
1814 ), array( /* WHERE */
1815 'rc_cur_id' => $current->getPage(),
1816 'rc_user_text' => $current->getUserText(),
1817 "rc_timestamp > '{$s->rev_timestamp}'",
1823 $target = Revision
::newFromId( $s->rev_id
);
1824 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1826 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1827 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1828 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1830 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle
->userIsWatching(), $bot );
1831 Article
::onArticleEdit( $this->mTitle
);
1834 $wgOut->returnToMain( false );
1839 * Do standard deferred updates after page view
1842 function viewUpdates() {
1843 global $wgDeferredUpdateList;
1845 if ( 0 != $this->getID() ) {
1846 global $wgDisableCounters;
1847 if( !$wgDisableCounters ) {
1848 Article
::incViewCount( $this->getID() );
1849 $u = new SiteStatsUpdate( 1, 0, 0 );
1850 array_push( $wgDeferredUpdateList, $u );
1854 # Update newtalk status if user is reading their own
1858 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1859 $this->mTitle
->getText() == $wgUser->getName()) {
1860 require_once( 'UserTalkUpdate.php' );
1861 $u = new UserTalkUpdate( 0, $this->mTitle
->getNamespace(), $this->mTitle
->getDBkey(), false, false, false );
1863 $wgUser->clearNotification( $this->mTitle
);
1869 * Do standard deferred updates after page edit.
1870 * Every 1000th edit, prune the recent changes table.
1872 * @param string $text
1874 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1875 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1876 global $wgMessageCache, $wgUser;
1879 if ( 0 == mt_rand( 0, 999 ) ) {
1880 # Periodically flush old entries from the recentchanges table.
1882 $dbw =& wfGetDB( DB_MASTER
);
1883 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1884 $recentchanges = $dbw->tableName( 'recentchanges' );
1885 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1886 $dbw->query( $sql );
1888 $id = $this->getID();
1889 $title = $this->mTitle
->getPrefixedDBkey();
1890 $shortTitle = $this->mTitle
->getDBkey();
1892 $adj = $this->mCountAdjustment
;
1895 $u = new LinksUpdate( $id, $title );
1896 array_push( $wgDeferredUpdateList, $u );
1897 $u = new SiteStatsUpdate( 0, 1, $adj );
1898 array_push( $wgDeferredUpdateList, $u );
1899 $u = new SearchUpdate( $id, $title, $text );
1900 array_push( $wgDeferredUpdateList, $u );
1902 # If this is another user's talk page,
1903 # create a watchlist entry for this page
1905 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&&
1906 $shortTitle != $wgUser->getName()) {
1907 require_once( 'UserTalkUpdate.php' );
1908 $u = new UserTalkUpdate( 1, $this->mTitle
->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1911 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1912 $wgMessageCache->replace( $shortTitle, $text );
1918 * @todo document this function
1920 * @param string $oldid Revision ID of this article revision
1922 function setOldSubtitle( $oldid=0 ) {
1923 global $wgLang, $wgOut, $wgUser;
1925 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
1926 $sk = $wgUser->getSkin();
1927 $lnk = $sk->makeKnownLinkObj ( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
1928 $prevlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1929 $nextlink = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1930 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1931 $wgOut->setSubtitle( $r );
1935 * This function is called right before saving the wikitext,
1936 * so we can do things like signatures and links-in-context.
1938 * @param string $text
1940 function preSaveTransform( $text ) {
1941 global $wgParser, $wgUser;
1942 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
1945 /* Caching functions */
1948 * checkLastModified returns true if it has taken care of all
1949 * output to the client that is necessary for this request.
1950 * (that is, it has sent a cached version of the page)
1952 function tryFileCache() {
1953 static $called = false;
1955 wfDebug( " tryFileCache() -- called twice!?\n" );
1959 if($this->isFileCacheable()) {
1960 $touched = $this->mTouched
;
1961 $cache = new CacheManager( $this->mTitle
);
1962 if($cache->isFileCacheGood( $touched )) {
1964 wfDebug( " tryFileCache() - about to load\n" );
1965 $cache->loadFromFileCache();
1968 wfDebug( " tryFileCache() - starting buffer\n" );
1969 ob_start( array(&$cache, 'saveToFileCache' ) );
1972 wfDebug( " tryFileCache() - not cacheable\n" );
1977 * Check if the page can be cached
1980 function isFileCacheable() {
1981 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1982 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1984 return $wgUseFileCache
1985 and (!$wgShowIPinHeader)
1986 and ($this->getID() != 0)
1987 and ($wgUser->isAnon())
1988 and (!$wgUser->getNewtalk())
1989 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
1990 and (empty( $action ) ||
$action == 'view')
1991 and (!isset($oldid))
1993 and (!isset($redirect))
1994 and (!isset($printable))
1995 and (!$this->mRedirectedFrom
);
1999 * Loads cur_touched and returns a value indicating if it should be used
2002 function checkTouched() {
2003 $fname = 'Article::checkTouched';
2004 $id = $this->getID();
2005 $dbr =& $this->getDB();
2006 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
2007 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
2008 if( $s !== false ) {
2009 $this->mTouched
= wfTimestamp( TS_MW
, $s->page_touched
);
2010 return !$s->page_is_redirect
;
2017 * Edit an article without doing all that other stuff
2018 * The article must already exist; link tables etc
2019 * are not updated, caches are not flushed.
2021 * @param string $text text submitted
2022 * @param string $comment comment submitted
2023 * @param bool $minor whereas it's a minor modification
2025 function quickEdit( $text, $comment = '', $minor = 0 ) {
2026 $fname = 'Article::quickEdit';
2027 wfProfileIn( $fname );
2029 $dbw =& wfGetDB( DB_MASTER
);
2031 $revision = new Revision( array(
2032 'page' => $this->getId(),
2034 'comment' => $comment,
2035 'minor_edit' => $minor ?
1 : 0,
2037 $revisionId = $revision->insertOn( $dbw );
2038 $this->updateRevisionOn( $dbw, $revision );
2041 wfProfileOut( $fname );
2045 * Used to increment the view counter
2048 * @param integer $id article id
2050 function incViewCount( $id ) {
2051 $id = intval( $id );
2052 global $wgHitcounterUpdateFreq;
2054 $dbw =& wfGetDB( DB_MASTER
);
2055 $pageTable = $dbw->tableName( 'page' );
2056 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2057 $acchitsTable = $dbw->tableName( 'acchits' );
2059 if( $wgHitcounterUpdateFreq <= 1 ){ //
2060 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2064 # Not important enough to warrant an error page in case of failure
2065 $oldignore = $dbw->ignoreErrors( true );
2067 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2069 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2070 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2071 # Most of the time (or on SQL errors), skip row count check
2072 $dbw->ignoreErrors( $oldignore );
2076 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2077 $row = $dbw->fetchObject( $res );
2078 $rown = intval( $row->n
);
2079 if( $rown >= $wgHitcounterUpdateFreq ){
2080 wfProfileIn( 'Article::incViewCount-collect' );
2081 $old_user_abort = ignore_user_abort( true );
2083 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2084 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2085 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2087 $dbw->query("DELETE FROM $hitcounterTable");
2088 $dbw->query('UNLOCK TABLES');
2089 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2090 'WHERE cur_id = hc_id');
2091 $dbw->query("DROP TABLE $acchitsTable");
2093 ignore_user_abort( $old_user_abort );
2094 wfProfileOut( 'Article::incViewCount-collect' );
2096 $dbw->ignoreErrors( $oldignore );
2100 * The onArticle*() functions are supposed to be a kind of hooks
2101 * which should be called whenever any of the specified actions
2104 * This is a good place to put code to clear caches, for instance.
2106 * This is called on page move and undelete, as well as edit
2108 * @param $title_obj a title object
2111 function onArticleCreate($title_obj) {
2112 global $wgUseSquid, $wgPostCommitUpdateList;
2114 $titles = $title_obj->getBrokenLinksTo();
2117 if ( $wgUseSquid ) {
2118 $urls = $title_obj->getSquidURLs();
2119 foreach ( $titles as $linkTitle ) {
2120 $urls[] = $linkTitle->getInternalURL();
2122 $u = new SquidUpdate( $urls );
2123 array_push( $wgPostCommitUpdateList, $u );
2126 # Clear persistent link cache
2127 LinkCache
::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2130 function onArticleDelete($title_obj) {
2131 LinkCache
::linksccClearLinksTo( $title_obj->getArticleID() );
2133 function onArticleEdit($title_obj) {
2134 LinkCache
::linksccClearPage( $title_obj->getArticleID() );
2139 * Info about this page
2140 * Called for ?action=info when $wgAllowPageInfo is on.
2145 global $wgLang, $wgOut, $wgAllowPageInfo;
2146 $fname = 'Article::info';
2148 if ( !$wgAllowPageInfo ) {
2149 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2153 $page = $this->mTitle
->getSubjectPage();
2155 $wgOut->setPagetitle( $page->getPrefixedText() );
2156 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2158 # first, see if the page exists at all.
2159 $exists = $page->getArticleId() != 0;
2161 $wgOut->addHTML( wfMsg('noarticletext') );
2163 $dbr =& $this->getDB( DB_SLAVE
);
2165 'wl_title' => $page->getDBkey(),
2166 'wl_namespace' => $page->getNamespace() );
2167 $numwatchers = $dbr->selectField(
2172 $this->getSelectOptions() );
2174 $pageInfo = $this->pageCountInfo( $page );
2175 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2177 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2178 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2180 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2182 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2184 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2186 $wgOut->addHTML( '</ul>' );
2192 * Return the total number of edits and number of unique editors
2193 * on a given page. If page does not exist, returns false.
2195 * @param Title $title
2199 function pageCountInfo( $title ) {
2200 $id = $title->getArticleId();
2205 $dbr =& $this->getDB( DB_SLAVE
);
2207 $rev_clause = array( 'rev_page' => $id );
2208 $fname = 'Article::pageCountInfo';
2210 $edits = $dbr->selectField(
2215 $this->getSelectOptions() );
2217 $authors = $dbr->selectField(
2219 'COUNT(DISTINCT rev_user_text)',
2222 $this->getSelectOptions() );
2224 return array( 'edits' => $edits, 'authors' => $authors );