Revert to r14165 . Did too many changes, didnt even run parserTests (i am bad)
[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 if( !$wasRedirected ) {
897 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
898 }
899 $targetUrl = $rt->escapeLocalURL();
900 # fixme unused $titleText :
901 $titleText = htmlspecialchars( $rt->getPrefixedText() );
902 $link = $sk->makeLinkObj( $rt );
903
904 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
905 '<span class="redirectText">'.$link.'</span>' );
906
907 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
908 $wgOut->addParserOutputNoText( $parseout );
909 } else if ( $pcache ) {
910 # Display content and save to parser cache
911 $wgOut->addPrimaryWikiText( $text, $this );
912 } else {
913 # Display content, don't attempt to save to parser cache
914
915 # Don't show section-edit links on old revisions... this way lies madness.
916 if( !$this->isCurrent() ) {
917 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
918 }
919 # Display content and don't save to parser cache
920 $wgOut->addPrimaryWikiText( $text, $this, false );
921
922 if( !$this->isCurrent() ) {
923 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
924 }
925 }
926 }
927 /* title may have been set from the cache */
928 $t = $wgOut->getPageTitle();
929 if( empty( $t ) ) {
930 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
931 }
932
933 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
934 if( $this->mTitle->getNamespace() == NS_USER_TALK &&
935 User::isIP( $this->mTitle->getText() ) ) {
936 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
937 }
938
939 # If we have been passed an &rcid= parameter, we want to give the user a
940 # chance to mark this new article as patrolled.
941 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
942 $wgOut->addHTML(
943 "<div class='patrollink'>" .
944 wfMsg ( 'markaspatrolledlink',
945 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
946 ) .
947 '</div>'
948 );
949 }
950
951 # Trackbacks
952 if ($wgUseTrackbacks)
953 $this->addTrackbacks();
954
955 $this->viewUpdates();
956 wfProfileOut( $fname );
957 }
958
959 function addTrackbacks() {
960 global $wgOut, $wgUser;
961
962 $dbr =& wfGetDB(DB_SLAVE);
963 $tbs = $dbr->select(
964 /* FROM */ 'trackbacks',
965 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
966 /* WHERE */ array('tb_page' => $this->getID())
967 );
968
969 if (!$dbr->numrows($tbs))
970 return;
971
972 $tbtext = "";
973 while ($o = $dbr->fetchObject($tbs)) {
974 $rmvtxt = "";
975 if ($wgUser->isAllowed( 'trackback' )) {
976 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
977 . $o->tb_id . "&token=" . $wgUser->editToken());
978 $rmvtxt = wfMsg('trackbackremove', $delurl);
979 }
980 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
981 $o->tb_title,
982 $o->tb_url,
983 $o->tb_ex,
984 $o->tb_name,
985 $rmvtxt);
986 }
987 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
988 }
989
990 function deletetrackback() {
991 global $wgUser, $wgRequest, $wgOut, $wgTitle;
992
993 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
994 $wgOut->addWikitext(wfMsg('sessionfailure'));
995 return;
996 }
997
998 if ((!$wgUser->isAllowed('delete'))) {
999 $wgOut->sysopRequired();
1000 return;
1001 }
1002
1003 if (wfReadOnly()) {
1004 $wgOut->readOnlyPage();
1005 return;
1006 }
1007
1008 $db =& wfGetDB(DB_MASTER);
1009 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1010 $wgTitle->invalidateCache();
1011 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1012 }
1013
1014 function render() {
1015 global $wgOut;
1016
1017 $wgOut->setArticleBodyOnly(true);
1018 $this->view();
1019 }
1020
1021 /**
1022 * Handle action=purge
1023 */
1024 function purge() {
1025 global $wgUser, $wgRequest, $wgOut;
1026
1027 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
1028 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1029 $this->doPurge();
1030 }
1031 } else {
1032 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1033 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
1034 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1035 $msg = str_replace( '$1',
1036 "<form method=\"post\" action=\"$action\">\n" .
1037 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1038 "</form>\n", $msg );
1039
1040 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1041 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1042 $wgOut->addHTML( $msg );
1043 }
1044 }
1045
1046 /**
1047 * Perform the actions of a page purging
1048 */
1049 function doPurge() {
1050 global $wgUseSquid;
1051 // Invalidate the cache
1052 $this->mTitle->invalidateCache();
1053
1054 if ( $wgUseSquid ) {
1055 // Commit the transaction before the purge is sent
1056 $dbw = wfGetDB( DB_MASTER );
1057 $dbw->immediateCommit();
1058
1059 // Send purge
1060 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1061 $update->doUpdate();
1062 }
1063 $this->view();
1064 }
1065
1066 /**
1067 * Insert a new empty page record for this article.
1068 * This *must* be followed up by creating a revision
1069 * and running $this->updateToLatest( $rev_id );
1070 * or else the record will be left in a funky state.
1071 * Best if all done inside a transaction.
1072 *
1073 * @param Database $dbw
1074 * @param string $restrictions
1075 * @return int The newly created page_id key
1076 * @private
1077 */
1078 function insertOn( &$dbw, $restrictions = '' ) {
1079 $fname = 'Article::insertOn';
1080 wfProfileIn( $fname );
1081
1082 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1083 $dbw->insert( 'page', array(
1084 'page_id' => $page_id,
1085 'page_namespace' => $this->mTitle->getNamespace(),
1086 'page_title' => $this->mTitle->getDBkey(),
1087 'page_counter' => 0,
1088 'page_restrictions' => $restrictions,
1089 'page_is_redirect' => 0, # Will set this shortly...
1090 'page_is_new' => 1,
1091 'page_random' => wfRandom(),
1092 'page_touched' => $dbw->timestamp(),
1093 'page_latest' => 0, # Fill this in shortly...
1094 'page_len' => 0, # Fill this in shortly...
1095 ), $fname );
1096 $newid = $dbw->insertId();
1097
1098 $this->mTitle->resetArticleId( $newid );
1099
1100 wfProfileOut( $fname );
1101 return $newid;
1102 }
1103
1104 /**
1105 * Update the page record to point to a newly saved revision.
1106 *
1107 * @param Database $dbw
1108 * @param Revision $revision For ID number, and text used to set
1109 length and redirect status fields
1110 * @param int $lastRevision If given, will not overwrite the page field
1111 * when different from the currently set value.
1112 * Giving 0 indicates the new page flag should
1113 * be set on.
1114 * @return bool true on success, false on failure
1115 * @private
1116 */
1117 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1118 $fname = 'Article::updateToRevision';
1119 wfProfileIn( $fname );
1120
1121 $conditions = array( 'page_id' => $this->getId() );
1122 if( !is_null( $lastRevision ) ) {
1123 # An extra check against threads stepping on each other
1124 $conditions['page_latest'] = $lastRevision;
1125 }
1126
1127 $text = $revision->getText();
1128 $dbw->update( 'page',
1129 array( /* SET */
1130 'page_latest' => $revision->getId(),
1131 'page_touched' => $dbw->timestamp(),
1132 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1133 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1134 'page_len' => strlen( $text ),
1135 ),
1136 $conditions,
1137 $fname );
1138
1139 wfProfileOut( $fname );
1140 return ( $dbw->affectedRows() != 0 );
1141 }
1142
1143 /**
1144 * If the given revision is newer than the currently set page_latest,
1145 * update the page record. Otherwise, do nothing.
1146 *
1147 * @param Database $dbw
1148 * @param Revision $revision
1149 */
1150 function updateIfNewerOn( &$dbw, $revision ) {
1151 $fname = 'Article::updateIfNewerOn';
1152 wfProfileIn( $fname );
1153
1154 $row = $dbw->selectRow(
1155 array( 'revision', 'page' ),
1156 array( 'rev_id', 'rev_timestamp' ),
1157 array(
1158 'page_id' => $this->getId(),
1159 'page_latest=rev_id' ),
1160 $fname );
1161 if( $row ) {
1162 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1163 wfProfileOut( $fname );
1164 return false;
1165 }
1166 $prev = $row->rev_id;
1167 } else {
1168 # No or missing previous revision; mark the page as new
1169 $prev = 0;
1170 }
1171
1172 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1173 wfProfileOut( $fname );
1174 return $ret;
1175 }
1176
1177 /**
1178 * Insert a new article into the database
1179 * @private
1180 */
1181 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1182 global $wgUser;
1183
1184 $fname = 'Article::insertNewArticle';
1185 wfProfileIn( $fname );
1186
1187 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1188 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1189 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1190 wfProfileOut( $fname );
1191 return false;
1192 }
1193
1194 $ns = $this->mTitle->getNamespace();
1195 $ttl = $this->mTitle->getDBkey();
1196
1197 # If this is a comment, add the summary as headline
1198 if($comment && $summary!="") {
1199 $text="== {$summary} ==\n\n".$text;
1200 }
1201 $text = $this->preSaveTransform( $text );
1202
1203
1204 # Set statistics members
1205 # We work out if it's countable after PST to avoid counter drift
1206 # when articles are created with {{subst:}}
1207 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1208 $this->mTotalAdjustment = 1;
1209
1210 /* Silently ignore minoredit if not allowed */
1211 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1212 $now = wfTimestampNow();
1213
1214 $dbw =& wfGetDB( DB_MASTER );
1215
1216 # Add the page record; stake our claim on this title!
1217 $newid = $this->insertOn( $dbw );
1218
1219 # Save the revision text...
1220 $revision = new Revision( array(
1221 'page' => $newid,
1222 'comment' => $summary,
1223 'minor_edit' => $isminor,
1224 'text' => $text
1225 ) );
1226 $revisionId = $revision->insertOn( $dbw );
1227
1228 $this->mTitle->resetArticleID( $newid );
1229
1230 # Update the page record with revision data
1231 $this->updateRevisionOn( $dbw, $revision, 0 );
1232
1233 Article::onArticleCreate( $this->mTitle );
1234 if(!$suppressRC) {
1235 require_once( 'RecentChange.php' );
1236 $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1237 '', strlen( $text ), $revisionId );
1238 # Mark as patrolled if the user can and has the option set
1239 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1240 RecentChange::markPatrolled( $rcid );
1241 }
1242 }
1243
1244 if ($watchthis) {
1245 if(!$this->mTitle->userIsWatching()) $this->doWatch();
1246 } else {
1247 if ( $this->mTitle->userIsWatching() ) {
1248 $this->doUnwatch();
1249 }
1250 }
1251
1252 # The talk page isn't in the regular link tables, so we need to update manually:
1253 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1254 $dbw->update( 'page',
1255 array( 'page_touched' => $dbw->timestamp($now) ),
1256 array( 'page_namespace' => $talkns,
1257 'page_title' => $ttl ),
1258 $fname );
1259
1260 # standard deferred updates
1261 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1262
1263 $oldid = 0; # new article
1264 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1265
1266 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1267 $summary, $isminor,
1268 $watchthis, NULL ) );
1269 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1270 $summary, $isminor,
1271 $watchthis, NULL ) );
1272 wfProfileOut( $fname );
1273 }
1274
1275 /**
1276 * @return string Complete article text, or null if error
1277 */
1278 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1279 $fname = 'Article::replaceSection';
1280 wfProfileIn( $fname );
1281
1282 if ($section != '') {
1283 if( is_null( $edittime ) ) {
1284 $rev = Revision::newFromTitle( $this->mTitle );
1285 } else {
1286 $dbw =& wfGetDB( DB_MASTER );
1287 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1288 }
1289 if( is_null( $rev ) ) {
1290 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1291 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1292 return null;
1293 }
1294 $oldtext = $rev->getText();
1295
1296 if($section=='new') {
1297 if($summary) $subject="== {$summary} ==\n\n";
1298 $text=$oldtext."\n\n".$subject.$text;
1299 } else {
1300
1301 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1302 # comments to be stripped as well)
1303 $striparray=array();
1304 $parser=new Parser();
1305 $parser->mOutputType=OT_WIKI;
1306 $parser->mOptions = new ParserOptions();
1307 $oldtext=$parser->strip($oldtext, $striparray, true);
1308
1309 # now that we can be sure that no pseudo-sections are in the source,
1310 # split it up
1311 # Unfortunately we can't simply do a preg_replace because that might
1312 # replace the wrong section, so we have to use the section counter instead
1313 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1314 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1315 $secs[$section*2]=$text."\n\n"; // replace with edited
1316
1317 # section 0 is top (intro) section
1318 if($section!=0) {
1319
1320 # headline of old section - we need to go through this section
1321 # to determine if there are any subsections that now need to
1322 # be erased, as the mother section has been replaced with
1323 # the text of all subsections.
1324 $headline=$secs[$section*2-1];
1325 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1326 $hlevel=$matches[1];
1327
1328 # determine headline level for wikimarkup headings
1329 if(strpos($hlevel,'=')!==false) {
1330 $hlevel=strlen($hlevel);
1331 }
1332
1333 $secs[$section*2-1]=''; // erase old headline
1334 $count=$section+1;
1335 $break=false;
1336 while(!empty($secs[$count*2-1]) && !$break) {
1337
1338 $subheadline=$secs[$count*2-1];
1339 preg_match(
1340 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1341 $subhlevel=$matches[1];
1342 if(strpos($subhlevel,'=')!==false) {
1343 $subhlevel=strlen($subhlevel);
1344 }
1345 if($subhlevel > $hlevel) {
1346 // erase old subsections
1347 $secs[$count*2-1]='';
1348 $secs[$count*2]='';
1349 }
1350 if($subhlevel <= $hlevel) {
1351 $break=true;
1352 }
1353 $count++;
1354
1355 }
1356
1357 }
1358 $text=join('',$secs);
1359 # reinsert the stuff that we stripped out earlier
1360 $text=$parser->unstrip($text,$striparray);
1361 $text=$parser->unstripNoWiki($text,$striparray);
1362 }
1363
1364 }
1365 wfProfileOut( $fname );
1366 return $text;
1367 }
1368
1369 /**
1370 * Change an existing article. Puts the previous version back into the old table, updates RC
1371 * and all necessary caches, mostly via the deferred update array.
1372 *
1373 * It is possible to call this function from a command-line script, but note that you should
1374 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1375 */
1376 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1377 global $wgUser, $wgDBtransactions, $wgUseSquid;
1378 global $wgPostCommitUpdateList, $wgUseFileCache;
1379
1380 $fname = 'Article::updateArticle';
1381 wfProfileIn( $fname );
1382 $good = true;
1383
1384 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1385 &$summary, &$minor,
1386 &$watchthis, &$sectionanchor ) ) ) {
1387 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1388 wfProfileOut( $fname );
1389 return false;
1390 }
1391
1392 $isminor = $minor && $wgUser->isAllowed('minoredit');
1393
1394 $text = $this->preSaveTransform( $text );
1395 $dbw =& wfGetDB( DB_MASTER );
1396 $now = wfTimestampNow();
1397
1398 # Update article, but only if changed.
1399
1400 # It's important that we either rollback or complete, otherwise an attacker could
1401 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1402 # could conceivably have the same effect, especially if cur is locked for long periods.
1403 if( !$wgDBtransactions ) {
1404 $userAbort = ignore_user_abort( true );
1405 }
1406
1407 $oldtext = $this->getContent();
1408 $oldsize = strlen( $oldtext );
1409 $newsize = strlen( $text );
1410 $lastRevision = 0;
1411 $revisionId = 0;
1412
1413 if ( 0 != strcmp( $text, $oldtext ) ) {
1414 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1415 - (int)$this->isCountable( $oldtext );
1416 $this->mTotalAdjustment = 0;
1417 $now = wfTimestampNow();
1418
1419 $lastRevision = $dbw->selectField(
1420 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1421
1422 $revision = new Revision( array(
1423 'page' => $this->getId(),
1424 'comment' => $summary,
1425 'minor_edit' => $isminor,
1426 'text' => $text
1427 ) );
1428
1429 $dbw->immediateCommit();
1430 $dbw->begin();
1431 $revisionId = $revision->insertOn( $dbw );
1432
1433 # Update page
1434 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1435
1436 if( !$ok ) {
1437 /* Belated edit conflict! Run away!! */
1438 $good = false;
1439 $dbw->rollback();
1440 } else {
1441 # Update recentchanges and purge cache and whatnot
1442 require_once( 'RecentChange.php' );
1443 $bot = (int)($wgUser->isBot() || $forceBot);
1444 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1445 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1446 $revisionId );
1447
1448 # Mark as patrolled if the user can do so and has it set in their options
1449 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1450 RecentChange::markPatrolled( $rcid );
1451 }
1452
1453 $dbw->commit();
1454
1455 // Update caches outside the main transaction
1456 Article::onArticleEdit( $this->mTitle );
1457 }
1458 } else {
1459 // Keep the same revision ID, but do some updates on it
1460 $revisionId = $this->getRevIdFetched();
1461 }
1462
1463 if( !$wgDBtransactions ) {
1464 ignore_user_abort( $userAbort );
1465 }
1466
1467 if ( $good ) {
1468 if ($watchthis) {
1469 if (!$this->mTitle->userIsWatching()) {
1470 $dbw->immediateCommit();
1471 $dbw->begin();
1472 $this->doWatch();
1473 $dbw->commit();
1474 }
1475 } else {
1476 if ( $this->mTitle->userIsWatching() ) {
1477 $dbw->immediateCommit();
1478 $dbw->begin();
1479 $this->doUnwatch();
1480 $dbw->commit();
1481 }
1482 }
1483 # standard deferred updates
1484 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1485
1486
1487 $urls = array();
1488 # Invalidate caches of all articles using this article as a template
1489
1490 # Template namespace
1491 # Purge all articles linking here
1492 $titles = $this->mTitle->getTemplateLinksTo();
1493 Title::touchArray( $titles );
1494 if ( $wgUseSquid ) {
1495 foreach ( $titles as $title ) {
1496 $urls[] = $title->getInternalURL();
1497 }
1498 }
1499
1500 # Squid updates
1501 if ( $wgUseSquid ) {
1502 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1503 $u = new SquidUpdate( $urls );
1504 array_push( $wgPostCommitUpdateList, $u );
1505 }
1506
1507 # File cache
1508 if ( $wgUseFileCache ) {
1509 $cm = new CacheManager($this->mTitle);
1510 @unlink($cm->fileCacheName());
1511 }
1512
1513 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1514 }
1515 wfRunHooks( 'ArticleSaveComplete',
1516 array( &$this, &$wgUser, $text,
1517 $summary, $minor,
1518 $watchthis, $sectionanchor ) );
1519 wfProfileOut( $fname );
1520 return $good;
1521 }
1522
1523 /**
1524 * After we've either updated or inserted the article, update
1525 * the link tables and redirect to the new page.
1526 * @todo FIXME some function arguments never used
1527 */
1528 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1529 global $wgOut;
1530
1531 $fname = 'Article::showArticle';
1532 wfProfileIn( $fname );
1533
1534 # Output the redirect
1535 if( $this->isRedirect( $text ) )
1536 $r = 'redirect=no';
1537 else
1538 $r = '';
1539 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1540
1541 wfProfileOut( $fname );
1542 }
1543
1544 /**
1545 * Mark this particular edit as patrolled
1546 */
1547 function markpatrolled() {
1548 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1549 $wgOut->setRobotpolicy( 'noindex,follow' );
1550
1551 # Check RC patrol config. option
1552 if( !$wgUseRCPatrol ) {
1553 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1554 return;
1555 }
1556
1557 # Check permissions
1558 if( !$wgUser->isAllowed( 'patrol' ) ) {
1559 $wgOut->permissionRequired( 'patrol' );
1560 return;
1561 }
1562
1563 $rcid = $wgRequest->getVal( 'rcid' );
1564 if ( !is_null ( $rcid ) ) {
1565 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1566 require_once( 'RecentChange.php' );
1567 RecentChange::markPatrolled( $rcid );
1568 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1569 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1570 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1571 }
1572 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1573 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1574 }
1575 else {
1576 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1577 }
1578 }
1579
1580 /**
1581 * User-interface handler for the "watch" action
1582 */
1583
1584 function watch() {
1585
1586 global $wgUser, $wgOut;
1587
1588 if ( $wgUser->isAnon() ) {
1589 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1590 return;
1591 }
1592 if ( wfReadOnly() ) {
1593 $wgOut->readOnlyPage();
1594 return;
1595 }
1596
1597 if( $this->doWatch() ) {
1598 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1599 $wgOut->setRobotpolicy( 'noindex,follow' );
1600
1601 $link = $this->mTitle->getPrefixedText();
1602 $text = wfMsg( 'addedwatchtext', $link );
1603 $wgOut->addWikiText( $text );
1604 }
1605
1606 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1607 }
1608
1609 /**
1610 * Add this page to $wgUser's watchlist
1611 * @return bool true on successful watch operation
1612 */
1613 function doWatch() {
1614 global $wgUser;
1615 if( $wgUser->isAnon() ) {
1616 return false;
1617 }
1618
1619 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1620 $wgUser->addWatch( $this->mTitle );
1621 $wgUser->saveSettings();
1622
1623 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1624 }
1625
1626 return false;
1627 }
1628
1629 /**
1630 * User interface handler for the "unwatch" action.
1631 */
1632 function unwatch() {
1633
1634 global $wgUser, $wgOut;
1635
1636 if ( $wgUser->isAnon() ) {
1637 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1638 return;
1639 }
1640 if ( wfReadOnly() ) {
1641 $wgOut->readOnlyPage();
1642 return;
1643 }
1644
1645 if( $this->doUnwatch() ) {
1646 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1647 $wgOut->setRobotpolicy( 'noindex,follow' );
1648
1649 $link = $this->mTitle->getPrefixedText();
1650 $text = wfMsg( 'removedwatchtext', $link );
1651 $wgOut->addWikiText( $text );
1652 }
1653
1654 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1655 }
1656
1657 /**
1658 * Stop watching a page
1659 * @return bool true on successful unwatch
1660 */
1661 function doUnwatch() {
1662 global $wgUser;
1663 if( $wgUser->isAnon() ) {
1664 return false;
1665 }
1666
1667 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1668 $wgUser->removeWatch( $this->mTitle );
1669 $wgUser->saveSettings();
1670
1671 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1672 }
1673
1674 return false;
1675 }
1676
1677 /**
1678 * action=protect handler
1679 */
1680 function protect() {
1681 require_once 'ProtectionForm.php';
1682 $form = new ProtectionForm( $this );
1683 $form->show();
1684 }
1685
1686 /**
1687 * action=unprotect handler (alias)
1688 */
1689 function unprotect() {
1690 $this->protect();
1691 }
1692
1693 /**
1694 * Update the article's restriction field, and leave a log entry.
1695 *
1696 * @param array $limit set of restriction keys
1697 * @param string $reason
1698 * @return bool true on success
1699 */
1700 function updateRestrictions( $limit = array(), $reason = '' ) {
1701 global $wgUser, $wgRestrictionTypes, $wgContLang;
1702
1703 $id = $this->mTitle->getArticleID();
1704 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1705 return false;
1706 }
1707
1708 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1709 # we expect a single selection, but the schema allows otherwise.
1710 $current = array();
1711 foreach( $wgRestrictionTypes as $action )
1712 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1713
1714 $current = Article::flattenRestrictions( $current );
1715 $updated = Article::flattenRestrictions( $limit );
1716
1717 $changed = ( $current != $updated );
1718 $protect = ( $updated != '' );
1719
1720 # If nothing's changed, do nothing
1721 if( $changed ) {
1722 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1723
1724 $dbw =& wfGetDB( DB_MASTER );
1725
1726 # Prepare a null revision to be added to the history
1727 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1728 if( $reason )
1729 $comment .= ": $reason";
1730 if( $protect )
1731 $comment .= " [$updated]";
1732 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1733 $nullRevId = $nullRevision->insertOn( $dbw );
1734
1735 # Update page record
1736 $dbw->update( 'page',
1737 array( /* SET */
1738 'page_touched' => $dbw->timestamp(),
1739 'page_restrictions' => $updated,
1740 'page_latest' => $nullRevId
1741 ), array( /* WHERE */
1742 'page_id' => $id
1743 ), 'Article::protect'
1744 );
1745 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1746
1747 # Update the protection log
1748 $log = new LogPage( 'protect' );
1749 if( $protect ) {
1750 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1751 } else {
1752 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1753 }
1754
1755 } # End hook
1756 } # End "changed" check
1757
1758 return true;
1759 }
1760
1761 /**
1762 * Take an array of page restrictions and flatten it to a string
1763 * suitable for insertion into the page_restrictions field.
1764 * @param array $limit
1765 * @return string
1766 * @private
1767 */
1768 function flattenRestrictions( $limit ) {
1769 if( !is_array( $limit ) ) {
1770 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1771 }
1772 $bits = array();
1773 ksort( $limit );
1774 foreach( $limit as $action => $restrictions ) {
1775 if( $restrictions != '' ) {
1776 $bits[] = "$action=$restrictions";
1777 }
1778 }
1779 return implode( ':', $bits );
1780 }
1781
1782 /*
1783 * UI entry point for page deletion
1784 */
1785 function delete() {
1786 global $wgUser, $wgOut, $wgRequest;
1787 $fname = 'Article::delete';
1788 $confirm = $wgRequest->wasPosted() &&
1789 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1790 $reason = $wgRequest->getText( 'wpReason' );
1791
1792 # This code desperately needs to be totally rewritten
1793
1794 # Check permissions
1795 if( $wgUser->isAllowed( 'delete' ) ) {
1796 if( $wgUser->isBlocked() ) {
1797 $wgOut->blockedPage();
1798 return;
1799 }
1800 } else {
1801 $wgOut->permissionRequired( 'delete' );
1802 return;
1803 }
1804
1805 if( wfReadOnly() ) {
1806 $wgOut->readOnlyPage();
1807 return;
1808 }
1809
1810 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1811
1812 # Better double-check that it hasn't been deleted yet!
1813 $dbw =& wfGetDB( DB_MASTER );
1814 $conds = $this->mTitle->pageCond();
1815 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1816 if ( $latest === false ) {
1817 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1818 return;
1819 }
1820
1821 if( $confirm ) {
1822 $this->doDelete( $reason );
1823 return;
1824 }
1825
1826 # determine whether this page has earlier revisions
1827 # and insert a warning if it does
1828 $maxRevisions = 20;
1829 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1830
1831 if( count( $authors ) > 1 && !$confirm ) {
1832 $skin=$wgUser->getSkin();
1833 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1834 }
1835
1836 # If a single user is responsible for all revisions, find out who they are
1837 if ( count( $authors ) == $maxRevisions ) {
1838 // Query bailed out, too many revisions to find out if they're all the same
1839 $authorOfAll = false;
1840 } else {
1841 $authorOfAll = reset( $authors );
1842 foreach ( $authors as $author ) {
1843 if ( $authorOfAll != $author ) {
1844 $authorOfAll = false;
1845 break;
1846 }
1847 }
1848 }
1849 # Fetch article text
1850 $rev = Revision::newFromTitle( $this->mTitle );
1851
1852 if( !is_null( $rev ) ) {
1853 # if this is a mini-text, we can paste part of it into the deletion reason
1854 $text = $rev->getText();
1855
1856 #if this is empty, an earlier revision may contain "useful" text
1857 $blanked = false;
1858 if( $text == '' ) {
1859 $prev = $rev->getPrevious();
1860 if( $prev ) {
1861 $text = $prev->getText();
1862 $blanked = true;
1863 }
1864 }
1865
1866 $length = strlen( $text );
1867
1868 # this should not happen, since it is not possible to store an empty, new
1869 # page. Let's insert a standard text in case it does, though
1870 if( $length == 0 && $reason === '' ) {
1871 $reason = wfMsgForContent( 'exblank' );
1872 }
1873
1874 if( $length < 500 && $reason === '' ) {
1875 # comment field=255, let's grep the first 150 to have some user
1876 # space left
1877 global $wgContLang;
1878 $text = $wgContLang->truncate( $text, 150, '...' );
1879
1880 # let's strip out newlines
1881 $text = preg_replace( "/[\n\r]/", '', $text );
1882
1883 if( !$blanked ) {
1884 if( $authorOfAll === false ) {
1885 $reason = wfMsgForContent( 'excontent', $text );
1886 } else {
1887 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1888 }
1889 } else {
1890 $reason = wfMsgForContent( 'exbeforeblank', $text );
1891 }
1892 }
1893 }
1894
1895 return $this->confirmDelete( '', $reason );
1896 }
1897
1898 /**
1899 * Get the last N authors
1900 * @param int $num Number of revisions to get
1901 * @param string $revLatest The latest rev_id, selected from the master (optional)
1902 * @return array Array of authors, duplicates not removed
1903 */
1904 function getLastNAuthors( $num, $revLatest = 0 ) {
1905 $fname = 'Article::getLastNAuthors';
1906 wfProfileIn( $fname );
1907
1908 // First try the slave
1909 // If that doesn't have the latest revision, try the master
1910 $continue = 2;
1911 $db =& wfGetDB( DB_SLAVE );
1912 do {
1913 $res = $db->select( array( 'page', 'revision' ),
1914 array( 'rev_id', 'rev_user_text' ),
1915 array(
1916 'page_namespace' => $this->mTitle->getNamespace(),
1917 'page_title' => $this->mTitle->getDBkey(),
1918 'rev_page = page_id'
1919 ), $fname, $this->getSelectOptions( array(
1920 'ORDER BY' => 'rev_timestamp DESC',
1921 'LIMIT' => $num
1922 ) )
1923 );
1924 if ( !$res ) {
1925 wfProfileOut( $fname );
1926 return array();
1927 }
1928 $row = $db->fetchObject( $res );
1929 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1930 $db =& wfGetDB( DB_MASTER );
1931 $continue--;
1932 } else {
1933 $continue = 0;
1934 }
1935 } while ( $continue );
1936
1937 $authors = array( $row->rev_user_text );
1938 while ( $row = $db->fetchObject( $res ) ) {
1939 $authors[] = $row->rev_user_text;
1940 }
1941 wfProfileOut( $fname );
1942 return $authors;
1943 }
1944
1945 /**
1946 * Output deletion confirmation dialog
1947 */
1948 function confirmDelete( $par, $reason ) {
1949 global $wgOut, $wgUser;
1950
1951 wfDebug( "Article::confirmDelete\n" );
1952
1953 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1954 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1955 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1956 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1957
1958 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1959
1960 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1961 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1962 $token = htmlspecialchars( $wgUser->editToken() );
1963
1964 $wgOut->addHTML( "
1965 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1966 <table border='0'>
1967 <tr>
1968 <td align='right'>
1969 <label for='wpReason'>{$delcom}:</label>
1970 </td>
1971 <td align='left'>
1972 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1973 </td>
1974 </tr>
1975 <tr>
1976 <td>&nbsp;</td>
1977 <td>
1978 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1979 </td>
1980 </tr>
1981 </table>
1982 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1983 </form>\n" );
1984
1985 $wgOut->returnToMain( false );
1986 }
1987
1988
1989 /**
1990 * Perform a deletion and output success or failure messages
1991 */
1992 function doDelete( $reason ) {
1993 global $wgOut, $wgUser;
1994 $fname = 'Article::doDelete';
1995 wfDebug( $fname."\n" );
1996
1997 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1998 if ( $this->doDeleteArticle( $reason ) ) {
1999 $deleted = $this->mTitle->getPrefixedText();
2000
2001 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2002 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2003
2004 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2005 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2006
2007 $wgOut->addWikiText( $text );
2008 $wgOut->returnToMain( false );
2009 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2010 } else {
2011 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2012 }
2013 }
2014 }
2015
2016 /**
2017 * Back-end article deletion
2018 * Deletes the article with database consistency, writes logs, purges caches
2019 * Returns success
2020 */
2021 function doDeleteArticle( $reason ) {
2022 global $wgUseSquid, $wgDeferredUpdateList;
2023 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2024
2025 $fname = 'Article::doDeleteArticle';
2026 wfDebug( $fname."\n" );
2027
2028 $dbw =& wfGetDB( DB_MASTER );
2029 $ns = $this->mTitle->getNamespace();
2030 $t = $this->mTitle->getDBkey();
2031 $id = $this->mTitle->getArticleID();
2032
2033 if ( $t == '' || $id == 0 ) {
2034 return false;
2035 }
2036
2037 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2038 array_push( $wgDeferredUpdateList, $u );
2039
2040 $linksTo = $this->mTitle->getLinksTo();
2041
2042 # Squid purging
2043 if ( $wgUseSquid ) {
2044 $urls = array(
2045 $this->mTitle->getInternalURL(),
2046 $this->mTitle->getInternalURL( 'history' )
2047 );
2048
2049 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
2050 array_push( $wgPostCommitUpdateList, $u );
2051
2052 }
2053
2054 # Client and file cache invalidation
2055 Title::touchArray( $linksTo );
2056
2057
2058 // For now, shunt the revision data into the archive table.
2059 // Text is *not* removed from the text table; bulk storage
2060 // is left intact to avoid breaking block-compression or
2061 // immutable storage schemes.
2062 //
2063 // For backwards compatibility, note that some older archive
2064 // table entries will have ar_text and ar_flags fields still.
2065 //
2066 // In the future, we may keep revisions and mark them with
2067 // the rev_deleted field, which is reserved for this purpose.
2068 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2069 array(
2070 'ar_namespace' => 'page_namespace',
2071 'ar_title' => 'page_title',
2072 'ar_comment' => 'rev_comment',
2073 'ar_user' => 'rev_user',
2074 'ar_user_text' => 'rev_user_text',
2075 'ar_timestamp' => 'rev_timestamp',
2076 'ar_minor_edit' => 'rev_minor_edit',
2077 'ar_rev_id' => 'rev_id',
2078 'ar_text_id' => 'rev_text_id',
2079 ), array(
2080 'page_id' => $id,
2081 'page_id = rev_page'
2082 ), $fname
2083 );
2084
2085 # Now that it's safely backed up, delete it
2086 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2087 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2088
2089 if ($wgUseTrackbacks)
2090 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2091
2092 # Clean up recentchanges entries...
2093 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2094
2095 # Finally, clean up the link tables
2096 $t = $this->mTitle->getPrefixedDBkey();
2097
2098 Article::onArticleDelete( $this->mTitle );
2099
2100 # Delete outgoing links
2101 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2102 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2103 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2104 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2105 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2106 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2107
2108 # Log the deletion
2109 $log = new LogPage( 'delete' );
2110 $log->addEntry( 'delete', $this->mTitle, $reason );
2111
2112 # Clear the cached article id so the interface doesn't act like we exist
2113 $this->mTitle->resetArticleID( 0 );
2114 $this->mTitle->mArticleID = 0;
2115 return true;
2116 }
2117
2118 /**
2119 * Revert a modification
2120 */
2121 function rollback() {
2122 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2123 $fname = 'Article::rollback';
2124
2125 if( $wgUser->isAllowed( 'rollback' ) ) {
2126 if( $wgUser->isBlocked() ) {
2127 $wgOut->blockedPage();
2128 return;
2129 }
2130 } else {
2131 $wgOut->permissionRequired( 'rollback' );
2132 return;
2133 }
2134
2135 if ( wfReadOnly() ) {
2136 $wgOut->readOnlyPage( $this->getContent() );
2137 return;
2138 }
2139 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2140 array( $this->mTitle->getPrefixedText(),
2141 $wgRequest->getVal( 'from' ) ) ) ) {
2142 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2143 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2144 return;
2145 }
2146 $dbw =& wfGetDB( DB_MASTER );
2147
2148 # Enhanced rollback, marks edits rc_bot=1
2149 $bot = $wgRequest->getBool( 'bot' );
2150
2151 # Replace all this user's current edits with the next one down
2152 $tt = $this->mTitle->getDBKey();
2153 $n = $this->mTitle->getNamespace();
2154
2155 # Get the last editor, lock table exclusively
2156 $dbw->begin();
2157 $current = Revision::newFromTitle( $this->mTitle );
2158 if( is_null( $current ) ) {
2159 # Something wrong... no page?
2160 $dbw->rollback();
2161 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2162 return;
2163 }
2164
2165 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2166 if( $from != $current->getUserText() ) {
2167 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2168 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2169 htmlspecialchars( $this->mTitle->getPrefixedText()),
2170 htmlspecialchars( $from ),
2171 htmlspecialchars( $current->getUserText() ) ) );
2172 if( $current->getComment() != '') {
2173 $wgOut->addHTML(
2174 wfMsg( 'editcomment',
2175 htmlspecialchars( $current->getComment() ) ) );
2176 }
2177 return;
2178 }
2179
2180 # Get the last edit not by this guy
2181 $user = intval( $current->getUser() );
2182 $user_text = $dbw->addQuotes( $current->getUserText() );
2183 $s = $dbw->selectRow( 'revision',
2184 array( 'rev_id', 'rev_timestamp' ),
2185 array(
2186 'rev_page' => $current->getPage(),
2187 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2188 ), $fname,
2189 array(
2190 'USE INDEX' => 'page_timestamp',
2191 'ORDER BY' => 'rev_timestamp DESC' )
2192 );
2193 if( $s === false ) {
2194 # Something wrong
2195 $dbw->rollback();
2196 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2197 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2198 return;
2199 }
2200
2201 $set = array();
2202 if ( $bot ) {
2203 # Mark all reverted edits as bot
2204 $set['rc_bot'] = 1;
2205 }
2206 if ( $wgUseRCPatrol ) {
2207 # Mark all reverted edits as patrolled
2208 $set['rc_patrolled'] = 1;
2209 }
2210
2211 if ( $set ) {
2212 $dbw->update( 'recentchanges', $set,
2213 array( /* WHERE */
2214 'rc_cur_id' => $current->getPage(),
2215 'rc_user_text' => $current->getUserText(),
2216 "rc_timestamp > '{$s->rev_timestamp}'",
2217 ), $fname
2218 );
2219 }
2220
2221 # Get the edit summary
2222 $target = Revision::newFromId( $s->rev_id );
2223 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2224 $newComment = $wgRequest->getText( 'summary', $newComment );
2225
2226 # Save it!
2227 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2228 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2229 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2230
2231 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2232 Article::onArticleEdit( $this->mTitle );
2233
2234 $dbw->commit();
2235 $wgOut->returnToMain( false );
2236 }
2237
2238
2239 /**
2240 * Do standard deferred updates after page view
2241 * @private
2242 */
2243 function viewUpdates() {
2244 global $wgDeferredUpdateList;
2245
2246 if ( 0 != $this->getID() ) {
2247 global $wgDisableCounters;
2248 if( !$wgDisableCounters ) {
2249 Article::incViewCount( $this->getID() );
2250 $u = new SiteStatsUpdate( 1, 0, 0 );
2251 array_push( $wgDeferredUpdateList, $u );
2252 }
2253 }
2254
2255 # Update newtalk / watchlist notification status
2256 global $wgUser;
2257 $wgUser->clearNotification( $this->mTitle );
2258 }
2259
2260 /**
2261 * Do standard deferred updates after page edit.
2262 * Every 1000th edit, prune the recent changes table.
2263 * @private
2264 * @param string $text
2265 */
2266 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2267 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2268
2269 $fname = 'Article::editUpdates';
2270 wfProfileIn( $fname );
2271
2272 # Parse the text
2273 $options = new ParserOptions;
2274 $options->setTidy(true);
2275 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2276
2277 # Save it to the parser cache
2278 $parserCache =& ParserCache::singleton();
2279 $parserCache->save( $poutput, $this, $wgUser );
2280
2281 # Update the links tables
2282 $u = new LinksUpdate( $this->mTitle, $poutput );
2283 $u->doUpdate();
2284
2285 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2286 wfSeedRandom();
2287 if ( 0 == mt_rand( 0, 999 ) ) {
2288 # Periodically flush old entries from the recentchanges table.
2289 global $wgRCMaxAge;
2290
2291 $dbw =& wfGetDB( DB_MASTER );
2292 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2293 $recentchanges = $dbw->tableName( 'recentchanges' );
2294 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2295 $dbw->query( $sql );
2296 }
2297 }
2298
2299 $id = $this->getID();
2300 $title = $this->mTitle->getPrefixedDBkey();
2301 $shortTitle = $this->mTitle->getDBkey();
2302
2303 if ( 0 == $id ) {
2304 wfProfileOut( $fname );
2305 return;
2306 }
2307
2308 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2309 array_push( $wgDeferredUpdateList, $u );
2310 $u = new SearchUpdate( $id, $title, $text );
2311 array_push( $wgDeferredUpdateList, $u );
2312
2313 # If this is another user's talk page, update newtalk
2314
2315 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2316 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2317 $other = User::newFromName( $shortTitle );
2318 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2319 // An anonymous user
2320 $other = new User();
2321 $other->setName( $shortTitle );
2322 }
2323 if( $other ) {
2324 $other->setNewtalk( true );
2325 }
2326 }
2327 }
2328
2329 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2330 $wgMessageCache->replace( $shortTitle, $text );
2331 }
2332
2333 wfProfileOut( $fname );
2334 }
2335
2336 /**
2337 * Generate the navigation links when browsing through an article revisions
2338 * It shows the information as:
2339 * Revision as of \<date\>; view current revision
2340 * \<- Previous version | Next Version -\>
2341 *
2342 * @private
2343 * @param string $oldid Revision ID of this article revision
2344 */
2345 function setOldSubtitle( $oldid=0 ) {
2346 global $wgLang, $wgOut, $wgUser;
2347
2348 $current = ( $oldid == $this->mLatest );
2349 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2350 $sk = $wgUser->getSkin();
2351 $lnk = $current
2352 ? wfMsg( 'currentrevisionlink' )
2353 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2354 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2355 $prevlink = $prev
2356 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2357 : wfMsg( 'previousrevision' );
2358 $nextlink = $current
2359 ? wfMsg( 'nextrevision' )
2360 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2361 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2362 $wgOut->setSubtitle( $r );
2363 }
2364
2365 /**
2366 * This function is called right before saving the wikitext,
2367 * so we can do things like signatures and links-in-context.
2368 *
2369 * @param string $text
2370 */
2371 function preSaveTransform( $text ) {
2372 global $wgParser, $wgUser;
2373 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2374 }
2375
2376 /* Caching functions */
2377
2378 /**
2379 * checkLastModified returns true if it has taken care of all
2380 * output to the client that is necessary for this request.
2381 * (that is, it has sent a cached version of the page)
2382 */
2383 function tryFileCache() {
2384 static $called = false;
2385 if( $called ) {
2386 wfDebug( " tryFileCache() -- called twice!?\n" );
2387 return;
2388 }
2389 $called = true;
2390 if($this->isFileCacheable()) {
2391 $touched = $this->mTouched;
2392 $cache = new CacheManager( $this->mTitle );
2393 if($cache->isFileCacheGood( $touched )) {
2394 wfDebug( " tryFileCache() - about to load\n" );
2395 $cache->loadFromFileCache();
2396 return true;
2397 } else {
2398 wfDebug( " tryFileCache() - starting buffer\n" );
2399 ob_start( array(&$cache, 'saveToFileCache' ) );
2400 }
2401 } else {
2402 wfDebug( " tryFileCache() - not cacheable\n" );
2403 }
2404 }
2405
2406 /**
2407 * Check if the page can be cached
2408 * @return bool
2409 */
2410 function isFileCacheable() {
2411 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2412 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2413
2414 return $wgUseFileCache
2415 and (!$wgShowIPinHeader)
2416 and ($this->getID() != 0)
2417 and ($wgUser->isAnon())
2418 and (!$wgUser->getNewtalk())
2419 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2420 and (empty( $action ) || $action == 'view')
2421 and (!isset($oldid))
2422 and (!isset($diff))
2423 and (!isset($redirect))
2424 and (!isset($printable))
2425 and (!$this->mRedirectedFrom);
2426 }
2427
2428 /**
2429 * Loads page_touched and returns a value indicating if it should be used
2430 *
2431 */
2432 function checkTouched() {
2433 $fname = 'Article::checkTouched';
2434 if( !$this->mDataLoaded ) {
2435 $this->loadPageData();
2436 }
2437 return !$this->mIsRedirect;
2438 }
2439
2440 /**
2441 * Get the page_touched field
2442 */
2443 function getTouched() {
2444 # Ensure that page data has been loaded
2445 if( !$this->mDataLoaded ) {
2446 $this->loadPageData();
2447 }
2448 return $this->mTouched;
2449 }
2450
2451 /**
2452 * Get the page_latest field
2453 */
2454 function getLatest() {
2455 if ( !$this->mDataLoaded ) {
2456 $this->loadPageData();
2457 }
2458 return $this->mLatest;
2459 }
2460
2461 /**
2462 * Edit an article without doing all that other stuff
2463 * The article must already exist; link tables etc
2464 * are not updated, caches are not flushed.
2465 *
2466 * @param string $text text submitted
2467 * @param string $comment comment submitted
2468 * @param bool $minor whereas it's a minor modification
2469 */
2470 function quickEdit( $text, $comment = '', $minor = 0 ) {
2471 $fname = 'Article::quickEdit';
2472 wfProfileIn( $fname );
2473
2474 $dbw =& wfGetDB( DB_MASTER );
2475 $dbw->begin();
2476 $revision = new Revision( array(
2477 'page' => $this->getId(),
2478 'text' => $text,
2479 'comment' => $comment,
2480 'minor_edit' => $minor ? 1 : 0,
2481 ) );
2482 # fixme : $revisionId never used
2483 $revisionId = $revision->insertOn( $dbw );
2484 $this->updateRevisionOn( $dbw, $revision );
2485 $dbw->commit();
2486
2487 wfProfileOut( $fname );
2488 }
2489
2490 /**
2491 * Used to increment the view counter
2492 *
2493 * @static
2494 * @param integer $id article id
2495 */
2496 function incViewCount( $id ) {
2497 $id = intval( $id );
2498 global $wgHitcounterUpdateFreq, $wgDBtype;
2499
2500 $dbw =& wfGetDB( DB_MASTER );
2501 $pageTable = $dbw->tableName( 'page' );
2502 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2503 $acchitsTable = $dbw->tableName( 'acchits' );
2504
2505 if( $wgHitcounterUpdateFreq <= 1 ){ //
2506 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2507 return;
2508 }
2509
2510 # Not important enough to warrant an error page in case of failure
2511 $oldignore = $dbw->ignoreErrors( true );
2512
2513 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2514
2515 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2516 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2517 # Most of the time (or on SQL errors), skip row count check
2518 $dbw->ignoreErrors( $oldignore );
2519 return;
2520 }
2521
2522 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2523 $row = $dbw->fetchObject( $res );
2524 $rown = intval( $row->n );
2525 if( $rown >= $wgHitcounterUpdateFreq ){
2526 wfProfileIn( 'Article::incViewCount-collect' );
2527 $old_user_abort = ignore_user_abort( true );
2528
2529 if ($wgDBtype == 'mysql')
2530 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2531 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2532 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2533 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2534 'GROUP BY hc_id');
2535 $dbw->query("DELETE FROM $hitcounterTable");
2536 if ($wgDBtype == 'mysql')
2537 $dbw->query('UNLOCK TABLES');
2538 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2539 'WHERE page_id = hc_id');
2540 $dbw->query("DROP TABLE $acchitsTable");
2541
2542 ignore_user_abort( $old_user_abort );
2543 wfProfileOut( 'Article::incViewCount-collect' );
2544 }
2545 $dbw->ignoreErrors( $oldignore );
2546 }
2547
2548 /**#@+
2549 * The onArticle*() functions are supposed to be a kind of hooks
2550 * which should be called whenever any of the specified actions
2551 * are done.
2552 *
2553 * This is a good place to put code to clear caches, for instance.
2554 *
2555 * This is called on page move and undelete, as well as edit
2556 * @static
2557 * @param $title_obj a title object
2558 */
2559
2560 function onArticleCreate($title_obj) {
2561 global $wgUseSquid, $wgPostCommitUpdateList;
2562
2563 $title_obj->touchLinks();
2564 $titles = $title_obj->getLinksTo();
2565
2566 # Purge squid
2567 if ( $wgUseSquid ) {
2568 $urls = $title_obj->getSquidURLs();
2569 foreach ( $titles as $linkTitle ) {
2570 $urls[] = $linkTitle->getInternalURL();
2571 }
2572 $u = new SquidUpdate( $urls );
2573 array_push( $wgPostCommitUpdateList, $u );
2574 }
2575 }
2576
2577 function onArticleDelete( $title ) {
2578 global $wgMessageCache;
2579
2580 $title->touchLinks();
2581
2582 if( $title->getNamespace() == NS_MEDIAWIKI) {
2583 $wgMessageCache->replace( $title->getDBkey(), false );
2584 }
2585 }
2586
2587 /**
2588 * Purge caches on page update etc
2589 */
2590 function onArticleEdit( $title ) {
2591 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2592
2593 $urls = array();
2594
2595 // Template namespace? Purge all articles linking here.
2596 // FIXME: When a templatelinks table arrives, use it for all includes.
2597 if ( $title->getNamespace() == NS_TEMPLATE) {
2598 $titles = $title->getLinksTo();
2599 Title::touchArray( $titles );
2600 if ( $wgUseSquid ) {
2601 foreach ( $titles as $link ) {
2602 $urls[] = $link->getInternalURL();
2603 }
2604 }
2605 }
2606
2607 # Squid updates
2608 if ( $wgUseSquid ) {
2609 $urls = array_merge( $urls, $title->getSquidURLs() );
2610 $u = new SquidUpdate( $urls );
2611 array_push( $wgPostCommitUpdateList, $u );
2612 }
2613
2614 # File cache
2615 if ( $wgUseFileCache ) {
2616 $cm = new CacheManager( $title );
2617 @unlink( $cm->fileCacheName() );
2618 }
2619 }
2620
2621 /**#@-*/
2622
2623 /**
2624 * Info about this page
2625 * Called for ?action=info when $wgAllowPageInfo is on.
2626 *
2627 * @public
2628 */
2629 function info() {
2630 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2631 $fname = 'Article::info';
2632
2633 if ( !$wgAllowPageInfo ) {
2634 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2635 return;
2636 }
2637
2638 $page = $this->mTitle->getSubjectPage();
2639
2640 $wgOut->setPagetitle( $page->getPrefixedText() );
2641 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2642
2643 # first, see if the page exists at all.
2644 $exists = $page->getArticleId() != 0;
2645 if( !$exists ) {
2646 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2647 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2648 } else {
2649 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2650 }
2651 } else {
2652 $dbr =& wfGetDB( DB_SLAVE );
2653 $wl_clause = array(
2654 'wl_title' => $page->getDBkey(),
2655 'wl_namespace' => $page->getNamespace() );
2656 $numwatchers = $dbr->selectField(
2657 'watchlist',
2658 'COUNT(*)',
2659 $wl_clause,
2660 $fname,
2661 $this->getSelectOptions() );
2662
2663 $pageInfo = $this->pageCountInfo( $page );
2664 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2665
2666 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2667 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2668 if( $talkInfo ) {
2669 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2670 }
2671 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2672 if( $talkInfo ) {
2673 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2674 }
2675 $wgOut->addHTML( '</ul>' );
2676
2677 }
2678 }
2679
2680 /**
2681 * Return the total number of edits and number of unique editors
2682 * on a given page. If page does not exist, returns false.
2683 *
2684 * @param Title $title
2685 * @return array
2686 * @private
2687 */
2688 function pageCountInfo( $title ) {
2689 $id = $title->getArticleId();
2690 if( $id == 0 ) {
2691 return false;
2692 }
2693
2694 $dbr =& wfGetDB( DB_SLAVE );
2695
2696 $rev_clause = array( 'rev_page' => $id );
2697 $fname = 'Article::pageCountInfo';
2698
2699 $edits = $dbr->selectField(
2700 'revision',
2701 'COUNT(rev_page)',
2702 $rev_clause,
2703 $fname,
2704 $this->getSelectOptions() );
2705
2706 $authors = $dbr->selectField(
2707 'revision',
2708 'COUNT(DISTINCT rev_user_text)',
2709 $rev_clause,
2710 $fname,
2711 $this->getSelectOptions() );
2712
2713 return array( 'edits' => $edits, 'authors' => $authors );
2714 }
2715
2716 /**
2717 * Return a list of templates used by this article.
2718 * Uses the templatelinks table
2719 *
2720 * @return array Array of Title objects
2721 */
2722 function getUsedTemplates() {
2723 $result = array();
2724 $id = $this->mTitle->getArticleID();
2725 if( $id == 0 ) {
2726 return array();
2727 }
2728
2729 $dbr =& wfGetDB( DB_SLAVE );
2730 $res = $dbr->select( array( 'templatelinks' ),
2731 array( 'tl_namespace', 'tl_title' ),
2732 array( 'tl_from' => $id ),
2733 'Article:getUsedTemplates' );
2734 if ( false !== $res ) {
2735 if ( $dbr->numRows( $res ) ) {
2736 while ( $row = $dbr->fetchObject( $res ) ) {
2737 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2738 }
2739 }
2740 }
2741 $dbr->freeResult( $res );
2742 return $result;
2743 }
2744 }
2745
2746 ?>