Revert to r14512; domas introduced massive breakage with incomplete experimental...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**@{{
27 * @private
28 */
29 var $mComment; //!<
30 var $mContent; //!<
31 var $mContentLoaded; //!<
32 var $mCounter; //!<
33 var $mFileCache; //!<
34 var $mForUpdate; //!<
35 var $mGoodAdjustment; //!<
36 var $mId; //!<
37 var $mLatest; //!<
38 var $mMinorEdit; //!<
39 var $mOldId; //!<
40 var $mRedirectedFrom; //!<
41 var $mRedirectUrl; //!<
42 var $mRevIdFetched; //!<
43 var $mRevision; //!<
44 var $mTable; //!<
45 var $mTimestamp; //!<
46 var $mTitle; //!<
47 var $mTotalAdjustment; //!<
48 var $mTouched; //!<
49 var $mUser; //!<
50 var $mUserText; //!<
51 /**@}}*/
52
53 /**
54 * Constructor and clear the article
55 * @param $title Reference to a Title object.
56 * @param $oldId Integer revision ID, null to fetch from request, zero for current
57 */
58 function Article( &$title, $oldId = null ) {
59 $this->mTitle =& $title;
60 $this->mOldId = $oldId;
61 $this->clear();
62 }
63
64 /**
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
68 */
69 function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom = $from;
71 }
72
73 /**
74 * @return mixed false, Title of in-wiki target, or string with URL
75 */
76 function followRedirect() {
77 $text = $this->getContent();
78 $rt = Title::newFromRedirect( $text );
79
80 # process if title object is valid and not special:userlogout
81 if( $rt ) {
82 if( $rt->getInterwiki() != '' ) {
83 if( $rt->isLocal() ) {
84 // Offsite wikis need an HTTP redirect.
85 //
86 // This can be hard to reverse and may produce loops,
87 // so they may be disabled in the site configuration.
88
89 $source = $this->mTitle->getFullURL( 'redirect=no' );
90 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
91 }
92 } else {
93 if( $rt->getNamespace() == NS_SPECIAL ) {
94 // Gotta hand redirects to special pages differently:
95 // Fill the HTTP response "Location" header and ignore
96 // the rest of the page we're on.
97 //
98 // This can be hard to reverse, so they may be disabled.
99
100 if( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) {
101 // rolleyes
102 } else {
103 return $rt->getFullURL();
104 }
105 }
106 return $rt;
107 }
108 }
109
110 // No or invalid redirect
111 return false;
112 }
113
114 /**
115 * get the title object of the article
116 */
117 function getTitle() {
118 return $this->mTitle;
119 }
120
121 /**
122 * Clear the object
123 * @private
124 */
125 function clear() {
126 $this->mDataLoaded = false;
127 $this->mContentLoaded = false;
128
129 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
130 $this->mRedirectedFrom = null; # Title object if set
131 $this->mUserText =
132 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
133 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
134 $this->mTouched = '19700101000000';
135 $this->mForUpdate = false;
136 $this->mIsRedirect = false;
137 $this->mRevIdFetched = 0;
138 $this->mRedirectUrl = false;
139 $this->mLatest = false;
140 }
141
142 /**
143 * Note that getContent/loadContent do not follow redirects anymore.
144 * If you need to fetch redirectable content easily, try
145 * the shortcut in Article::followContent()
146 * FIXME
147 * @todo There are still side-effects in this!
148 * In general, you should use the Revision class, not Article,
149 * to fetch text for purposes other than page views.
150 *
151 * @return Return the text of this revision
152 */
153 function getContent() {
154 global $wgRequest, $wgUser, $wgOut;
155
156 # Get variables from query string :P
157 $action = $wgRequest->getText( 'action', 'view' );
158 $section = $wgRequest->getText( 'section' );
159 $preload = $wgRequest->getText( 'preload' );
160
161 $fname = 'Article::getContent';
162 wfProfileIn( $fname );
163
164 if ( 0 == $this->getID() ) {
165 if ( 'edit' == $action ) {
166 wfProfileOut( $fname );
167
168 # If requested, preload some text.
169 $text=$this->getPreloadedText($preload);
170
171 # We used to put MediaWiki:Newarticletext here if
172 # $text was empty at this point.
173 # This is now shown above the edit box instead.
174 return $text;
175 }
176 wfProfileOut( $fname );
177 $wgOut->setRobotpolicy( 'noindex,nofollow' );
178
179 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
180 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
181 } else {
182 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
183 }
184
185 return "<div class='noarticletext'>$ret</div>";
186 } else {
187 $this->loadContent();
188 if($action=='edit') {
189 if($section!='') {
190 if($section=='new') {
191 wfProfileOut( $fname );
192 $text=$this->getPreloadedText($preload);
193 return $text;
194 }
195
196 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
197 # comments to be stripped as well)
198 $rv=$this->getSection($this->mContent,$section);
199 wfProfileOut( $fname );
200 return $rv;
201 }
202 }
203 wfProfileOut( $fname );
204 return $this->mContent;
205 }
206 }
207
208 /**
209 * Get the contents of a page from its title and remove includeonly tags
210 *
211 * @param $preload String: the title of the page.
212 * @return string The contents of the page.
213 */
214 function getPreloadedText($preload) {
215 if ( $preload === '' )
216 return '';
217 else {
218 $preloadTitle = Title::newFromText( $preload );
219 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
220 $rev=Revision::newFromTitle($preloadTitle);
221 if ( is_object( $rev ) ) {
222 $text = $rev->getText();
223 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
224 // its own mini-parser! -ævar
225 $text = preg_replace( '~</?includeonly>~', '', $text );
226 return $text;
227 } else
228 return '';
229 }
230 }
231 }
232
233 /**
234 * This function returns the text of a section, specified by a number ($section).
235 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
236 * the first section before any such heading (section 0).
237 *
238 * If a section contains subsections, these are also returned.
239 *
240 * @param $text String: text to look in
241 * @param $section Integer: section number
242 * @return string text of the requested section
243 */
244 function getSection($text,$section) {
245
246 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
247 # comments to be stripped as well)
248 $striparray=array();
249 $parser=new Parser();
250 $parser->mOutputType=OT_WIKI;
251 $parser->mOptions = new ParserOptions();
252 $striptext=$parser->strip($text, $striparray, true);
253
254 # now that we can be sure that no pseudo-sections are in the source,
255 # split it up by section
256 $secs =
257 preg_split(
258 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
259 $striptext, -1,
260 PREG_SPLIT_DELIM_CAPTURE);
261 if($section==0) {
262 $rv=$secs[0];
263 } else {
264 $headline=$secs[$section*2-1];
265 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
266 $hlevel=$matches[1];
267
268 # translate wiki heading into level
269 if(strpos($hlevel,'=')!==false) {
270 $hlevel=strlen($hlevel);
271 }
272
273 $rv=$headline. $secs[$section*2];
274 $count=$section+1;
275
276 $break=false;
277 while(!empty($secs[$count*2-1]) && !$break) {
278
279 $subheadline=$secs[$count*2-1];
280 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
281 $subhlevel=$matches[1];
282 if(strpos($subhlevel,'=')!==false) {
283 $subhlevel=strlen($subhlevel);
284 }
285 if($subhlevel > $hlevel) {
286 $rv.=$subheadline.$secs[$count*2];
287 }
288 if($subhlevel <= $hlevel) {
289 $break=true;
290 }
291 $count++;
292
293 }
294 }
295 # reinsert stripped tags
296 $rv=$parser->unstrip($rv,$striparray);
297 $rv=$parser->unstripNoWiki($rv,$striparray);
298 $rv=trim($rv);
299 return $rv;
300
301 }
302
303 /**
304 * @return int The oldid of the article that is to be shown, 0 for the
305 * current revision
306 */
307 function getOldID() {
308 if ( is_null( $this->mOldId ) ) {
309 $this->mOldId = $this->getOldIDFromRequest();
310 }
311 return $this->mOldId;
312 }
313
314 /**
315 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
316 *
317 * @return int The old id for the request
318 */
319 function getOldIDFromRequest() {
320 global $wgRequest;
321 $this->mRedirectUrl = false;
322 $oldid = $wgRequest->getVal( 'oldid' );
323 if ( isset( $oldid ) ) {
324 $oldid = intval( $oldid );
325 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
326 $nextid = $this->mTitle->getNextRevisionID( $oldid );
327 if ( $nextid ) {
328 $oldid = $nextid;
329 } else {
330 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
331 }
332 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
333 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
334 if ( $previd ) {
335 $oldid = $previd;
336 } else {
337 # TODO
338 }
339 }
340 # unused:
341 # $lastid = $oldid;
342 }
343 if ( !$oldid ) {
344 $oldid = 0;
345 }
346 return $oldid;
347 }
348
349 /**
350 * Load the revision (including text) into this object
351 */
352 function loadContent() {
353 if ( $this->mContentLoaded ) return;
354
355 # Query variables :P
356 $oldid = $this->getOldID();
357
358 # Pre-fill content with error message so that if something
359 # fails we'll have something telling us what we intended.
360
361 $t = $this->mTitle->getPrefixedText();
362
363 $this->mOldId = $oldid;
364 $this->fetchContent( $oldid );
365 }
366
367
368 /**
369 * Fetch a page record with the given conditions
370 * @param Database $dbr
371 * @param array $conditions
372 * @private
373 */
374 function pageData( &$dbr, $conditions ) {
375 $fields = array(
376 'page_id',
377 'page_namespace',
378 'page_title',
379 'page_restrictions',
380 'page_counter',
381 'page_is_redirect',
382 'page_is_new',
383 'page_random',
384 'page_touched',
385 'page_latest',
386 'page_len' ) ;
387 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
388 $row = $dbr->selectRow( 'page',
389 $fields,
390 $conditions,
391 'Article::pageData' );
392 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
393 return $row ;
394 }
395
396 /**
397 * @param Database $dbr
398 * @param Title $title
399 */
400 function pageDataFromTitle( &$dbr, $title ) {
401 return $this->pageData( $dbr, array(
402 'page_namespace' => $title->getNamespace(),
403 'page_title' => $title->getDBkey() ) );
404 }
405
406 /**
407 * @param Database $dbr
408 * @param int $id
409 */
410 function pageDataFromId( &$dbr, $id ) {
411 return $this->pageData( $dbr, array( 'page_id' => $id ) );
412 }
413
414 /**
415 * Set the general counter, title etc data loaded from
416 * some source.
417 *
418 * @param object $data
419 * @private
420 */
421 function loadPageData( $data = 'fromdb' ) {
422 if ( $data === 'fromdb' ) {
423 $dbr =& $this->getDB();
424 $data = $this->pageDataFromId( $dbr, $this->getId() );
425 }
426
427 $lc =& LinkCache::singleton();
428 if ( $data ) {
429 $lc->addGoodLinkObj( $data->page_id, $this->mTitle );
430
431 $this->mTitle->mArticleID = $data->page_id;
432 $this->mTitle->loadRestrictions( $data->page_restrictions );
433 $this->mTitle->mRestrictionsLoaded = true;
434
435 $this->mCounter = $data->page_counter;
436 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
437 $this->mIsRedirect = $data->page_is_redirect;
438 $this->mLatest = $data->page_latest;
439 } else {
440 if ( is_object( $this->mTitle ) ) {
441 $lc->addBadLinkObj( $this->mTitle );
442 }
443 $this->mTitle->mArticleID = 0;
444 }
445
446 $this->mDataLoaded = true;
447 }
448
449 /**
450 * Get text of an article from database
451 * Does *NOT* follow redirects.
452 * @param int $oldid 0 for whatever the latest revision is
453 * @return string
454 */
455 function fetchContent( $oldid = 0 ) {
456 if ( $this->mContentLoaded ) {
457 return $this->mContent;
458 }
459
460 $dbr =& $this->getDB();
461 $fname = 'Article::fetchContent';
462
463 # Pre-fill content with error message so that if something
464 # fails we'll have something telling us what we intended.
465 $t = $this->mTitle->getPrefixedText();
466 if( $oldid ) {
467 $t .= ',oldid='.$oldid;
468 }
469 $this->mContent = wfMsg( 'missingarticle', $t ) ;
470
471 if( $oldid ) {
472 $revision = Revision::newFromId( $oldid );
473 if( is_null( $revision ) ) {
474 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
475 return false;
476 }
477 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
478 if( !$data ) {
479 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
480 return false;
481 }
482 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
483 $this->loadPageData( $data );
484 } else {
485 if( !$this->mDataLoaded ) {
486 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
487 if( !$data ) {
488 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
489 return false;
490 }
491 $this->loadPageData( $data );
492 }
493 $revision = Revision::newFromId( $this->mLatest );
494 if( is_null( $revision ) ) {
495 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
496 return false;
497 }
498 }
499
500 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
501 // We should instead work with the Revision object when we need it...
502 $this->mContent = $revision->userCan( MW_REV_DELETED_TEXT ) ? $revision->getRawText() : "";
503 //$this->mContent = $revision->getText();
504
505 $this->mUser = $revision->getUser();
506 $this->mUserText = $revision->getUserText();
507 $this->mComment = $revision->getComment();
508 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
509
510 $this->mRevIdFetched = $revision->getID();
511 $this->mContentLoaded = true;
512 $this->mRevision =& $revision;
513
514 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
515
516 return $this->mContent;
517 }
518
519 /**
520 * Read/write accessor to select FOR UPDATE
521 *
522 * @param $x Mixed: FIXME
523 */
524 function forUpdate( $x = NULL ) {
525 return wfSetVar( $this->mForUpdate, $x );
526 }
527
528 /**
529 * Get the database which should be used for reads
530 *
531 * @return Database
532 */
533 function &getDB() {
534 $ret =& wfGetDB( DB_MASTER );
535 return $ret;
536 }
537
538 /**
539 * Get options for all SELECT statements
540 *
541 * @param $options Array: an optional options array which'll be appended to
542 * the default
543 * @return Array: options
544 */
545 function getSelectOptions( $options = '' ) {
546 if ( $this->mForUpdate ) {
547 if ( is_array( $options ) ) {
548 $options[] = 'FOR UPDATE';
549 } else {
550 $options = 'FOR UPDATE';
551 }
552 }
553 return $options;
554 }
555
556 /**
557 * @return int Page ID
558 */
559 function getID() {
560 if( $this->mTitle ) {
561 return $this->mTitle->getArticleID();
562 } else {
563 return 0;
564 }
565 }
566
567 /**
568 * @return bool Whether or not the page exists in the database
569 */
570 function exists() {
571 return $this->getId() != 0;
572 }
573
574 /**
575 * @return int The view count for the page
576 */
577 function getCount() {
578 if ( -1 == $this->mCounter ) {
579 $id = $this->getID();
580 if ( $id == 0 ) {
581 $this->mCounter = 0;
582 } else {
583 $dbr =& wfGetDB( DB_SLAVE );
584 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
585 'Article::getCount', $this->getSelectOptions() );
586 }
587 }
588 return $this->mCounter;
589 }
590
591 /**
592 * Determine whether a page would be suitable for being counted as an
593 * article in the site_stats table based on the title & its content
594 *
595 * @param $text String: text to analyze
596 * @return bool
597 */
598 function isCountable( $text ) {
599 global $wgUseCommaCount;
600
601 $token = $wgUseCommaCount ? ',' : '[[';
602 return
603 $this->mTitle->getNamespace() == NS_MAIN
604 && ! $this->isRedirect( $text )
605 && in_string( $token, $text );
606 }
607
608 /**
609 * Tests if the article text represents a redirect
610 *
611 * @param $text String: FIXME
612 * @return bool
613 */
614 function isRedirect( $text = false ) {
615 if ( $text === false ) {
616 $this->loadContent();
617 $titleObj = Title::newFromRedirect( $this->fetchContent() );
618 } else {
619 $titleObj = Title::newFromRedirect( $text );
620 }
621 return $titleObj !== NULL;
622 }
623
624 /**
625 * Returns true if the currently-referenced revision is the current edit
626 * to this page (and it exists).
627 * @return bool
628 */
629 function isCurrent() {
630 return $this->exists() &&
631 isset( $this->mRevision ) &&
632 $this->mRevision->isCurrent();
633 }
634
635 /**
636 * Loads everything except the text
637 * This isn't necessary for all uses, so it's only done if needed.
638 * @private
639 */
640 function loadLastEdit() {
641 if ( -1 != $this->mUser )
642 return;
643
644 # New or non-existent articles have no user information
645 $id = $this->getID();
646 if ( 0 == $id ) return;
647
648 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
649 if( !is_null( $this->mLastRevision ) ) {
650 $this->mUser = $this->mLastRevision->getUser();
651 $this->mUserText = $this->mLastRevision->getUserText();
652 $this->mTimestamp = $this->mLastRevision->getTimestamp();
653 $this->mComment = $this->mLastRevision->getComment();
654 $this->mMinorEdit = $this->mLastRevision->isMinor();
655 $this->mRevIdFetched = $this->mLastRevision->getID();
656 }
657 }
658
659 function getTimestamp() {
660 // Check if the field has been filled by ParserCache::get()
661 if ( !$this->mTimestamp ) {
662 $this->loadLastEdit();
663 }
664 return wfTimestamp(TS_MW, $this->mTimestamp);
665 }
666
667 function getUser() {
668 $this->loadLastEdit();
669 return $this->mUser;
670 }
671
672 function getUserText() {
673 $this->loadLastEdit();
674 return $this->mUserText;
675 }
676
677 function getComment() {
678 $this->loadLastEdit();
679 return $this->mComment;
680 }
681
682 function getMinorEdit() {
683 $this->loadLastEdit();
684 return $this->mMinorEdit;
685 }
686
687 function getRevIdFetched() {
688 $this->loadLastEdit();
689 return $this->mRevIdFetched;
690 }
691
692 /**
693 * @todo Document, fixme $offset never used.
694 * @param $limit Integer: default 0.
695 * @param $offset Integer: default 0.
696 */
697 function getContributors($limit = 0, $offset = 0) {
698 $fname = 'Article::getContributors';
699
700 # XXX: this is expensive; cache this info somewhere.
701
702 $title = $this->mTitle;
703 $contribs = array();
704 $dbr =& wfGetDB( DB_SLAVE );
705 $revTable = $dbr->tableName( 'revision' );
706 $userTable = $dbr->tableName( 'user' );
707 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
708 $ns = $title->getNamespace();
709 $user = $this->getUser();
710 $pageId = $this->getId();
711
712 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
713 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
714 WHERE rev_page = $pageId
715 AND rev_user != $user
716 GROUP BY rev_user, rev_user_text, user_real_name
717 ORDER BY timestamp DESC";
718
719 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
720 $sql .= ' '. $this->getSelectOptions();
721
722 $res = $dbr->query($sql, $fname);
723
724 while ( $line = $dbr->fetchObject( $res ) ) {
725 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
726 }
727
728 $dbr->freeResult($res);
729 return $contribs;
730 }
731
732 /**
733 * This is the default action of the script: just view the page of
734 * the given title.
735 */
736 function view() {
737 global $wgUser, $wgOut, $wgRequest, $wgContLang;
738 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
739 global $wgUseTrackbacks;
740 $sk = $wgUser->getSkin();
741
742 $fname = 'Article::view';
743 wfProfileIn( $fname );
744 $parserCache =& ParserCache::singleton();
745 # Get variables from query string
746 $oldid = $this->getOldID();
747
748 # getOldID may want us to redirect somewhere else
749 if ( $this->mRedirectUrl ) {
750 $wgOut->redirect( $this->mRedirectUrl );
751 wfProfileOut( $fname );
752 return;
753 }
754
755 $diff = $wgRequest->getVal( 'diff' );
756 $rcid = $wgRequest->getVal( 'rcid' );
757 $rdfrom = $wgRequest->getVal( 'rdfrom' );
758
759 $wgOut->setArticleFlag( true );
760 $wgOut->setRobotpolicy( 'index,follow' );
761 # If we got diff and oldid in the query, we want to see a
762 # diff page instead of the article.
763
764 if ( !is_null( $diff ) ) {
765 require_once( 'DifferenceEngine.php' );
766 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
767
768 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
769 // DifferenceEngine directly fetched the revision:
770 $this->mRevIdFetched = $de->mNewid;
771 $de->showDiffPage();
772
773 if( $diff == 0 ) {
774 # Run view updates for current revision only
775 $this->viewUpdates();
776 }
777 wfProfileOut( $fname );
778 return;
779 }
780
781 if ( empty( $oldid ) && $this->checkTouched() ) {
782 $wgOut->setETag($parserCache->getETag($this, $wgUser));
783
784 if( $wgOut->checkLastModified( $this->mTouched ) ){
785 wfProfileOut( $fname );
786 return;
787 } else if ( $this->tryFileCache() ) {
788 # tell wgOut that output is taken care of
789 $wgOut->disable();
790 $this->viewUpdates();
791 wfProfileOut( $fname );
792 return;
793 }
794 }
795 # Should the parser cache be used?
796 $pcache = $wgEnableParserCache &&
797 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
798 $this->exists() &&
799 empty( $oldid );
800 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
801 if ( $wgUser->getOption( 'stubthreshold' ) ) {
802 wfIncrStats( 'pcache_miss_stub' );
803 }
804
805 $wasRedirected = false;
806 if ( isset( $this->mRedirectedFrom ) ) {
807 // This is an internally redirected page view.
808 // We'll need a backlink to the source page for navigation.
809 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
810 $sk = $wgUser->getSkin();
811 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
812 $s = wfMsg( 'redirectedfrom', $redir );
813 $wgOut->setSubtitle( $s );
814 $wasRedirected = true;
815 }
816 } elseif ( !empty( $rdfrom ) ) {
817 // This is an externally redirected view, from some other wiki.
818 // If it was reported from a trusted site, supply a backlink.
819 global $wgRedirectSources;
820 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
821 $sk = $wgUser->getSkin();
822 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
823 $s = wfMsg( 'redirectedfrom', $redir );
824 $wgOut->setSubtitle( $s );
825 $wasRedirected = true;
826 }
827 }
828
829 $outputDone = false;
830 if ( $pcache ) {
831 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
832 $outputDone = true;
833 }
834 }
835 if ( !$outputDone ) {
836 $text = $this->getContent();
837 if ( $text === false ) {
838 # Failed to load, replace text with error message
839 $t = $this->mTitle->getPrefixedText();
840 if( $oldid ) {
841 $t .= ',oldid='.$oldid;
842 $text = wfMsg( 'missingarticle', $t );
843 } else {
844 $text = wfMsg( 'noarticletext', $t );
845 }
846 }
847
848 # Another whitelist check in case oldid is altering the title
849 if ( !$this->mTitle->userCanRead() ) {
850 $wgOut->loginToUse();
851 $wgOut->output();
852 exit;
853 }
854
855 # We're looking at an old revision
856
857 if ( !empty( $oldid ) ) {
858 $wgOut->setRobotpolicy( 'noindex,nofollow' );
859 if( is_null( $this->mRevision ) ) {
860 // FIXME: This would be a nice place to load the 'no such page' text.
861 } else {
862 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
863 if( $this->mRevision->isDeleted( MW_REV_DELETED_TEXT ) ) {
864 if( !$this->mRevision->userCan( MW_REV_DELETED_TEXT ) ) {
865 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
866 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
867 return;
868 } else {
869 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
870 // and we are allowed to see...
871 }
872 }
873 }
874
875 }
876 }
877 if( !$outputDone ) {
878 /**
879 * @fixme: this hook doesn't work most of the time, as it doesn't
880 * trigger when the parser cache is used.
881 */
882 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
883 $wgOut->setRevisionId( $this->getRevIdFetched() );
884 # wrap user css and user js in pre and don't parse
885 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
886 if (
887 $this->mTitle->getNamespace() == NS_USER &&
888 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
889 ) {
890 $wgOut->addWikiText( wfMsg('clearyourcache'));
891 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
892 } else if ( $rt = Title::newFromRedirect( $text ) ) {
893 # Display redirect
894 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
895 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
896 # Don't overwrite the subtitle if this was an old revision
897 if( !$wasRedirected && $this->isCurrent() ) {
898 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
899 }
900 $targetUrl = $rt->escapeLocalURL();
901 # fixme unused $titleText :
902 $titleText = htmlspecialchars( $rt->getPrefixedText() );
903 $link = $sk->makeLinkObj( $rt );
904
905 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
906 '<span class="redirectText">'.$link.'</span>' );
907
908 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
909 $wgOut->addParserOutputNoText( $parseout );
910 } else if ( $pcache ) {
911 # Display content and save to parser cache
912 $wgOut->addPrimaryWikiText( $text, $this );
913 } else {
914 # Display content, don't attempt to save to parser cache
915
916 # Don't show section-edit links on old revisions... this way lies madness.
917 if( !$this->isCurrent() ) {
918 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
919 }
920 # Display content and don't save to parser cache
921 $wgOut->addPrimaryWikiText( $text, $this, false );
922
923 if( !$this->isCurrent() ) {
924 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
925 }
926 }
927 }
928 /* title may have been set from the cache */
929 $t = $wgOut->getPageTitle();
930 if( empty( $t ) ) {
931 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
932 }
933
934 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
935 if( $this->mTitle->getNamespace() == NS_USER_TALK &&
936 User::isIP( $this->mTitle->getText() ) ) {
937 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
938 }
939
940 # If we have been passed an &rcid= parameter, we want to give the user a
941 # chance to mark this new article as patrolled.
942 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
943 $wgOut->addHTML(
944 "<div class='patrollink'>" .
945 wfMsg ( 'markaspatrolledlink',
946 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
947 ) .
948 '</div>'
949 );
950 }
951
952 # Trackbacks
953 if ($wgUseTrackbacks)
954 $this->addTrackbacks();
955
956 $this->viewUpdates();
957 wfProfileOut( $fname );
958 }
959
960 function addTrackbacks() {
961 global $wgOut, $wgUser;
962
963 $dbr =& wfGetDB(DB_SLAVE);
964 $tbs = $dbr->select(
965 /* FROM */ 'trackbacks',
966 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
967 /* WHERE */ array('tb_page' => $this->getID())
968 );
969
970 if (!$dbr->numrows($tbs))
971 return;
972
973 $tbtext = "";
974 while ($o = $dbr->fetchObject($tbs)) {
975 $rmvtxt = "";
976 if ($wgUser->isAllowed( 'trackback' )) {
977 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
978 . $o->tb_id . "&token=" . $wgUser->editToken());
979 $rmvtxt = wfMsg('trackbackremove', $delurl);
980 }
981 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
982 $o->tb_title,
983 $o->tb_url,
984 $o->tb_ex,
985 $o->tb_name,
986 $rmvtxt);
987 }
988 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
989 }
990
991 function deletetrackback() {
992 global $wgUser, $wgRequest, $wgOut, $wgTitle;
993
994 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
995 $wgOut->addWikitext(wfMsg('sessionfailure'));
996 return;
997 }
998
999 if ((!$wgUser->isAllowed('delete'))) {
1000 $wgOut->sysopRequired();
1001 return;
1002 }
1003
1004 if (wfReadOnly()) {
1005 $wgOut->readOnlyPage();
1006 return;
1007 }
1008
1009 $db =& wfGetDB(DB_MASTER);
1010 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1011 $wgTitle->invalidateCache();
1012 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1013 }
1014
1015 function render() {
1016 global $wgOut;
1017
1018 $wgOut->setArticleBodyOnly(true);
1019 $this->view();
1020 }
1021
1022 /**
1023 * Handle action=purge
1024 */
1025 function purge() {
1026 global $wgUser, $wgRequest, $wgOut;
1027
1028 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
1029 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1030 $this->doPurge();
1031 }
1032 } else {
1033 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1034 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
1035 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1036 $msg = str_replace( '$1',
1037 "<form method=\"post\" action=\"$action\">\n" .
1038 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1039 "</form>\n", $msg );
1040
1041 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1042 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1043 $wgOut->addHTML( $msg );
1044 }
1045 }
1046
1047 /**
1048 * Perform the actions of a page purging
1049 */
1050 function doPurge() {
1051 global $wgUseSquid;
1052 // Invalidate the cache
1053 $this->mTitle->invalidateCache();
1054
1055 if ( $wgUseSquid ) {
1056 // Commit the transaction before the purge is sent
1057 $dbw = wfGetDB( DB_MASTER );
1058 $dbw->immediateCommit();
1059
1060 // Send purge
1061 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1062 $update->doUpdate();
1063 }
1064 $this->view();
1065 }
1066
1067 /**
1068 * Insert a new empty page record for this article.
1069 * This *must* be followed up by creating a revision
1070 * and running $this->updateToLatest( $rev_id );
1071 * or else the record will be left in a funky state.
1072 * Best if all done inside a transaction.
1073 *
1074 * @param Database $dbw
1075 * @param string $restrictions
1076 * @return int The newly created page_id key
1077 * @private
1078 */
1079 function insertOn( &$dbw, $restrictions = '' ) {
1080 $fname = 'Article::insertOn';
1081 wfProfileIn( $fname );
1082
1083 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1084 $dbw->insert( 'page', array(
1085 'page_id' => $page_id,
1086 'page_namespace' => $this->mTitle->getNamespace(),
1087 'page_title' => $this->mTitle->getDBkey(),
1088 'page_counter' => 0,
1089 'page_restrictions' => $restrictions,
1090 'page_is_redirect' => 0, # Will set this shortly...
1091 'page_is_new' => 1,
1092 'page_random' => wfRandom(),
1093 'page_touched' => $dbw->timestamp(),
1094 'page_latest' => 0, # Fill this in shortly...
1095 'page_len' => 0, # Fill this in shortly...
1096 ), $fname );
1097 $newid = $dbw->insertId();
1098
1099 $this->mTitle->resetArticleId( $newid );
1100
1101 wfProfileOut( $fname );
1102 return $newid;
1103 }
1104
1105 /**
1106 * Update the page record to point to a newly saved revision.
1107 *
1108 * @param Database $dbw
1109 * @param Revision $revision For ID number, and text used to set
1110 length and redirect status fields
1111 * @param int $lastRevision If given, will not overwrite the page field
1112 * when different from the currently set value.
1113 * Giving 0 indicates the new page flag should
1114 * be set on.
1115 * @return bool true on success, false on failure
1116 * @private
1117 */
1118 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1119 $fname = 'Article::updateToRevision';
1120 wfProfileIn( $fname );
1121
1122 $conditions = array( 'page_id' => $this->getId() );
1123 if( !is_null( $lastRevision ) ) {
1124 # An extra check against threads stepping on each other
1125 $conditions['page_latest'] = $lastRevision;
1126 }
1127
1128 $text = $revision->getText();
1129 $dbw->update( 'page',
1130 array( /* SET */
1131 'page_latest' => $revision->getId(),
1132 'page_touched' => $dbw->timestamp(),
1133 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1134 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1135 'page_len' => strlen( $text ),
1136 ),
1137 $conditions,
1138 $fname );
1139
1140 wfProfileOut( $fname );
1141 return ( $dbw->affectedRows() != 0 );
1142 }
1143
1144 /**
1145 * If the given revision is newer than the currently set page_latest,
1146 * update the page record. Otherwise, do nothing.
1147 *
1148 * @param Database $dbw
1149 * @param Revision $revision
1150 */
1151 function updateIfNewerOn( &$dbw, $revision ) {
1152 $fname = 'Article::updateIfNewerOn';
1153 wfProfileIn( $fname );
1154
1155 $row = $dbw->selectRow(
1156 array( 'revision', 'page' ),
1157 array( 'rev_id', 'rev_timestamp' ),
1158 array(
1159 'page_id' => $this->getId(),
1160 'page_latest=rev_id' ),
1161 $fname );
1162 if( $row ) {
1163 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1164 wfProfileOut( $fname );
1165 return false;
1166 }
1167 $prev = $row->rev_id;
1168 } else {
1169 # No or missing previous revision; mark the page as new
1170 $prev = 0;
1171 }
1172
1173 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1174 wfProfileOut( $fname );
1175 return $ret;
1176 }
1177
1178 /**
1179 * Insert a new article into the database
1180 * @private
1181 */
1182 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1183 global $wgUser;
1184
1185 $fname = 'Article::insertNewArticle';
1186 wfProfileIn( $fname );
1187
1188 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1189 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1190 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1191 wfProfileOut( $fname );
1192 return false;
1193 }
1194
1195 $ns = $this->mTitle->getNamespace();
1196 $ttl = $this->mTitle->getDBkey();
1197
1198 # If this is a comment, add the summary as headline
1199 if($comment && $summary!="") {
1200 $text="== {$summary} ==\n\n".$text;
1201 }
1202 $text = $this->preSaveTransform( $text );
1203
1204
1205 # Set statistics members
1206 # We work out if it's countable after PST to avoid counter drift
1207 # when articles are created with {{subst:}}
1208 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1209 $this->mTotalAdjustment = 1;
1210
1211 /* Silently ignore minoredit if not allowed */
1212 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1213 $now = wfTimestampNow();
1214
1215 $dbw =& wfGetDB( DB_MASTER );
1216
1217 # Add the page record; stake our claim on this title!
1218 $newid = $this->insertOn( $dbw );
1219
1220 # Save the revision text...
1221 $revision = new Revision( array(
1222 'page' => $newid,
1223 'comment' => $summary,
1224 'minor_edit' => $isminor,
1225 'text' => $text
1226 ) );
1227 $revisionId = $revision->insertOn( $dbw );
1228
1229 $this->mTitle->resetArticleID( $newid );
1230
1231 # Update the page record with revision data
1232 $this->updateRevisionOn( $dbw, $revision, 0 );
1233
1234 Article::onArticleCreate( $this->mTitle );
1235 if(!$suppressRC) {
1236 require_once( 'RecentChange.php' );
1237 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1238 '', strlen( $text ), $revisionId );
1239 # Mark as patrolled if the user can and has the option set
1240 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1241 RecentChange::markPatrolled( $rcid );
1242 }
1243 }
1244
1245 if ($watchthis) {
1246 if(!$this->mTitle->userIsWatching()) $this->doWatch();
1247 } else {
1248 if ( $this->mTitle->userIsWatching() ) {
1249 $this->doUnwatch();
1250 }
1251 }
1252
1253 # The talk page isn't in the regular link tables, so we need to update manually:
1254 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1255 $dbw->update( 'page',
1256 array( 'page_touched' => $dbw->timestamp($now) ),
1257 array( 'page_namespace' => $talkns,
1258 'page_title' => $ttl ),
1259 $fname );
1260
1261 # standard deferred updates
1262 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1263
1264 $oldid = 0; # new article
1265 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1266
1267 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1268 $summary, $isminor,
1269 $watchthis, NULL ) );
1270 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1271 $summary, $isminor,
1272 $watchthis, NULL ) );
1273 wfProfileOut( $fname );
1274 }
1275
1276 /**
1277 * @return string Complete article text, or null if error
1278 */
1279 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1280 $fname = 'Article::replaceSection';
1281 wfProfileIn( $fname );
1282
1283 if ($section != '') {
1284 if( is_null( $edittime ) ) {
1285 $rev = Revision::newFromTitle( $this->mTitle );
1286 } else {
1287 $dbw =& wfGetDB( DB_MASTER );
1288 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1289 }
1290 if( is_null( $rev ) ) {
1291 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1292 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1293 return null;
1294 }
1295 $oldtext = $rev->getText();
1296
1297 if($section=='new') {
1298 if($summary) $subject="== {$summary} ==\n\n";
1299 $text=$oldtext."\n\n".$subject.$text;
1300 } else {
1301
1302 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1303 # comments to be stripped as well)
1304 $striparray=array();
1305 $parser=new Parser();
1306 $parser->mOutputType=OT_WIKI;
1307 $parser->mOptions = new ParserOptions();
1308 $oldtext=$parser->strip($oldtext, $striparray, true);
1309
1310 # now that we can be sure that no pseudo-sections are in the source,
1311 # split it up
1312 # Unfortunately we can't simply do a preg_replace because that might
1313 # replace the wrong section, so we have to use the section counter instead
1314 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1315 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1316 $secs[$section*2]=$text."\n\n"; // replace with edited
1317
1318 # section 0 is top (intro) section
1319 if($section!=0) {
1320
1321 # headline of old section - we need to go through this section
1322 # to determine if there are any subsections that now need to
1323 # be erased, as the mother section has been replaced with
1324 # the text of all subsections.
1325 $headline=$secs[$section*2-1];
1326 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1327 $hlevel=$matches[1];
1328
1329 # determine headline level for wikimarkup headings
1330 if(strpos($hlevel,'=')!==false) {
1331 $hlevel=strlen($hlevel);
1332 }
1333
1334 $secs[$section*2-1]=''; // erase old headline
1335 $count=$section+1;
1336 $break=false;
1337 while(!empty($secs[$count*2-1]) && !$break) {
1338
1339 $subheadline=$secs[$count*2-1];
1340 preg_match(
1341 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1342 $subhlevel=$matches[1];
1343 if(strpos($subhlevel,'=')!==false) {
1344 $subhlevel=strlen($subhlevel);
1345 }
1346 if($subhlevel > $hlevel) {
1347 // erase old subsections
1348 $secs[$count*2-1]='';
1349 $secs[$count*2]='';
1350 }
1351 if($subhlevel <= $hlevel) {
1352 $break=true;
1353 }
1354 $count++;
1355
1356 }
1357
1358 }
1359 $text=join('',$secs);
1360 # reinsert the stuff that we stripped out earlier
1361 $text=$parser->unstrip($text,$striparray);
1362 $text=$parser->unstripNoWiki($text,$striparray);
1363 }
1364
1365 }
1366 wfProfileOut( $fname );
1367 return $text;
1368 }
1369
1370 /**
1371 * Change an existing article. Puts the previous version back into the old table, updates RC
1372 * and all necessary caches, mostly via the deferred update array.
1373 *
1374 * It is possible to call this function from a command-line script, but note that you should
1375 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1376 */
1377 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1378 global $wgUser, $wgDBtransactions, $wgUseSquid;
1379 global $wgPostCommitUpdateList, $wgUseFileCache;
1380
1381 $fname = 'Article::updateArticle';
1382 wfProfileIn( $fname );
1383 $good = true;
1384
1385 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1386 &$summary, &$minor,
1387 &$watchthis, &$sectionanchor ) ) ) {
1388 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1389 wfProfileOut( $fname );
1390 return false;
1391 }
1392
1393 $isminor = $minor && $wgUser->isAllowed('minoredit');
1394
1395 $text = $this->preSaveTransform( $text );
1396 $dbw =& wfGetDB( DB_MASTER );
1397 $now = wfTimestampNow();
1398
1399 # Update article, but only if changed.
1400
1401 # It's important that we either rollback or complete, otherwise an attacker could
1402 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1403 # could conceivably have the same effect, especially if cur is locked for long periods.
1404 if( !$wgDBtransactions ) {
1405 $userAbort = ignore_user_abort( true );
1406 }
1407
1408 $oldtext = $this->getContent();
1409 $oldsize = strlen( $oldtext );
1410 $newsize = strlen( $text );
1411 $lastRevision = 0;
1412 $revisionId = 0;
1413
1414 if ( 0 != strcmp( $text, $oldtext ) ) {
1415 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1416 - (int)$this->isCountable( $oldtext );
1417 $this->mTotalAdjustment = 0;
1418 $now = wfTimestampNow();
1419
1420 $lastRevision = $dbw->selectField(
1421 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1422
1423 $revision = new Revision( array(
1424 'page' => $this->getId(),
1425 'comment' => $summary,
1426 'minor_edit' => $isminor,
1427 'text' => $text
1428 ) );
1429
1430 $dbw->immediateCommit();
1431 $dbw->begin();
1432 $revisionId = $revision->insertOn( $dbw );
1433
1434 # Update page
1435 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1436
1437 if( !$ok ) {
1438 /* Belated edit conflict! Run away!! */
1439 $good = false;
1440 $dbw->rollback();
1441 } else {
1442 # Update recentchanges and purge cache and whatnot
1443 require_once( 'RecentChange.php' );
1444 $bot = (int)($wgUser->isBot() || $forceBot);
1445 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1446 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1447 $revisionId );
1448
1449 # Mark as patrolled if the user can do so and has it set in their options
1450 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1451 RecentChange::markPatrolled( $rcid );
1452 }
1453
1454 $dbw->commit();
1455
1456 // Update caches outside the main transaction
1457 Article::onArticleEdit( $this->mTitle );
1458 }
1459 } else {
1460 // Keep the same revision ID, but do some updates on it
1461 $revisionId = $this->getRevIdFetched();
1462 }
1463
1464 if( !$wgDBtransactions ) {
1465 ignore_user_abort( $userAbort );
1466 }
1467
1468 if ( $good ) {
1469 if ($watchthis) {
1470 if (!$this->mTitle->userIsWatching()) {
1471 $dbw->immediateCommit();
1472 $dbw->begin();
1473 $this->doWatch();
1474 $dbw->commit();
1475 }
1476 } else {
1477 if ( $this->mTitle->userIsWatching() ) {
1478 $dbw->immediateCommit();
1479 $dbw->begin();
1480 $this->doUnwatch();
1481 $dbw->commit();
1482 }
1483 }
1484 # standard deferred updates
1485 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1486
1487
1488 $urls = array();
1489 # Invalidate caches of all articles using this article as a template
1490
1491 # Template namespace
1492 # Purge all articles linking here
1493 $titles = $this->mTitle->getTemplateLinksTo();
1494 Title::touchArray( $titles );
1495 if ( $wgUseSquid ) {
1496 foreach ( $titles as $title ) {
1497 $urls[] = $title->getInternalURL();
1498 }
1499 }
1500
1501 # Squid updates
1502 if ( $wgUseSquid ) {
1503 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1504 $u = new SquidUpdate( $urls );
1505 array_push( $wgPostCommitUpdateList, $u );
1506 }
1507
1508 # File cache
1509 if ( $wgUseFileCache ) {
1510 $cm = new CacheManager($this->mTitle);
1511 @unlink($cm->fileCacheName());
1512 }
1513
1514 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1515 }
1516 wfRunHooks( 'ArticleSaveComplete',
1517 array( &$this, &$wgUser, $text,
1518 $summary, $minor,
1519 $watchthis, $sectionanchor ) );
1520 wfProfileOut( $fname );
1521 return $good;
1522 }
1523
1524 /**
1525 * After we've either updated or inserted the article, update
1526 * the link tables and redirect to the new page.
1527 * @todo FIXME some function arguments never used
1528 */
1529 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1530 global $wgOut;
1531
1532 $fname = 'Article::showArticle';
1533 wfProfileIn( $fname );
1534
1535 # Output the redirect
1536 if( $this->isRedirect( $text ) )
1537 $r = 'redirect=no';
1538 else
1539 $r = '';
1540 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1541
1542 wfProfileOut( $fname );
1543 }
1544
1545 /**
1546 * Mark this particular edit as patrolled
1547 */
1548 function markpatrolled() {
1549 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1550 $wgOut->setRobotpolicy( 'noindex,follow' );
1551
1552 # Check RC patrol config. option
1553 if( !$wgUseRCPatrol ) {
1554 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1555 return;
1556 }
1557
1558 # Check permissions
1559 if( !$wgUser->isAllowed( 'patrol' ) ) {
1560 $wgOut->permissionRequired( 'patrol' );
1561 return;
1562 }
1563
1564 $rcid = $wgRequest->getVal( 'rcid' );
1565 if ( !is_null ( $rcid ) ) {
1566 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1567 require_once( 'RecentChange.php' );
1568 RecentChange::markPatrolled( $rcid );
1569 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1570 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1571 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1572 }
1573 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1574 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1575 }
1576 else {
1577 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1578 }
1579 }
1580
1581 /**
1582 * User-interface handler for the "watch" action
1583 */
1584
1585 function watch() {
1586
1587 global $wgUser, $wgOut;
1588
1589 if ( $wgUser->isAnon() ) {
1590 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1591 return;
1592 }
1593 if ( wfReadOnly() ) {
1594 $wgOut->readOnlyPage();
1595 return;
1596 }
1597
1598 if( $this->doWatch() ) {
1599 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1600 $wgOut->setRobotpolicy( 'noindex,follow' );
1601
1602 $link = $this->mTitle->getPrefixedText();
1603 $text = wfMsg( 'addedwatchtext', $link );
1604 $wgOut->addWikiText( $text );
1605 }
1606
1607 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1608 }
1609
1610 /**
1611 * Add this page to $wgUser's watchlist
1612 * @return bool true on successful watch operation
1613 */
1614 function doWatch() {
1615 global $wgUser;
1616 if( $wgUser->isAnon() ) {
1617 return false;
1618 }
1619
1620 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1621 $wgUser->addWatch( $this->mTitle );
1622 $wgUser->saveSettings();
1623
1624 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1625 }
1626
1627 return false;
1628 }
1629
1630 /**
1631 * User interface handler for the "unwatch" action.
1632 */
1633 function unwatch() {
1634
1635 global $wgUser, $wgOut;
1636
1637 if ( $wgUser->isAnon() ) {
1638 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1639 return;
1640 }
1641 if ( wfReadOnly() ) {
1642 $wgOut->readOnlyPage();
1643 return;
1644 }
1645
1646 if( $this->doUnwatch() ) {
1647 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1648 $wgOut->setRobotpolicy( 'noindex,follow' );
1649
1650 $link = $this->mTitle->getPrefixedText();
1651 $text = wfMsg( 'removedwatchtext', $link );
1652 $wgOut->addWikiText( $text );
1653 }
1654
1655 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1656 }
1657
1658 /**
1659 * Stop watching a page
1660 * @return bool true on successful unwatch
1661 */
1662 function doUnwatch() {
1663 global $wgUser;
1664 if( $wgUser->isAnon() ) {
1665 return false;
1666 }
1667
1668 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1669 $wgUser->removeWatch( $this->mTitle );
1670 $wgUser->saveSettings();
1671
1672 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1673 }
1674
1675 return false;
1676 }
1677
1678 /**
1679 * action=protect handler
1680 */
1681 function protect() {
1682 require_once 'ProtectionForm.php';
1683 $form = new ProtectionForm( $this );
1684 $form->show();
1685 }
1686
1687 /**
1688 * action=unprotect handler (alias)
1689 */
1690 function unprotect() {
1691 $this->protect();
1692 }
1693
1694 /**
1695 * Update the article's restriction field, and leave a log entry.
1696 *
1697 * @param array $limit set of restriction keys
1698 * @param string $reason
1699 * @return bool true on success
1700 */
1701 function updateRestrictions( $limit = array(), $reason = '' ) {
1702 global $wgUser, $wgRestrictionTypes, $wgContLang;
1703
1704 $id = $this->mTitle->getArticleID();
1705 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1706 return false;
1707 }
1708
1709 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1710 # we expect a single selection, but the schema allows otherwise.
1711 $current = array();
1712 foreach( $wgRestrictionTypes as $action )
1713 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1714
1715 $current = Article::flattenRestrictions( $current );
1716 $updated = Article::flattenRestrictions( $limit );
1717
1718 $changed = ( $current != $updated );
1719 $protect = ( $updated != '' );
1720
1721 # If nothing's changed, do nothing
1722 if( $changed ) {
1723 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1724
1725 $dbw =& wfGetDB( DB_MASTER );
1726
1727 # Prepare a null revision to be added to the history
1728 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1729 if( $reason )
1730 $comment .= ": $reason";
1731 if( $protect )
1732 $comment .= " [$updated]";
1733 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1734 $nullRevId = $nullRevision->insertOn( $dbw );
1735
1736 # Update page record
1737 $dbw->update( 'page',
1738 array( /* SET */
1739 'page_touched' => $dbw->timestamp(),
1740 'page_restrictions' => $updated,
1741 'page_latest' => $nullRevId
1742 ), array( /* WHERE */
1743 'page_id' => $id
1744 ), 'Article::protect'
1745 );
1746 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1747
1748 # Update the protection log
1749 $log = new LogPage( 'protect' );
1750 if( $protect ) {
1751 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1752 } else {
1753 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1754 }
1755
1756 } # End hook
1757 } # End "changed" check
1758
1759 return true;
1760 }
1761
1762 /**
1763 * Take an array of page restrictions and flatten it to a string
1764 * suitable for insertion into the page_restrictions field.
1765 * @param array $limit
1766 * @return string
1767 * @private
1768 */
1769 function flattenRestrictions( $limit ) {
1770 if( !is_array( $limit ) ) {
1771 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1772 }
1773 $bits = array();
1774 ksort( $limit );
1775 foreach( $limit as $action => $restrictions ) {
1776 if( $restrictions != '' ) {
1777 $bits[] = "$action=$restrictions";
1778 }
1779 }
1780 return implode( ':', $bits );
1781 }
1782
1783 /*
1784 * UI entry point for page deletion
1785 */
1786 function delete() {
1787 global $wgUser, $wgOut, $wgRequest;
1788 $fname = 'Article::delete';
1789 $confirm = $wgRequest->wasPosted() &&
1790 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1791 $reason = $wgRequest->getText( 'wpReason' );
1792
1793 # This code desperately needs to be totally rewritten
1794
1795 # Check permissions
1796 if( $wgUser->isAllowed( 'delete' ) ) {
1797 if( $wgUser->isBlocked() ) {
1798 $wgOut->blockedPage();
1799 return;
1800 }
1801 } else {
1802 $wgOut->permissionRequired( 'delete' );
1803 return;
1804 }
1805
1806 if( wfReadOnly() ) {
1807 $wgOut->readOnlyPage();
1808 return;
1809 }
1810
1811 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1812
1813 # Better double-check that it hasn't been deleted yet!
1814 $dbw =& wfGetDB( DB_MASTER );
1815 $conds = $this->mTitle->pageCond();
1816 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1817 if ( $latest === false ) {
1818 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1819 return;
1820 }
1821
1822 if( $confirm ) {
1823 $this->doDelete( $reason );
1824 return;
1825 }
1826
1827 # determine whether this page has earlier revisions
1828 # and insert a warning if it does
1829 $maxRevisions = 20;
1830 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1831
1832 if( count( $authors ) > 1 && !$confirm ) {
1833 $skin=$wgUser->getSkin();
1834 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1835 }
1836
1837 # If a single user is responsible for all revisions, find out who they are
1838 if ( count( $authors ) == $maxRevisions ) {
1839 // Query bailed out, too many revisions to find out if they're all the same
1840 $authorOfAll = false;
1841 } else {
1842 $authorOfAll = reset( $authors );
1843 foreach ( $authors as $author ) {
1844 if ( $authorOfAll != $author ) {
1845 $authorOfAll = false;
1846 break;
1847 }
1848 }
1849 }
1850 # Fetch article text
1851 $rev = Revision::newFromTitle( $this->mTitle );
1852
1853 if( !is_null( $rev ) ) {
1854 # if this is a mini-text, we can paste part of it into the deletion reason
1855 $text = $rev->getText();
1856
1857 #if this is empty, an earlier revision may contain "useful" text
1858 $blanked = false;
1859 if( $text == '' ) {
1860 $prev = $rev->getPrevious();
1861 if( $prev ) {
1862 $text = $prev->getText();
1863 $blanked = true;
1864 }
1865 }
1866
1867 $length = strlen( $text );
1868
1869 # this should not happen, since it is not possible to store an empty, new
1870 # page. Let's insert a standard text in case it does, though
1871 if( $length == 0 && $reason === '' ) {
1872 $reason = wfMsgForContent( 'exblank' );
1873 }
1874
1875 if( $length < 500 && $reason === '' ) {
1876 # comment field=255, let's grep the first 150 to have some user
1877 # space left
1878 global $wgContLang;
1879 $text = $wgContLang->truncate( $text, 150, '...' );
1880
1881 # let's strip out newlines
1882 $text = preg_replace( "/[\n\r]/", '', $text );
1883
1884 if( !$blanked ) {
1885 if( $authorOfAll === false ) {
1886 $reason = wfMsgForContent( 'excontent', $text );
1887 } else {
1888 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1889 }
1890 } else {
1891 $reason = wfMsgForContent( 'exbeforeblank', $text );
1892 }
1893 }
1894 }
1895
1896 return $this->confirmDelete( '', $reason );
1897 }
1898
1899 /**
1900 * Get the last N authors
1901 * @param int $num Number of revisions to get
1902 * @param string $revLatest The latest rev_id, selected from the master (optional)
1903 * @return array Array of authors, duplicates not removed
1904 */
1905 function getLastNAuthors( $num, $revLatest = 0 ) {
1906 $fname = 'Article::getLastNAuthors';
1907 wfProfileIn( $fname );
1908
1909 // First try the slave
1910 // If that doesn't have the latest revision, try the master
1911 $continue = 2;
1912 $db =& wfGetDB( DB_SLAVE );
1913 do {
1914 $res = $db->select( array( 'page', 'revision' ),
1915 array( 'rev_id', 'rev_user_text' ),
1916 array(
1917 'page_namespace' => $this->mTitle->getNamespace(),
1918 'page_title' => $this->mTitle->getDBkey(),
1919 'rev_page = page_id'
1920 ), $fname, $this->getSelectOptions( array(
1921 'ORDER BY' => 'rev_timestamp DESC',
1922 'LIMIT' => $num
1923 ) )
1924 );
1925 if ( !$res ) {
1926 wfProfileOut( $fname );
1927 return array();
1928 }
1929 $row = $db->fetchObject( $res );
1930 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1931 $db =& wfGetDB( DB_MASTER );
1932 $continue--;
1933 } else {
1934 $continue = 0;
1935 }
1936 } while ( $continue );
1937
1938 $authors = array( $row->rev_user_text );
1939 while ( $row = $db->fetchObject( $res ) ) {
1940 $authors[] = $row->rev_user_text;
1941 }
1942 wfProfileOut( $fname );
1943 return $authors;
1944 }
1945
1946 /**
1947 * Output deletion confirmation dialog
1948 */
1949 function confirmDelete( $par, $reason ) {
1950 global $wgOut, $wgUser;
1951
1952 wfDebug( "Article::confirmDelete\n" );
1953
1954 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1955 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1956 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1957 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1958
1959 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1960
1961 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1962 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1963 $token = htmlspecialchars( $wgUser->editToken() );
1964
1965 $wgOut->addHTML( "
1966 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1967 <table border='0'>
1968 <tr>
1969 <td align='right'>
1970 <label for='wpReason'>{$delcom}:</label>
1971 </td>
1972 <td align='left'>
1973 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1974 </td>
1975 </tr>
1976 <tr>
1977 <td>&nbsp;</td>
1978 <td>
1979 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1980 </td>
1981 </tr>
1982 </table>
1983 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1984 </form>\n" );
1985
1986 $wgOut->returnToMain( false );
1987 }
1988
1989
1990 /**
1991 * Perform a deletion and output success or failure messages
1992 */
1993 function doDelete( $reason ) {
1994 global $wgOut, $wgUser;
1995 $fname = 'Article::doDelete';
1996 wfDebug( $fname."\n" );
1997
1998 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1999 if ( $this->doDeleteArticle( $reason ) ) {
2000 $deleted = $this->mTitle->getPrefixedText();
2001
2002 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2003 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2004
2005 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2006 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2007
2008 $wgOut->addWikiText( $text );
2009 $wgOut->returnToMain( false );
2010 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2011 } else {
2012 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2013 }
2014 }
2015 }
2016
2017 /**
2018 * Back-end article deletion
2019 * Deletes the article with database consistency, writes logs, purges caches
2020 * Returns success
2021 */
2022 function doDeleteArticle( $reason ) {
2023 global $wgUseSquid, $wgDeferredUpdateList;
2024 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2025
2026 $fname = 'Article::doDeleteArticle';
2027 wfDebug( $fname."\n" );
2028
2029 $dbw =& wfGetDB( DB_MASTER );
2030 $ns = $this->mTitle->getNamespace();
2031 $t = $this->mTitle->getDBkey();
2032 $id = $this->mTitle->getArticleID();
2033
2034 if ( $t == '' || $id == 0 ) {
2035 return false;
2036 }
2037
2038 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2039 array_push( $wgDeferredUpdateList, $u );
2040
2041 $linksTo = $this->mTitle->getLinksTo();
2042
2043 # Squid purging
2044 if ( $wgUseSquid ) {
2045 $urls = array(
2046 $this->mTitle->getInternalURL(),
2047 $this->mTitle->getInternalURL( 'history' )
2048 );
2049
2050 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
2051 array_push( $wgPostCommitUpdateList, $u );
2052
2053 }
2054
2055 # Client and file cache invalidation
2056 Title::touchArray( $linksTo );
2057
2058
2059 // For now, shunt the revision data into the archive table.
2060 // Text is *not* removed from the text table; bulk storage
2061 // is left intact to avoid breaking block-compression or
2062 // immutable storage schemes.
2063 //
2064 // For backwards compatibility, note that some older archive
2065 // table entries will have ar_text and ar_flags fields still.
2066 //
2067 // In the future, we may keep revisions and mark them with
2068 // the rev_deleted field, which is reserved for this purpose.
2069 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2070 array(
2071 'ar_namespace' => 'page_namespace',
2072 'ar_title' => 'page_title',
2073 'ar_comment' => 'rev_comment',
2074 'ar_user' => 'rev_user',
2075 'ar_user_text' => 'rev_user_text',
2076 'ar_timestamp' => 'rev_timestamp',
2077 'ar_minor_edit' => 'rev_minor_edit',
2078 'ar_rev_id' => 'rev_id',
2079 'ar_text_id' => 'rev_text_id',
2080 ), array(
2081 'page_id' => $id,
2082 'page_id = rev_page'
2083 ), $fname
2084 );
2085
2086 # Now that it's safely backed up, delete it
2087 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2088 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2089
2090 if ($wgUseTrackbacks)
2091 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2092
2093 # Clean up recentchanges entries...
2094 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2095
2096 # Finally, clean up the link tables
2097 $t = $this->mTitle->getPrefixedDBkey();
2098
2099 Article::onArticleDelete( $this->mTitle );
2100
2101 # Delete outgoing links
2102 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2103 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2104 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2105 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2106 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2107 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2108
2109 # Log the deletion
2110 $log = new LogPage( 'delete' );
2111 $log->addEntry( 'delete', $this->mTitle, $reason );
2112
2113 # Clear the cached article id so the interface doesn't act like we exist
2114 $this->mTitle->resetArticleID( 0 );
2115 $this->mTitle->mArticleID = 0;
2116 return true;
2117 }
2118
2119 /**
2120 * Revert a modification
2121 */
2122 function rollback() {
2123 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2124 $fname = 'Article::rollback';
2125
2126 if( $wgUser->isAllowed( 'rollback' ) ) {
2127 if( $wgUser->isBlocked() ) {
2128 $wgOut->blockedPage();
2129 return;
2130 }
2131 } else {
2132 $wgOut->permissionRequired( 'rollback' );
2133 return;
2134 }
2135
2136 if ( wfReadOnly() ) {
2137 $wgOut->readOnlyPage( $this->getContent() );
2138 return;
2139 }
2140 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2141 array( $this->mTitle->getPrefixedText(),
2142 $wgRequest->getVal( 'from' ) ) ) ) {
2143 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2144 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2145 return;
2146 }
2147 $dbw =& wfGetDB( DB_MASTER );
2148
2149 # Enhanced rollback, marks edits rc_bot=1
2150 $bot = $wgRequest->getBool( 'bot' );
2151
2152 # Replace all this user's current edits with the next one down
2153 $tt = $this->mTitle->getDBKey();
2154 $n = $this->mTitle->getNamespace();
2155
2156 # Get the last editor, lock table exclusively
2157 $dbw->begin();
2158 $current = Revision::newFromTitle( $this->mTitle );
2159 if( is_null( $current ) ) {
2160 # Something wrong... no page?
2161 $dbw->rollback();
2162 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2163 return;
2164 }
2165
2166 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2167 if( $from != $current->getUserText() ) {
2168 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2169 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2170 htmlspecialchars( $this->mTitle->getPrefixedText()),
2171 htmlspecialchars( $from ),
2172 htmlspecialchars( $current->getUserText() ) ) );
2173 if( $current->getComment() != '') {
2174 $wgOut->addHTML(
2175 wfMsg( 'editcomment',
2176 htmlspecialchars( $current->getComment() ) ) );
2177 }
2178 return;
2179 }
2180
2181 # Get the last edit not by this guy
2182 $user = intval( $current->getUser() );
2183 $user_text = $dbw->addQuotes( $current->getUserText() );
2184 $s = $dbw->selectRow( 'revision',
2185 array( 'rev_id', 'rev_timestamp' ),
2186 array(
2187 'rev_page' => $current->getPage(),
2188 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2189 ), $fname,
2190 array(
2191 'USE INDEX' => 'page_timestamp',
2192 'ORDER BY' => 'rev_timestamp DESC' )
2193 );
2194 if( $s === false ) {
2195 # Something wrong
2196 $dbw->rollback();
2197 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2198 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2199 return;
2200 }
2201
2202 $set = array();
2203 if ( $bot ) {
2204 # Mark all reverted edits as bot
2205 $set['rc_bot'] = 1;
2206 }
2207 if ( $wgUseRCPatrol ) {
2208 # Mark all reverted edits as patrolled
2209 $set['rc_patrolled'] = 1;
2210 }
2211
2212 if ( $set ) {
2213 $dbw->update( 'recentchanges', $set,
2214 array( /* WHERE */
2215 'rc_cur_id' => $current->getPage(),
2216 'rc_user_text' => $current->getUserText(),
2217 "rc_timestamp > '{$s->rev_timestamp}'",
2218 ), $fname
2219 );
2220 }
2221
2222 # Get the edit summary
2223 $target = Revision::newFromId( $s->rev_id );
2224 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2225 $newComment = $wgRequest->getText( 'summary', $newComment );
2226
2227 # Save it!
2228 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2229 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2230 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2231
2232 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2233 Article::onArticleEdit( $this->mTitle );
2234
2235 $dbw->commit();
2236 $wgOut->returnToMain( false );
2237 }
2238
2239
2240 /**
2241 * Do standard deferred updates after page view
2242 * @private
2243 */
2244 function viewUpdates() {
2245 global $wgDeferredUpdateList;
2246
2247 if ( 0 != $this->getID() ) {
2248 global $wgDisableCounters;
2249 if( !$wgDisableCounters ) {
2250 Article::incViewCount( $this->getID() );
2251 $u = new SiteStatsUpdate( 1, 0, 0 );
2252 array_push( $wgDeferredUpdateList, $u );
2253 }
2254 }
2255
2256 # Update newtalk / watchlist notification status
2257 global $wgUser;
2258 $wgUser->clearNotification( $this->mTitle );
2259 }
2260
2261 /**
2262 * Do standard deferred updates after page edit.
2263 * Every 1000th edit, prune the recent changes table.
2264 * @private
2265 * @param string $text
2266 */
2267 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2268 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2269
2270 $fname = 'Article::editUpdates';
2271 wfProfileIn( $fname );
2272
2273 # Parse the text
2274 $options = new ParserOptions;
2275 $options->setTidy(true);
2276 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2277
2278 # Save it to the parser cache
2279 $parserCache =& ParserCache::singleton();
2280 $parserCache->save( $poutput, $this, $wgUser );
2281
2282 # Update the links tables
2283 $u = new LinksUpdate( $this->mTitle, $poutput );
2284 $u->doUpdate();
2285
2286 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2287 wfSeedRandom();
2288 if ( 0 == mt_rand( 0, 999 ) ) {
2289 # Periodically flush old entries from the recentchanges table.
2290 global $wgRCMaxAge;
2291
2292 $dbw =& wfGetDB( DB_MASTER );
2293 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2294 $recentchanges = $dbw->tableName( 'recentchanges' );
2295 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2296 $dbw->query( $sql );
2297 }
2298 }
2299
2300 $id = $this->getID();
2301 $title = $this->mTitle->getPrefixedDBkey();
2302 $shortTitle = $this->mTitle->getDBkey();
2303
2304 if ( 0 == $id ) {
2305 wfProfileOut( $fname );
2306 return;
2307 }
2308
2309 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2310 array_push( $wgDeferredUpdateList, $u );
2311 $u = new SearchUpdate( $id, $title, $text );
2312 array_push( $wgDeferredUpdateList, $u );
2313
2314 # If this is another user's talk page, update newtalk
2315
2316 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2317 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2318 $other = User::newFromName( $shortTitle );
2319 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2320 // An anonymous user
2321 $other = new User();
2322 $other->setName( $shortTitle );
2323 }
2324 if( $other ) {
2325 $other->setNewtalk( true );
2326 }
2327 }
2328 }
2329
2330 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2331 $wgMessageCache->replace( $shortTitle, $text );
2332 }
2333
2334 wfProfileOut( $fname );
2335 }
2336
2337 /**
2338 * Generate the navigation links when browsing through an article revisions
2339 * It shows the information as:
2340 * Revision as of \<date\>; view current revision
2341 * \<- Previous version | Next Version -\>
2342 *
2343 * @private
2344 * @param string $oldid Revision ID of this article revision
2345 */
2346 function setOldSubtitle( $oldid=0 ) {
2347 global $wgLang, $wgOut, $wgUser;
2348
2349 $current = ( $oldid == $this->mLatest );
2350 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2351 $sk = $wgUser->getSkin();
2352 $lnk = $current
2353 ? wfMsg( 'currentrevisionlink' )
2354 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2355 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2356 $prevlink = $prev
2357 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2358 : wfMsg( 'previousrevision' );
2359 $nextlink = $current
2360 ? wfMsg( 'nextrevision' )
2361 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2362 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2363 $wgOut->setSubtitle( $r );
2364 }
2365
2366 /**
2367 * This function is called right before saving the wikitext,
2368 * so we can do things like signatures and links-in-context.
2369 *
2370 * @param string $text
2371 */
2372 function preSaveTransform( $text ) {
2373 global $wgParser, $wgUser;
2374 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2375 }
2376
2377 /* Caching functions */
2378
2379 /**
2380 * checkLastModified returns true if it has taken care of all
2381 * output to the client that is necessary for this request.
2382 * (that is, it has sent a cached version of the page)
2383 */
2384 function tryFileCache() {
2385 static $called = false;
2386 if( $called ) {
2387 wfDebug( " tryFileCache() -- called twice!?\n" );
2388 return;
2389 }
2390 $called = true;
2391 if($this->isFileCacheable()) {
2392 $touched = $this->mTouched;
2393 $cache = new CacheManager( $this->mTitle );
2394 if($cache->isFileCacheGood( $touched )) {
2395 wfDebug( " tryFileCache() - about to load\n" );
2396 $cache->loadFromFileCache();
2397 return true;
2398 } else {
2399 wfDebug( " tryFileCache() - starting buffer\n" );
2400 ob_start( array(&$cache, 'saveToFileCache' ) );
2401 }
2402 } else {
2403 wfDebug( " tryFileCache() - not cacheable\n" );
2404 }
2405 }
2406
2407 /**
2408 * Check if the page can be cached
2409 * @return bool
2410 */
2411 function isFileCacheable() {
2412 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2413 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2414
2415 return $wgUseFileCache
2416 and (!$wgShowIPinHeader)
2417 and ($this->getID() != 0)
2418 and ($wgUser->isAnon())
2419 and (!$wgUser->getNewtalk())
2420 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2421 and (empty( $action ) || $action == 'view')
2422 and (!isset($oldid))
2423 and (!isset($diff))
2424 and (!isset($redirect))
2425 and (!isset($printable))
2426 and (!$this->mRedirectedFrom);
2427 }
2428
2429 /**
2430 * Loads page_touched and returns a value indicating if it should be used
2431 *
2432 */
2433 function checkTouched() {
2434 $fname = 'Article::checkTouched';
2435 if( !$this->mDataLoaded ) {
2436 $this->loadPageData();
2437 }
2438 return !$this->mIsRedirect;
2439 }
2440
2441 /**
2442 * Get the page_touched field
2443 */
2444 function getTouched() {
2445 # Ensure that page data has been loaded
2446 if( !$this->mDataLoaded ) {
2447 $this->loadPageData();
2448 }
2449 return $this->mTouched;
2450 }
2451
2452 /**
2453 * Get the page_latest field
2454 */
2455 function getLatest() {
2456 if ( !$this->mDataLoaded ) {
2457 $this->loadPageData();
2458 }
2459 return $this->mLatest;
2460 }
2461
2462 /**
2463 * Edit an article without doing all that other stuff
2464 * The article must already exist; link tables etc
2465 * are not updated, caches are not flushed.
2466 *
2467 * @param string $text text submitted
2468 * @param string $comment comment submitted
2469 * @param bool $minor whereas it's a minor modification
2470 */
2471 function quickEdit( $text, $comment = '', $minor = 0 ) {
2472 $fname = 'Article::quickEdit';
2473 wfProfileIn( $fname );
2474
2475 $dbw =& wfGetDB( DB_MASTER );
2476 $dbw->begin();
2477 $revision = new Revision( array(
2478 'page' => $this->getId(),
2479 'text' => $text,
2480 'comment' => $comment,
2481 'minor_edit' => $minor ? 1 : 0,
2482 ) );
2483 # fixme : $revisionId never used
2484 $revisionId = $revision->insertOn( $dbw );
2485 $this->updateRevisionOn( $dbw, $revision );
2486 $dbw->commit();
2487
2488 wfProfileOut( $fname );
2489 }
2490
2491 /**
2492 * Used to increment the view counter
2493 *
2494 * @static
2495 * @param integer $id article id
2496 */
2497 function incViewCount( $id ) {
2498 $id = intval( $id );
2499 global $wgHitcounterUpdateFreq, $wgDBtype;
2500
2501 $dbw =& wfGetDB( DB_MASTER );
2502 $pageTable = $dbw->tableName( 'page' );
2503 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2504 $acchitsTable = $dbw->tableName( 'acchits' );
2505
2506 if( $wgHitcounterUpdateFreq <= 1 ){ //
2507 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2508 return;
2509 }
2510
2511 # Not important enough to warrant an error page in case of failure
2512 $oldignore = $dbw->ignoreErrors( true );
2513
2514 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2515
2516 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2517 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2518 # Most of the time (or on SQL errors), skip row count check
2519 $dbw->ignoreErrors( $oldignore );
2520 return;
2521 }
2522
2523 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2524 $row = $dbw->fetchObject( $res );
2525 $rown = intval( $row->n );
2526 if( $rown >= $wgHitcounterUpdateFreq ){
2527 wfProfileIn( 'Article::incViewCount-collect' );
2528 $old_user_abort = ignore_user_abort( true );
2529
2530 if ($wgDBtype == 'mysql')
2531 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2532 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2533 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2534 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2535 'GROUP BY hc_id');
2536 $dbw->query("DELETE FROM $hitcounterTable");
2537 if ($wgDBtype == 'mysql')
2538 $dbw->query('UNLOCK TABLES');
2539 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2540 'WHERE page_id = hc_id');
2541 $dbw->query("DROP TABLE $acchitsTable");
2542
2543 ignore_user_abort( $old_user_abort );
2544 wfProfileOut( 'Article::incViewCount-collect' );
2545 }
2546 $dbw->ignoreErrors( $oldignore );
2547 }
2548
2549 /**#@+
2550 * The onArticle*() functions are supposed to be a kind of hooks
2551 * which should be called whenever any of the specified actions
2552 * are done.
2553 *
2554 * This is a good place to put code to clear caches, for instance.
2555 *
2556 * This is called on page move and undelete, as well as edit
2557 * @static
2558 * @param $title_obj a title object
2559 */
2560
2561 function onArticleCreate($title_obj) {
2562 global $wgUseSquid, $wgPostCommitUpdateList;
2563
2564 $title_obj->touchLinks();
2565 $titles = $title_obj->getLinksTo();
2566
2567 # Purge squid
2568 if ( $wgUseSquid ) {
2569 $urls = $title_obj->getSquidURLs();
2570 foreach ( $titles as $linkTitle ) {
2571 $urls[] = $linkTitle->getInternalURL();
2572 }
2573 $u = new SquidUpdate( $urls );
2574 array_push( $wgPostCommitUpdateList, $u );
2575 }
2576 }
2577
2578 function onArticleDelete( $title ) {
2579 global $wgMessageCache;
2580
2581 $title->touchLinks();
2582
2583 if( $title->getNamespace() == NS_MEDIAWIKI) {
2584 $wgMessageCache->replace( $title->getDBkey(), false );
2585 }
2586 }
2587
2588 /**
2589 * Purge caches on page update etc
2590 */
2591 function onArticleEdit( $title ) {
2592 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2593
2594 $urls = array();
2595
2596 // Template namespace? Purge all articles linking here.
2597 // FIXME: When a templatelinks table arrives, use it for all includes.
2598 if ( $title->getNamespace() == NS_TEMPLATE) {
2599 $titles = $title->getLinksTo();
2600 Title::touchArray( $titles );
2601 if ( $wgUseSquid ) {
2602 foreach ( $titles as $link ) {
2603 $urls[] = $link->getInternalURL();
2604 }
2605 }
2606 }
2607
2608 # Squid updates
2609 if ( $wgUseSquid ) {
2610 $urls = array_merge( $urls, $title->getSquidURLs() );
2611 $u = new SquidUpdate( $urls );
2612 array_push( $wgPostCommitUpdateList, $u );
2613 }
2614
2615 # File cache
2616 if ( $wgUseFileCache ) {
2617 $cm = new CacheManager( $title );
2618 @unlink( $cm->fileCacheName() );
2619 }
2620 }
2621
2622 /**#@-*/
2623
2624 /**
2625 * Info about this page
2626 * Called for ?action=info when $wgAllowPageInfo is on.
2627 *
2628 * @public
2629 */
2630 function info() {
2631 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2632 $fname = 'Article::info';
2633
2634 if ( !$wgAllowPageInfo ) {
2635 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2636 return;
2637 }
2638
2639 $page = $this->mTitle->getSubjectPage();
2640
2641 $wgOut->setPagetitle( $page->getPrefixedText() );
2642 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2643
2644 # first, see if the page exists at all.
2645 $exists = $page->getArticleId() != 0;
2646 if( !$exists ) {
2647 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2648 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2649 } else {
2650 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2651 }
2652 } else {
2653 $dbr =& wfGetDB( DB_SLAVE );
2654 $wl_clause = array(
2655 'wl_title' => $page->getDBkey(),
2656 'wl_namespace' => $page->getNamespace() );
2657 $numwatchers = $dbr->selectField(
2658 'watchlist',
2659 'COUNT(*)',
2660 $wl_clause,
2661 $fname,
2662 $this->getSelectOptions() );
2663
2664 $pageInfo = $this->pageCountInfo( $page );
2665 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2666
2667 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2668 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2669 if( $talkInfo ) {
2670 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2671 }
2672 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2673 if( $talkInfo ) {
2674 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2675 }
2676 $wgOut->addHTML( '</ul>' );
2677
2678 }
2679 }
2680
2681 /**
2682 * Return the total number of edits and number of unique editors
2683 * on a given page. If page does not exist, returns false.
2684 *
2685 * @param Title $title
2686 * @return array
2687 * @private
2688 */
2689 function pageCountInfo( $title ) {
2690 $id = $title->getArticleId();
2691 if( $id == 0 ) {
2692 return false;
2693 }
2694
2695 $dbr =& wfGetDB( DB_SLAVE );
2696
2697 $rev_clause = array( 'rev_page' => $id );
2698 $fname = 'Article::pageCountInfo';
2699
2700 $edits = $dbr->selectField(
2701 'revision',
2702 'COUNT(rev_page)',
2703 $rev_clause,
2704 $fname,
2705 $this->getSelectOptions() );
2706
2707 $authors = $dbr->selectField(
2708 'revision',
2709 'COUNT(DISTINCT rev_user_text)',
2710 $rev_clause,
2711 $fname,
2712 $this->getSelectOptions() );
2713
2714 return array( 'edits' => $edits, 'authors' => $authors );
2715 }
2716
2717 /**
2718 * Return a list of templates used by this article.
2719 * Uses the templatelinks table
2720 *
2721 * @return array Array of Title objects
2722 */
2723 function getUsedTemplates() {
2724 $result = array();
2725 $id = $this->mTitle->getArticleID();
2726 if( $id == 0 ) {
2727 return array();
2728 }
2729
2730 $dbr =& wfGetDB( DB_SLAVE );
2731 $res = $dbr->select( array( 'templatelinks' ),
2732 array( 'tl_namespace', 'tl_title' ),
2733 array( 'tl_from' => $id ),
2734 'Article:getUsedTemplates' );
2735 if ( false !== $res ) {
2736 if ( $dbr->numRows( $res ) ) {
2737 while ( $row = $dbr->fetchObject( $res ) ) {
2738 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2739 }
2740 }
2741 }
2742 $dbr->freeResult( $res );
2743 return $result;
2744 }
2745 }
2746
2747 ?>