Switching from phpdoc to doxygen (use less than 32MB of memory).
[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 $lastid = $oldid;
341 }
342 if ( !$oldid ) {
343 $oldid = 0;
344 }
345 return $oldid;
346 }
347
348 /**
349 * Load the revision (including text) into this object
350 */
351 function loadContent() {
352 if ( $this->mContentLoaded ) return;
353
354 # Query variables :P
355 $oldid = $this->getOldID();
356
357 $fname = 'Article::loadContent';
358
359 # Pre-fill content with error message so that if something
360 # fails we'll have something telling us what we intended.
361
362 $t = $this->mTitle->getPrefixedText();
363
364 $this->mOldId = $oldid;
365 $this->fetchContent( $oldid );
366 }
367
368
369 /**
370 * Fetch a page record with the given conditions
371 * @param Database $dbr
372 * @param array $conditions
373 * @private
374 */
375 function pageData( &$dbr, $conditions ) {
376 $fields = array(
377 'page_id',
378 'page_namespace',
379 'page_title',
380 'page_restrictions',
381 'page_counter',
382 'page_is_redirect',
383 'page_is_new',
384 'page_random',
385 'page_touched',
386 'page_latest',
387 'page_len' ) ;
388 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
389 $row = $dbr->selectRow( 'page',
390 $fields,
391 $conditions,
392 'Article::pageData' );
393 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
394 return $row ;
395 }
396
397 /**
398 * @param Database $dbr
399 * @param Title $title
400 */
401 function pageDataFromTitle( &$dbr, $title ) {
402 return $this->pageData( $dbr, array(
403 'page_namespace' => $title->getNamespace(),
404 'page_title' => $title->getDBkey() ) );
405 }
406
407 /**
408 * @param Database $dbr
409 * @param int $id
410 */
411 function pageDataFromId( &$dbr, $id ) {
412 return $this->pageData( $dbr, array( 'page_id' => $id ) );
413 }
414
415 /**
416 * Set the general counter, title etc data loaded from
417 * some source.
418 *
419 * @param object $data
420 * @private
421 */
422 function loadPageData( $data = 'fromdb' ) {
423 if ( $data === 'fromdb' ) {
424 $dbr =& $this->getDB();
425 $data = $this->pageDataFromId( $dbr, $this->getId() );
426 }
427
428 $lc =& LinkCache::singleton();
429 if ( $data ) {
430 $lc->addGoodLinkObj( $data->page_id, $this->mTitle );
431
432 $this->mTitle->mArticleID = $data->page_id;
433 $this->mTitle->loadRestrictions( $data->page_restrictions );
434 $this->mTitle->mRestrictionsLoaded = true;
435
436 $this->mCounter = $data->page_counter;
437 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
438 $this->mIsRedirect = $data->page_is_redirect;
439 $this->mLatest = $data->page_latest;
440 } else {
441 if ( is_object( $this->mTitle ) ) {
442 $lc->addBadLinkObj( $this->mTitle );
443 }
444 $this->mTitle->mArticleID = 0;
445 }
446
447 $this->mDataLoaded = true;
448 }
449
450 /**
451 * Get text of an article from database
452 * Does *NOT* follow redirects.
453 * @param int $oldid 0 for whatever the latest revision is
454 * @return string
455 */
456 function fetchContent( $oldid = 0 ) {
457 if ( $this->mContentLoaded ) {
458 return $this->mContent;
459 }
460
461 $dbr =& $this->getDB();
462 $fname = 'Article::fetchContent';
463
464 # Pre-fill content with error message so that if something
465 # fails we'll have something telling us what we intended.
466 $t = $this->mTitle->getPrefixedText();
467 if( $oldid ) {
468 $t .= ',oldid='.$oldid;
469 }
470 $this->mContent = wfMsg( 'missingarticle', $t ) ;
471
472 if( $oldid ) {
473 $revision = Revision::newFromId( $oldid );
474 if( is_null( $revision ) ) {
475 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
476 return false;
477 }
478 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
479 if( !$data ) {
480 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
481 return false;
482 }
483 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
484 $this->loadPageData( $data );
485 } else {
486 if( !$this->mDataLoaded ) {
487 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
488 if( !$data ) {
489 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
490 return false;
491 }
492 $this->loadPageData( $data );
493 }
494 $revision = Revision::newFromId( $this->mLatest );
495 if( is_null( $revision ) ) {
496 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
497 return false;
498 }
499 }
500
501 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
502 // We should instead work with the Revision object when we need it...
503 $this->mContent = $revision->userCan( MW_REV_DELETED_TEXT ) ? $revision->getRawText() : "";
504 //$this->mContent = $revision->getText();
505
506 $this->mUser = $revision->getUser();
507 $this->mUserText = $revision->getUserText();
508 $this->mComment = $revision->getComment();
509 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
510
511 $this->mRevIdFetched = $revision->getID();
512 $this->mContentLoaded = true;
513 $this->mRevision =& $revision;
514
515 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
516
517 return $this->mContent;
518 }
519
520 /**
521 * Read/write accessor to select FOR UPDATE
522 *
523 * @param $x Mixed: FIXME
524 */
525 function forUpdate( $x = NULL ) {
526 return wfSetVar( $this->mForUpdate, $x );
527 }
528
529 /**
530 * Get the database which should be used for reads
531 *
532 * @return Database
533 */
534 function &getDB() {
535 $ret =& wfGetDB( DB_MASTER );
536 return $ret;
537 }
538
539 /**
540 * Get options for all SELECT statements
541 *
542 * @param $options Array: an optional options array which'll be appended to
543 * the default
544 * @return Array: options
545 */
546 function getSelectOptions( $options = '' ) {
547 if ( $this->mForUpdate ) {
548 if ( is_array( $options ) ) {
549 $options[] = 'FOR UPDATE';
550 } else {
551 $options = 'FOR UPDATE';
552 }
553 }
554 return $options;
555 }
556
557 /**
558 * @return int Page ID
559 */
560 function getID() {
561 if( $this->mTitle ) {
562 return $this->mTitle->getArticleID();
563 } else {
564 return 0;
565 }
566 }
567
568 /**
569 * @return bool Whether or not the page exists in the database
570 */
571 function exists() {
572 return $this->getId() != 0;
573 }
574
575 /**
576 * @return int The view count for the page
577 */
578 function getCount() {
579 if ( -1 == $this->mCounter ) {
580 $id = $this->getID();
581 if ( $id == 0 ) {
582 $this->mCounter = 0;
583 } else {
584 $dbr =& wfGetDB( DB_SLAVE );
585 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
586 'Article::getCount', $this->getSelectOptions() );
587 }
588 }
589 return $this->mCounter;
590 }
591
592 /**
593 * Determine whether a page would be suitable for being counted as an
594 * article in the site_stats table based on the title & its content
595 *
596 * @param $text String: text to analyze
597 * @return bool
598 */
599 function isCountable( $text ) {
600 global $wgUseCommaCount;
601
602 $token = $wgUseCommaCount ? ',' : '[[';
603 return
604 $this->mTitle->getNamespace() == NS_MAIN
605 && ! $this->isRedirect( $text )
606 && in_string( $token, $text );
607 }
608
609 /**
610 * Tests if the article text represents a redirect
611 *
612 * @param $text String: FIXME
613 * @return bool
614 */
615 function isRedirect( $text = false ) {
616 if ( $text === false ) {
617 $this->loadContent();
618 $titleObj = Title::newFromRedirect( $this->fetchContent() );
619 } else {
620 $titleObj = Title::newFromRedirect( $text );
621 }
622 return $titleObj !== NULL;
623 }
624
625 /**
626 * Returns true if the currently-referenced revision is the current edit
627 * to this page (and it exists).
628 * @return bool
629 */
630 function isCurrent() {
631 return $this->exists() &&
632 isset( $this->mRevision ) &&
633 $this->mRevision->isCurrent();
634 }
635
636 /**
637 * Loads everything except the text
638 * This isn't necessary for all uses, so it's only done if needed.
639 * @private
640 */
641 function loadLastEdit() {
642 if ( -1 != $this->mUser )
643 return;
644
645 # New or non-existent articles have no user information
646 $id = $this->getID();
647 if ( 0 == $id ) return;
648
649 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
650 if( !is_null( $this->mLastRevision ) ) {
651 $this->mUser = $this->mLastRevision->getUser();
652 $this->mUserText = $this->mLastRevision->getUserText();
653 $this->mTimestamp = $this->mLastRevision->getTimestamp();
654 $this->mComment = $this->mLastRevision->getComment();
655 $this->mMinorEdit = $this->mLastRevision->isMinor();
656 $this->mRevIdFetched = $this->mLastRevision->getID();
657 }
658 }
659
660 function getTimestamp() {
661 // Check if the field has been filled by ParserCache::get()
662 if ( !$this->mTimestamp ) {
663 $this->loadLastEdit();
664 }
665 return wfTimestamp(TS_MW, $this->mTimestamp);
666 }
667
668 function getUser() {
669 $this->loadLastEdit();
670 return $this->mUser;
671 }
672
673 function getUserText() {
674 $this->loadLastEdit();
675 return $this->mUserText;
676 }
677
678 function getComment() {
679 $this->loadLastEdit();
680 return $this->mComment;
681 }
682
683 function getMinorEdit() {
684 $this->loadLastEdit();
685 return $this->mMinorEdit;
686 }
687
688 function getRevIdFetched() {
689 $this->loadLastEdit();
690 return $this->mRevIdFetched;
691 }
692
693 /**
694 * @todo Document
695 * @param $limit Integer: default 0.
696 * @param $offset Integer: default 0.
697 */
698 function getContributors($limit = 0, $offset = 0) {
699 $fname = 'Article::getContributors';
700
701 # XXX: this is expensive; cache this info somewhere.
702
703 $title = $this->mTitle;
704 $contribs = array();
705 $dbr =& wfGetDB( DB_SLAVE );
706 $revTable = $dbr->tableName( 'revision' );
707 $userTable = $dbr->tableName( 'user' );
708 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
709 $ns = $title->getNamespace();
710 $user = $this->getUser();
711 $pageId = $this->getId();
712
713 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
714 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
715 WHERE rev_page = $pageId
716 AND rev_user != $user
717 GROUP BY rev_user, rev_user_text, user_real_name
718 ORDER BY timestamp DESC";
719
720 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
721 $sql .= ' '. $this->getSelectOptions();
722
723 $res = $dbr->query($sql, $fname);
724
725 while ( $line = $dbr->fetchObject( $res ) ) {
726 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
727 }
728
729 $dbr->freeResult($res);
730 return $contribs;
731 }
732
733 /**
734 * This is the default action of the script: just view the page of
735 * the given title.
736 */
737 function view() {
738 global $wgUser, $wgOut, $wgRequest, $wgContLang;
739 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
740 global $wgUseTrackbacks;
741 $sk = $wgUser->getSkin();
742
743 $fname = 'Article::view';
744 wfProfileIn( $fname );
745 $parserCache =& ParserCache::singleton();
746 # Get variables from query string
747 $oldid = $this->getOldID();
748
749 # getOldID may want us to redirect somewhere else
750 if ( $this->mRedirectUrl ) {
751 $wgOut->redirect( $this->mRedirectUrl );
752 wfProfileOut( $fname );
753 return;
754 }
755
756 $diff = $wgRequest->getVal( 'diff' );
757 $rcid = $wgRequest->getVal( 'rcid' );
758 $rdfrom = $wgRequest->getVal( 'rdfrom' );
759
760 $wgOut->setArticleFlag( true );
761 $wgOut->setRobotpolicy( 'index,follow' );
762 # If we got diff and oldid in the query, we want to see a
763 # diff page instead of the article.
764
765 if ( !is_null( $diff ) ) {
766 require_once( 'DifferenceEngine.php' );
767 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
768
769 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
770 // DifferenceEngine directly fetched the revision:
771 $this->mRevIdFetched = $de->mNewid;
772 $de->showDiffPage();
773
774 if( $diff == 0 ) {
775 # Run view updates for current revision only
776 $this->viewUpdates();
777 }
778 wfProfileOut( $fname );
779 return;
780 }
781
782 if ( empty( $oldid ) && $this->checkTouched() ) {
783 $wgOut->setETag($parserCache->getETag($this, $wgUser));
784
785 if( $wgOut->checkLastModified( $this->mTouched ) ){
786 wfProfileOut( $fname );
787 return;
788 } else if ( $this->tryFileCache() ) {
789 # tell wgOut that output is taken care of
790 $wgOut->disable();
791 $this->viewUpdates();
792 wfProfileOut( $fname );
793 return;
794 }
795 }
796 # Should the parser cache be used?
797 $pcache = $wgEnableParserCache &&
798 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
799 $this->exists() &&
800 empty( $oldid );
801 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
802 if ( $wgUser->getOption( 'stubthreshold' ) ) {
803 wfIncrStats( 'pcache_miss_stub' );
804 }
805
806 $wasRedirected = false;
807 if ( isset( $this->mRedirectedFrom ) ) {
808 // This is an internally redirected page view.
809 // We'll need a backlink to the source page for navigation.
810 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
811 $sk = $wgUser->getSkin();
812 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
813 $s = wfMsg( 'redirectedfrom', $redir );
814 $wgOut->setSubtitle( $s );
815 $wasRedirected = true;
816 }
817 } elseif ( !empty( $rdfrom ) ) {
818 // This is an externally redirected view, from some other wiki.
819 // If it was reported from a trusted site, supply a backlink.
820 global $wgRedirectSources;
821 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
822 $sk = $wgUser->getSkin();
823 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
824 $s = wfMsg( 'redirectedfrom', $redir );
825 $wgOut->setSubtitle( $s );
826 $wasRedirected = true;
827 }
828 }
829
830 $outputDone = false;
831 if ( $pcache ) {
832 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
833 $outputDone = true;
834 }
835 }
836 if ( !$outputDone ) {
837 $text = $this->getContent();
838 if ( $text === false ) {
839 # Failed to load, replace text with error message
840 $t = $this->mTitle->getPrefixedText();
841 if( $oldid ) {
842 $t .= ',oldid='.$oldid;
843 $text = wfMsg( 'missingarticle', $t );
844 } else {
845 $text = wfMsg( 'noarticletext', $t );
846 }
847 }
848
849 # Another whitelist check in case oldid is altering the title
850 if ( !$this->mTitle->userCanRead() ) {
851 $wgOut->loginToUse();
852 $wgOut->output();
853 exit;
854 }
855
856 # We're looking at an old revision
857
858 if ( !empty( $oldid ) ) {
859 $wgOut->setRobotpolicy( 'noindex,nofollow' );
860 if( is_null( $this->mRevision ) ) {
861 // FIXME: This would be a nice place to load the 'no such page' text.
862 } else {
863 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
864 if( $this->mRevision->isDeleted( MW_REV_DELETED_TEXT ) ) {
865 if( !$this->mRevision->userCan( MW_REV_DELETED_TEXT ) ) {
866 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
867 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
868 return;
869 } else {
870 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
871 // and we are allowed to see...
872 }
873 }
874 }
875
876 }
877 }
878 if( !$outputDone ) {
879 /**
880 * @fixme: this hook doesn't work most of the time, as it doesn't
881 * trigger when the parser cache is used.
882 */
883 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
884 $wgOut->setRevisionId( $this->getRevIdFetched() );
885 # wrap user css and user js in pre and don't parse
886 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
887 if (
888 $this->mTitle->getNamespace() == NS_USER &&
889 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
890 ) {
891 $wgOut->addWikiText( wfMsg('clearyourcache'));
892 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
893 } else if ( $rt = Title::newFromRedirect( $text ) ) {
894 # Display redirect
895 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
896 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
897 if( !$wasRedirected ) {
898 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
899 }
900 $targetUrl = $rt->escapeLocalURL();
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->isSysop()) {
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 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1276 $this->replaceSection( $section, $text, $summary, $edittime );
1277 }
1278
1279 /**
1280 * @return string Complete article text, or null if error
1281 */
1282 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1283 $fname = 'Article::replaceSection';
1284 wfProfileIn( $fname );
1285
1286 if ($section != '') {
1287 if( is_null( $edittime ) ) {
1288 $rev = Revision::newFromTitle( $this->mTitle );
1289 } else {
1290 $dbw =& wfGetDB( DB_MASTER );
1291 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1292 }
1293 if( is_null( $rev ) ) {
1294 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1295 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1296 return null;
1297 }
1298 $oldtext = $rev->getText();
1299
1300 if($section=='new') {
1301 if($summary) $subject="== {$summary} ==\n\n";
1302 $text=$oldtext."\n\n".$subject.$text;
1303 } else {
1304
1305 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1306 # comments to be stripped as well)
1307 $striparray=array();
1308 $parser=new Parser();
1309 $parser->mOutputType=OT_WIKI;
1310 $parser->mOptions = new ParserOptions();
1311 $oldtext=$parser->strip($oldtext, $striparray, true);
1312
1313 # now that we can be sure that no pseudo-sections are in the source,
1314 # split it up
1315 # Unfortunately we can't simply do a preg_replace because that might
1316 # replace the wrong section, so we have to use the section counter instead
1317 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1318 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1319 $secs[$section*2]=$text."\n\n"; // replace with edited
1320
1321 # section 0 is top (intro) section
1322 if($section!=0) {
1323
1324 # headline of old section - we need to go through this section
1325 # to determine if there are any subsections that now need to
1326 # be erased, as the mother section has been replaced with
1327 # the text of all subsections.
1328 $headline=$secs[$section*2-1];
1329 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1330 $hlevel=$matches[1];
1331
1332 # determine headline level for wikimarkup headings
1333 if(strpos($hlevel,'=')!==false) {
1334 $hlevel=strlen($hlevel);
1335 }
1336
1337 $secs[$section*2-1]=''; // erase old headline
1338 $count=$section+1;
1339 $break=false;
1340 while(!empty($secs[$count*2-1]) && !$break) {
1341
1342 $subheadline=$secs[$count*2-1];
1343 preg_match(
1344 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1345 $subhlevel=$matches[1];
1346 if(strpos($subhlevel,'=')!==false) {
1347 $subhlevel=strlen($subhlevel);
1348 }
1349 if($subhlevel > $hlevel) {
1350 // erase old subsections
1351 $secs[$count*2-1]='';
1352 $secs[$count*2]='';
1353 }
1354 if($subhlevel <= $hlevel) {
1355 $break=true;
1356 }
1357 $count++;
1358
1359 }
1360
1361 }
1362 $text=join('',$secs);
1363 # reinsert the stuff that we stripped out earlier
1364 $text=$parser->unstrip($text,$striparray);
1365 $text=$parser->unstripNoWiki($text,$striparray);
1366 }
1367
1368 }
1369 wfProfileOut( $fname );
1370 return $text;
1371 }
1372
1373 /**
1374 * Change an existing article. Puts the previous version back into the old table, updates RC
1375 * and all necessary caches, mostly via the deferred update array.
1376 *
1377 * It is possible to call this function from a command-line script, but note that you should
1378 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1379 */
1380 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1381 global $wgUser, $wgDBtransactions, $wgUseSquid;
1382 global $wgPostCommitUpdateList, $wgUseFileCache;
1383
1384 $fname = 'Article::updateArticle';
1385 wfProfileIn( $fname );
1386 $good = true;
1387
1388 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1389 &$summary, &$minor,
1390 &$watchthis, &$sectionanchor ) ) ) {
1391 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1392 wfProfileOut( $fname );
1393 return false;
1394 }
1395
1396 $isminor = $minor && $wgUser->isAllowed('minoredit');
1397 $redir = (int)$this->isRedirect( $text );
1398
1399 $text = $this->preSaveTransform( $text );
1400 $dbw =& wfGetDB( DB_MASTER );
1401 $now = wfTimestampNow();
1402
1403 # Update article, but only if changed.
1404
1405 # It's important that we either rollback or complete, otherwise an attacker could
1406 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1407 # could conceivably have the same effect, especially if cur is locked for long periods.
1408 if( !$wgDBtransactions ) {
1409 $userAbort = ignore_user_abort( true );
1410 }
1411
1412 $oldtext = $this->getContent();
1413 $oldsize = strlen( $oldtext );
1414 $newsize = strlen( $text );
1415 $lastRevision = 0;
1416 $revisionId = 0;
1417
1418 if ( 0 != strcmp( $text, $oldtext ) ) {
1419 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1420 - (int)$this->isCountable( $oldtext );
1421 $this->mTotalAdjustment = 0;
1422 $now = wfTimestampNow();
1423
1424 $lastRevision = $dbw->selectField(
1425 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1426
1427 $revision = new Revision( array(
1428 'page' => $this->getId(),
1429 'comment' => $summary,
1430 'minor_edit' => $isminor,
1431 'text' => $text
1432 ) );
1433
1434 $dbw->immediateCommit();
1435 $dbw->begin();
1436 $revisionId = $revision->insertOn( $dbw );
1437
1438 # Update page
1439 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1440
1441 if( !$ok ) {
1442 /* Belated edit conflict! Run away!! */
1443 $good = false;
1444 $dbw->rollback();
1445 } else {
1446 # Update recentchanges and purge cache and whatnot
1447 require_once( 'RecentChange.php' );
1448 $bot = (int)($wgUser->isBot() || $forceBot);
1449 $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1450 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1451 $revisionId );
1452
1453 # Mark as patrolled if the user can do so and has it set in their options
1454 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1455 RecentChange::markPatrolled( $rcid );
1456 }
1457
1458 $dbw->commit();
1459
1460 // Update caches outside the main transaction
1461 Article::onArticleEdit( $this->mTitle );
1462 }
1463 } else {
1464 // Keep the same revision ID, but do some updates on it
1465 $revisionId = $this->getRevIdFetched();
1466 }
1467
1468 if( !$wgDBtransactions ) {
1469 ignore_user_abort( $userAbort );
1470 }
1471
1472 if ( $good ) {
1473 if ($watchthis) {
1474 if (!$this->mTitle->userIsWatching()) {
1475 $dbw->immediateCommit();
1476 $dbw->begin();
1477 $this->doWatch();
1478 $dbw->commit();
1479 }
1480 } else {
1481 if ( $this->mTitle->userIsWatching() ) {
1482 $dbw->immediateCommit();
1483 $dbw->begin();
1484 $this->doUnwatch();
1485 $dbw->commit();
1486 }
1487 }
1488 # standard deferred updates
1489 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1490
1491
1492 $urls = array();
1493 # Invalidate caches of all articles using this article as a template
1494
1495 # Template namespace
1496 # Purge all articles linking here
1497 $titles = $this->mTitle->getTemplateLinksTo();
1498 Title::touchArray( $titles );
1499 if ( $wgUseSquid ) {
1500 foreach ( $titles as $title ) {
1501 $urls[] = $title->getInternalURL();
1502 }
1503 }
1504
1505 # Squid updates
1506 if ( $wgUseSquid ) {
1507 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1508 $u = new SquidUpdate( $urls );
1509 array_push( $wgPostCommitUpdateList, $u );
1510 }
1511
1512 # File cache
1513 if ( $wgUseFileCache ) {
1514 $cm = new CacheManager($this->mTitle);
1515 @unlink($cm->fileCacheName());
1516 }
1517
1518 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1519 }
1520 wfRunHooks( 'ArticleSaveComplete',
1521 array( &$this, &$wgUser, $text,
1522 $summary, $minor,
1523 $watchthis, $sectionanchor ) );
1524 wfProfileOut( $fname );
1525 return $good;
1526 }
1527
1528 /**
1529 * After we've either updated or inserted the article, update
1530 * the link tables and redirect to the new page.
1531 */
1532 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1533 global $wgOut;
1534
1535 $fname = 'Article::showArticle';
1536 wfProfileIn( $fname );
1537
1538 # Output the redirect
1539 if( $this->isRedirect( $text ) )
1540 $r = 'redirect=no';
1541 else
1542 $r = '';
1543 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1544
1545 wfProfileOut( $fname );
1546 }
1547
1548 /**
1549 * Mark this particular edit as patrolled
1550 */
1551 function markpatrolled() {
1552 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1553 $wgOut->setRobotpolicy( 'noindex,follow' );
1554
1555 # Check RC patrol config. option
1556 if( !$wgUseRCPatrol ) {
1557 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1558 return;
1559 }
1560
1561 # Check permissions
1562 if( !$wgUser->isAllowed( 'patrol' ) ) {
1563 $wgOut->permissionRequired( 'patrol' );
1564 return;
1565 }
1566
1567 $rcid = $wgRequest->getVal( 'rcid' );
1568 if ( !is_null ( $rcid ) ) {
1569 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1570 require_once( 'RecentChange.php' );
1571 RecentChange::markPatrolled( $rcid );
1572 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1573 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1574 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1575 }
1576 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1577 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1578 }
1579 else {
1580 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1581 }
1582 }
1583
1584 /**
1585 * User-interface handler for the "watch" action
1586 */
1587
1588 function watch() {
1589
1590 global $wgUser, $wgOut;
1591
1592 if ( $wgUser->isAnon() ) {
1593 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1594 return;
1595 }
1596 if ( wfReadOnly() ) {
1597 $wgOut->readOnlyPage();
1598 return;
1599 }
1600
1601 if( $this->doWatch() ) {
1602 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1603 $wgOut->setRobotpolicy( 'noindex,follow' );
1604
1605 $link = $this->mTitle->getPrefixedText();
1606 $text = wfMsg( 'addedwatchtext', $link );
1607 $wgOut->addWikiText( $text );
1608 }
1609
1610 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1611 }
1612
1613 /**
1614 * Add this page to $wgUser's watchlist
1615 * @return bool true on successful watch operation
1616 */
1617 function doWatch() {
1618 global $wgUser;
1619 if( $wgUser->isAnon() ) {
1620 return false;
1621 }
1622
1623 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1624 $wgUser->addWatch( $this->mTitle );
1625 $wgUser->saveSettings();
1626
1627 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1628 }
1629
1630 return false;
1631 }
1632
1633 /**
1634 * User interface handler for the "unwatch" action.
1635 */
1636 function unwatch() {
1637
1638 global $wgUser, $wgOut;
1639
1640 if ( $wgUser->isAnon() ) {
1641 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1642 return;
1643 }
1644 if ( wfReadOnly() ) {
1645 $wgOut->readOnlyPage();
1646 return;
1647 }
1648
1649 if( $this->doUnwatch() ) {
1650 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1651 $wgOut->setRobotpolicy( 'noindex,follow' );
1652
1653 $link = $this->mTitle->getPrefixedText();
1654 $text = wfMsg( 'removedwatchtext', $link );
1655 $wgOut->addWikiText( $text );
1656 }
1657
1658 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1659 }
1660
1661 /**
1662 * Stop watching a page
1663 * @return bool true on successful unwatch
1664 */
1665 function doUnwatch() {
1666 global $wgUser;
1667 if( $wgUser->isAnon() ) {
1668 return false;
1669 }
1670
1671 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1672 $wgUser->removeWatch( $this->mTitle );
1673 $wgUser->saveSettings();
1674
1675 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1676 }
1677
1678 return false;
1679 }
1680
1681 /**
1682 * action=protect handler
1683 */
1684 function protect() {
1685 require_once 'ProtectionForm.php';
1686 $form = new ProtectionForm( $this );
1687 $form->show();
1688 }
1689
1690 /**
1691 * action=unprotect handler (alias)
1692 */
1693 function unprotect() {
1694 $this->protect();
1695 }
1696
1697 /**
1698 * Update the article's restriction field, and leave a log entry.
1699 *
1700 * @param array $limit set of restriction keys
1701 * @param string $reason
1702 * @return bool true on success
1703 */
1704 function updateRestrictions( $limit = array(), $reason = '' ) {
1705 global $wgUser, $wgRestrictionTypes, $wgContLang;
1706
1707 $id = $this->mTitle->getArticleID();
1708 if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
1709 return false;
1710 }
1711
1712 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1713 # we expect a single selection, but the schema allows otherwise.
1714 $current = array();
1715 foreach( $wgRestrictionTypes as $action )
1716 $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
1717
1718 $current = Article::flattenRestrictions( $current );
1719 $updated = Article::flattenRestrictions( $limit );
1720
1721 $changed = ( $current != $updated );
1722 $protect = ( $updated != '' );
1723
1724 # If nothing's changed, do nothing
1725 if( $changed ) {
1726 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1727
1728 $dbw =& wfGetDB( DB_MASTER );
1729
1730 # Prepare a null revision to be added to the history
1731 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
1732 if( $reason )
1733 $comment .= ": $reason";
1734 if( $protect )
1735 $comment .= " [$updated]";
1736 $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
1737 $nullRevId = $nullRevision->insertOn( $dbw );
1738
1739 # Update page record
1740 $dbw->update( 'page',
1741 array( /* SET */
1742 'page_touched' => $dbw->timestamp(),
1743 'page_restrictions' => $updated,
1744 'page_latest' => $nullRevId
1745 ), array( /* WHERE */
1746 'page_id' => $id
1747 ), 'Article::protect'
1748 );
1749 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1750
1751 # Update the protection log
1752 $log = new LogPage( 'protect' );
1753 if( $protect ) {
1754 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
1755 } else {
1756 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1757 }
1758
1759 } # End hook
1760 } # End "changed" check
1761
1762 return true;
1763 }
1764
1765 /**
1766 * Take an array of page restrictions and flatten it to a string
1767 * suitable for insertion into the page_restrictions field.
1768 * @param array $limit
1769 * @return string
1770 * @private
1771 */
1772 function flattenRestrictions( $limit ) {
1773 if( !is_array( $limit ) ) {
1774 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1775 }
1776 $bits = array();
1777 ksort( $limit );
1778 foreach( $limit as $action => $restrictions ) {
1779 if( $restrictions != '' ) {
1780 $bits[] = "$action=$restrictions";
1781 }
1782 }
1783 return implode( ':', $bits );
1784 }
1785
1786 /*
1787 * UI entry point for page deletion
1788 */
1789 function delete() {
1790 global $wgUser, $wgOut, $wgRequest;
1791 $fname = 'Article::delete';
1792 $confirm = $wgRequest->wasPosted() &&
1793 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1794 $reason = $wgRequest->getText( 'wpReason' );
1795
1796 # This code desperately needs to be totally rewritten
1797
1798 # Check permissions
1799 if( $wgUser->isAllowed( 'delete' ) ) {
1800 if( $wgUser->isBlocked() ) {
1801 $wgOut->blockedPage();
1802 return;
1803 }
1804 } else {
1805 $wgOut->permissionRequired( 'delete' );
1806 return;
1807 }
1808
1809 if( wfReadOnly() ) {
1810 $wgOut->readOnlyPage();
1811 return;
1812 }
1813
1814 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1815
1816 # Better double-check that it hasn't been deleted yet!
1817 $dbw =& wfGetDB( DB_MASTER );
1818 $conds = $this->mTitle->pageCond();
1819 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1820 if ( $latest === false ) {
1821 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1822 return;
1823 }
1824
1825 if( $confirm ) {
1826 $this->doDelete( $reason );
1827 return;
1828 }
1829
1830 # determine whether this page has earlier revisions
1831 # and insert a warning if it does
1832 $maxRevisions = 20;
1833 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1834
1835 if( count( $authors ) > 1 && !$confirm ) {
1836 $skin=$wgUser->getSkin();
1837 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1838 }
1839
1840 # If a single user is responsible for all revisions, find out who they are
1841 if ( count( $authors ) == $maxRevisions ) {
1842 // Query bailed out, too many revisions to find out if they're all the same
1843 $authorOfAll = false;
1844 } else {
1845 $authorOfAll = reset( $authors );
1846 foreach ( $authors as $author ) {
1847 if ( $authorOfAll != $author ) {
1848 $authorOfAll = false;
1849 break;
1850 }
1851 }
1852 }
1853 # Fetch article text
1854 $rev = Revision::newFromTitle( $this->mTitle );
1855
1856 if( !is_null( $rev ) ) {
1857 # if this is a mini-text, we can paste part of it into the deletion reason
1858 $text = $rev->getText();
1859
1860 #if this is empty, an earlier revision may contain "useful" text
1861 $blanked = false;
1862 if( $text == '' ) {
1863 $prev = $rev->getPrevious();
1864 if( $prev ) {
1865 $text = $prev->getText();
1866 $blanked = true;
1867 }
1868 }
1869
1870 $length = strlen( $text );
1871
1872 # this should not happen, since it is not possible to store an empty, new
1873 # page. Let's insert a standard text in case it does, though
1874 if( $length == 0 && $reason === '' ) {
1875 $reason = wfMsgForContent( 'exblank' );
1876 }
1877
1878 if( $length < 500 && $reason === '' ) {
1879 # comment field=255, let's grep the first 150 to have some user
1880 # space left
1881 global $wgContLang;
1882 $text = $wgContLang->truncate( $text, 150, '...' );
1883
1884 # let's strip out newlines
1885 $text = preg_replace( "/[\n\r]/", '', $text );
1886
1887 if( !$blanked ) {
1888 if( $authorOfAll === false ) {
1889 $reason = wfMsgForContent( 'excontent', $text );
1890 } else {
1891 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1892 }
1893 } else {
1894 $reason = wfMsgForContent( 'exbeforeblank', $text );
1895 }
1896 }
1897 }
1898
1899 return $this->confirmDelete( '', $reason );
1900 }
1901
1902 /**
1903 * Get the last N authors
1904 * @param int $num Number of revisions to get
1905 * @param string $revLatest The latest rev_id, selected from the master (optional)
1906 * @return array Array of authors, duplicates not removed
1907 */
1908 function getLastNAuthors( $num, $revLatest = 0 ) {
1909 $fname = 'Article::getLastNAuthors';
1910 wfProfileIn( $fname );
1911
1912 // First try the slave
1913 // If that doesn't have the latest revision, try the master
1914 $continue = 2;
1915 $db =& wfGetDB( DB_SLAVE );
1916 do {
1917 $res = $db->select( array( 'page', 'revision' ),
1918 array( 'rev_id', 'rev_user_text' ),
1919 array(
1920 'page_namespace' => $this->mTitle->getNamespace(),
1921 'page_title' => $this->mTitle->getDBkey(),
1922 'rev_page = page_id'
1923 ), $fname, $this->getSelectOptions( array(
1924 'ORDER BY' => 'rev_timestamp DESC',
1925 'LIMIT' => $num
1926 ) )
1927 );
1928 if ( !$res ) {
1929 wfProfileOut( $fname );
1930 return array();
1931 }
1932 $row = $db->fetchObject( $res );
1933 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1934 $db =& wfGetDB( DB_MASTER );
1935 $continue--;
1936 } else {
1937 $continue = 0;
1938 }
1939 } while ( $continue );
1940
1941 $authors = array( $row->rev_user_text );
1942 while ( $row = $db->fetchObject( $res ) ) {
1943 $authors[] = $row->rev_user_text;
1944 }
1945 wfProfileOut( $fname );
1946 return $authors;
1947 }
1948
1949 /**
1950 * Output deletion confirmation dialog
1951 */
1952 function confirmDelete( $par, $reason ) {
1953 global $wgOut, $wgUser;
1954
1955 wfDebug( "Article::confirmDelete\n" );
1956
1957 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1958 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1959 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1960 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1961
1962 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1963
1964 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1965 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1966 $token = htmlspecialchars( $wgUser->editToken() );
1967
1968 $wgOut->addHTML( "
1969 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1970 <table border='0'>
1971 <tr>
1972 <td align='right'>
1973 <label for='wpReason'>{$delcom}:</label>
1974 </td>
1975 <td align='left'>
1976 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1977 </td>
1978 </tr>
1979 <tr>
1980 <td>&nbsp;</td>
1981 <td>
1982 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1983 </td>
1984 </tr>
1985 </table>
1986 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1987 </form>\n" );
1988
1989 $wgOut->returnToMain( false );
1990 }
1991
1992
1993 /**
1994 * Perform a deletion and output success or failure messages
1995 */
1996 function doDelete( $reason ) {
1997 global $wgOut, $wgUser;
1998 $fname = 'Article::doDelete';
1999 wfDebug( $fname."\n" );
2000
2001 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
2002 if ( $this->doDeleteArticle( $reason ) ) {
2003 $deleted = $this->mTitle->getPrefixedText();
2004
2005 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2006 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2007
2008 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2009 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2010
2011 $wgOut->addWikiText( $text );
2012 $wgOut->returnToMain( false );
2013 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2014 } else {
2015 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2016 }
2017 }
2018 }
2019
2020 /**
2021 * Back-end article deletion
2022 * Deletes the article with database consistency, writes logs, purges caches
2023 * Returns success
2024 */
2025 function doDeleteArticle( $reason ) {
2026 global $wgUseSquid, $wgDeferredUpdateList;
2027 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2028
2029 $fname = 'Article::doDeleteArticle';
2030 wfDebug( $fname."\n" );
2031
2032 $dbw =& wfGetDB( DB_MASTER );
2033 $ns = $this->mTitle->getNamespace();
2034 $t = $this->mTitle->getDBkey();
2035 $id = $this->mTitle->getArticleID();
2036
2037 if ( $t == '' || $id == 0 ) {
2038 return false;
2039 }
2040
2041 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2042 array_push( $wgDeferredUpdateList, $u );
2043
2044 $linksTo = $this->mTitle->getLinksTo();
2045
2046 # Squid purging
2047 if ( $wgUseSquid ) {
2048 $urls = array(
2049 $this->mTitle->getInternalURL(),
2050 $this->mTitle->getInternalURL( 'history' )
2051 );
2052
2053 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
2054 array_push( $wgPostCommitUpdateList, $u );
2055
2056 }
2057
2058 # Client and file cache invalidation
2059 Title::touchArray( $linksTo );
2060
2061
2062 // For now, shunt the revision data into the archive table.
2063 // Text is *not* removed from the text table; bulk storage
2064 // is left intact to avoid breaking block-compression or
2065 // immutable storage schemes.
2066 //
2067 // For backwards compatibility, note that some older archive
2068 // table entries will have ar_text and ar_flags fields still.
2069 //
2070 // In the future, we may keep revisions and mark them with
2071 // the rev_deleted field, which is reserved for this purpose.
2072 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2073 array(
2074 'ar_namespace' => 'page_namespace',
2075 'ar_title' => 'page_title',
2076 'ar_comment' => 'rev_comment',
2077 'ar_user' => 'rev_user',
2078 'ar_user_text' => 'rev_user_text',
2079 'ar_timestamp' => 'rev_timestamp',
2080 'ar_minor_edit' => 'rev_minor_edit',
2081 'ar_rev_id' => 'rev_id',
2082 'ar_text_id' => 'rev_text_id',
2083 ), array(
2084 'page_id' => $id,
2085 'page_id = rev_page'
2086 ), $fname
2087 );
2088
2089 # Now that it's safely backed up, delete it
2090 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2091 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2092
2093 if ($wgUseTrackbacks)
2094 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2095
2096 # Clean up recentchanges entries...
2097 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2098
2099 # Finally, clean up the link tables
2100 $t = $this->mTitle->getPrefixedDBkey();
2101
2102 Article::onArticleDelete( $this->mTitle );
2103
2104 # Delete outgoing links
2105 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2106 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2107 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2108 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2109 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2110 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2111
2112 # Log the deletion
2113 $log = new LogPage( 'delete' );
2114 $log->addEntry( 'delete', $this->mTitle, $reason );
2115
2116 # Clear the cached article id so the interface doesn't act like we exist
2117 $this->mTitle->resetArticleID( 0 );
2118 $this->mTitle->mArticleID = 0;
2119 return true;
2120 }
2121
2122 /**
2123 * Revert a modification
2124 */
2125 function rollback() {
2126 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2127 $fname = 'Article::rollback';
2128
2129 if( $wgUser->isAllowed( 'rollback' ) ) {
2130 if( $wgUser->isBlocked() ) {
2131 $wgOut->blockedPage();
2132 return;
2133 }
2134 } else {
2135 $wgOut->permissionRequired( 'rollback' );
2136 return;
2137 }
2138
2139 if ( wfReadOnly() ) {
2140 $wgOut->readOnlyPage( $this->getContent() );
2141 return;
2142 }
2143 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2144 array( $this->mTitle->getPrefixedText(),
2145 $wgRequest->getVal( 'from' ) ) ) ) {
2146 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2147 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2148 return;
2149 }
2150 $dbw =& wfGetDB( DB_MASTER );
2151
2152 # Enhanced rollback, marks edits rc_bot=1
2153 $bot = $wgRequest->getBool( 'bot' );
2154
2155 # Replace all this user's current edits with the next one down
2156 $tt = $this->mTitle->getDBKey();
2157 $n = $this->mTitle->getNamespace();
2158
2159 # Get the last editor, lock table exclusively
2160 $dbw->begin();
2161 $current = Revision::newFromTitle( $this->mTitle );
2162 if( is_null( $current ) ) {
2163 # Something wrong... no page?
2164 $dbw->rollback();
2165 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2166 return;
2167 }
2168
2169 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2170 if( $from != $current->getUserText() ) {
2171 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2172 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2173 htmlspecialchars( $this->mTitle->getPrefixedText()),
2174 htmlspecialchars( $from ),
2175 htmlspecialchars( $current->getUserText() ) ) );
2176 if( $current->getComment() != '') {
2177 $wgOut->addHTML(
2178 wfMsg( 'editcomment',
2179 htmlspecialchars( $current->getComment() ) ) );
2180 }
2181 return;
2182 }
2183
2184 # Get the last edit not by this guy
2185 $user = intval( $current->getUser() );
2186 $user_text = $dbw->addQuotes( $current->getUserText() );
2187 $s = $dbw->selectRow( 'revision',
2188 array( 'rev_id', 'rev_timestamp' ),
2189 array(
2190 'rev_page' => $current->getPage(),
2191 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2192 ), $fname,
2193 array(
2194 'USE INDEX' => 'page_timestamp',
2195 'ORDER BY' => 'rev_timestamp DESC' )
2196 );
2197 if( $s === false ) {
2198 # Something wrong
2199 $dbw->rollback();
2200 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2201 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2202 return;
2203 }
2204
2205 $set = array();
2206 if ( $bot ) {
2207 # Mark all reverted edits as bot
2208 $set['rc_bot'] = 1;
2209 }
2210 if ( $wgUseRCPatrol ) {
2211 # Mark all reverted edits as patrolled
2212 $set['rc_patrolled'] = 1;
2213 }
2214
2215 if ( $set ) {
2216 $dbw->update( 'recentchanges', $set,
2217 array( /* WHERE */
2218 'rc_cur_id' => $current->getPage(),
2219 'rc_user_text' => $current->getUserText(),
2220 "rc_timestamp > '{$s->rev_timestamp}'",
2221 ), $fname
2222 );
2223 }
2224
2225 # Get the edit summary
2226 $target = Revision::newFromId( $s->rev_id );
2227 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2228 $newComment = $wgRequest->getText( 'summary', $newComment );
2229
2230 # Save it!
2231 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2232 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2233 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2234
2235 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2236 Article::onArticleEdit( $this->mTitle );
2237
2238 $dbw->commit();
2239 $wgOut->returnToMain( false );
2240 }
2241
2242
2243 /**
2244 * Do standard deferred updates after page view
2245 * @private
2246 */
2247 function viewUpdates() {
2248 global $wgDeferredUpdateList;
2249
2250 if ( 0 != $this->getID() ) {
2251 global $wgDisableCounters;
2252 if( !$wgDisableCounters ) {
2253 Article::incViewCount( $this->getID() );
2254 $u = new SiteStatsUpdate( 1, 0, 0 );
2255 array_push( $wgDeferredUpdateList, $u );
2256 }
2257 }
2258
2259 # Update newtalk / watchlist notification status
2260 global $wgUser;
2261 $wgUser->clearNotification( $this->mTitle );
2262 }
2263
2264 /**
2265 * Do standard deferred updates after page edit.
2266 * Every 1000th edit, prune the recent changes table.
2267 * @private
2268 * @param string $text
2269 */
2270 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2271 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2272
2273 $fname = 'Article::editUpdates';
2274 wfProfileIn( $fname );
2275
2276 # Parse the text
2277 $options = new ParserOptions;
2278 $options->setTidy(true);
2279 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2280
2281 # Save it to the parser cache
2282 $parserCache =& ParserCache::singleton();
2283 $parserCache->save( $poutput, $this, $wgUser );
2284
2285 # Update the links tables
2286 $u = new LinksUpdate( $this->mTitle, $poutput );
2287 $u->doUpdate();
2288
2289 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2290 wfSeedRandom();
2291 if ( 0 == mt_rand( 0, 999 ) ) {
2292 # Periodically flush old entries from the recentchanges table.
2293 global $wgRCMaxAge;
2294
2295 $dbw =& wfGetDB( DB_MASTER );
2296 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2297 $recentchanges = $dbw->tableName( 'recentchanges' );
2298 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2299 $dbw->query( $sql );
2300 }
2301 }
2302
2303 $id = $this->getID();
2304 $title = $this->mTitle->getPrefixedDBkey();
2305 $shortTitle = $this->mTitle->getDBkey();
2306
2307 if ( 0 == $id ) {
2308 wfProfileOut( $fname );
2309 return;
2310 }
2311
2312 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2313 array_push( $wgDeferredUpdateList, $u );
2314 $u = new SearchUpdate( $id, $title, $text );
2315 array_push( $wgDeferredUpdateList, $u );
2316
2317 # If this is another user's talk page, update newtalk
2318
2319 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2320 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2321 $other = User::newFromName( $shortTitle );
2322 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2323 // An anonymous user
2324 $other = new User();
2325 $other->setName( $shortTitle );
2326 }
2327 if( $other ) {
2328 $other->setNewtalk( true );
2329 }
2330 }
2331 }
2332
2333 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2334 $wgMessageCache->replace( $shortTitle, $text );
2335 }
2336
2337 wfProfileOut( $fname );
2338 }
2339
2340 /**
2341 * Generate the navigation links when browsing through an article revisions
2342 * It shows the information as:
2343 * Revision as of \<date\>; view current revision
2344 * \<- Previous version | Next Version -\>
2345 *
2346 * @private
2347 * @param string $oldid Revision ID of this article revision
2348 */
2349 function setOldSubtitle( $oldid=0 ) {
2350 global $wgLang, $wgOut, $wgUser;
2351
2352 $current = ( $oldid == $this->mLatest );
2353 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2354 $sk = $wgUser->getSkin();
2355 $lnk = $current
2356 ? wfMsg( 'currentrevisionlink' )
2357 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2358 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
2359 $prevlink = $prev
2360 ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2361 : wfMsg( 'previousrevision' );
2362 $nextlink = $current
2363 ? wfMsg( 'nextrevision' )
2364 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2365 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2366 $wgOut->setSubtitle( $r );
2367 }
2368
2369 /**
2370 * This function is called right before saving the wikitext,
2371 * so we can do things like signatures and links-in-context.
2372 *
2373 * @param string $text
2374 */
2375 function preSaveTransform( $text ) {
2376 global $wgParser, $wgUser;
2377 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2378 }
2379
2380 /* Caching functions */
2381
2382 /**
2383 * checkLastModified returns true if it has taken care of all
2384 * output to the client that is necessary for this request.
2385 * (that is, it has sent a cached version of the page)
2386 */
2387 function tryFileCache() {
2388 static $called = false;
2389 if( $called ) {
2390 wfDebug( " tryFileCache() -- called twice!?\n" );
2391 return;
2392 }
2393 $called = true;
2394 if($this->isFileCacheable()) {
2395 $touched = $this->mTouched;
2396 $cache = new CacheManager( $this->mTitle );
2397 if($cache->isFileCacheGood( $touched )) {
2398 wfDebug( " tryFileCache() - about to load\n" );
2399 $cache->loadFromFileCache();
2400 return true;
2401 } else {
2402 wfDebug( " tryFileCache() - starting buffer\n" );
2403 ob_start( array(&$cache, 'saveToFileCache' ) );
2404 }
2405 } else {
2406 wfDebug( " tryFileCache() - not cacheable\n" );
2407 }
2408 }
2409
2410 /**
2411 * Check if the page can be cached
2412 * @return bool
2413 */
2414 function isFileCacheable() {
2415 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2416 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2417
2418 return $wgUseFileCache
2419 and (!$wgShowIPinHeader)
2420 and ($this->getID() != 0)
2421 and ($wgUser->isAnon())
2422 and (!$wgUser->getNewtalk())
2423 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2424 and (empty( $action ) || $action == 'view')
2425 and (!isset($oldid))
2426 and (!isset($diff))
2427 and (!isset($redirect))
2428 and (!isset($printable))
2429 and (!$this->mRedirectedFrom);
2430 }
2431
2432 /**
2433 * Loads page_touched and returns a value indicating if it should be used
2434 *
2435 */
2436 function checkTouched() {
2437 $fname = 'Article::checkTouched';
2438 if( !$this->mDataLoaded ) {
2439 $this->loadPageData();
2440 }
2441 return !$this->mIsRedirect;
2442 }
2443
2444 /**
2445 * Get the page_touched field
2446 */
2447 function getTouched() {
2448 # Ensure that page data has been loaded
2449 if( !$this->mDataLoaded ) {
2450 $this->loadPageData();
2451 }
2452 return $this->mTouched;
2453 }
2454
2455 /**
2456 * Get the page_latest field
2457 */
2458 function getLatest() {
2459 if ( !$this->mDataLoaded ) {
2460 $this->loadPageData();
2461 }
2462 return $this->mLatest;
2463 }
2464
2465 /**
2466 * Edit an article without doing all that other stuff
2467 * The article must already exist; link tables etc
2468 * are not updated, caches are not flushed.
2469 *
2470 * @param string $text text submitted
2471 * @param string $comment comment submitted
2472 * @param bool $minor whereas it's a minor modification
2473 */
2474 function quickEdit( $text, $comment = '', $minor = 0 ) {
2475 $fname = 'Article::quickEdit';
2476 wfProfileIn( $fname );
2477
2478 $dbw =& wfGetDB( DB_MASTER );
2479 $dbw->begin();
2480 $revision = new Revision( array(
2481 'page' => $this->getId(),
2482 'text' => $text,
2483 'comment' => $comment,
2484 'minor_edit' => $minor ? 1 : 0,
2485 ) );
2486 $revisionId = $revision->insertOn( $dbw );
2487 $this->updateRevisionOn( $dbw, $revision );
2488 $dbw->commit();
2489
2490 wfProfileOut( $fname );
2491 }
2492
2493 /**
2494 * Used to increment the view counter
2495 *
2496 * @static
2497 * @param integer $id article id
2498 */
2499 function incViewCount( $id ) {
2500 $id = intval( $id );
2501 global $wgHitcounterUpdateFreq, $wgDBtype;
2502
2503 $dbw =& wfGetDB( DB_MASTER );
2504 $pageTable = $dbw->tableName( 'page' );
2505 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2506 $acchitsTable = $dbw->tableName( 'acchits' );
2507
2508 if( $wgHitcounterUpdateFreq <= 1 ){ //
2509 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2510 return;
2511 }
2512
2513 # Not important enough to warrant an error page in case of failure
2514 $oldignore = $dbw->ignoreErrors( true );
2515
2516 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2517
2518 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2519 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2520 # Most of the time (or on SQL errors), skip row count check
2521 $dbw->ignoreErrors( $oldignore );
2522 return;
2523 }
2524
2525 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2526 $row = $dbw->fetchObject( $res );
2527 $rown = intval( $row->n );
2528 if( $rown >= $wgHitcounterUpdateFreq ){
2529 wfProfileIn( 'Article::incViewCount-collect' );
2530 $old_user_abort = ignore_user_abort( true );
2531
2532 if ($wgDBtype == 'mysql')
2533 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2534 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
2535 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2536 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2537 'GROUP BY hc_id');
2538 $dbw->query("DELETE FROM $hitcounterTable");
2539 if ($wgDBtype == 'mysql')
2540 $dbw->query('UNLOCK TABLES');
2541 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2542 'WHERE page_id = hc_id');
2543 $dbw->query("DROP TABLE $acchitsTable");
2544
2545 ignore_user_abort( $old_user_abort );
2546 wfProfileOut( 'Article::incViewCount-collect' );
2547 }
2548 $dbw->ignoreErrors( $oldignore );
2549 }
2550
2551 /**#@+
2552 * The onArticle*() functions are supposed to be a kind of hooks
2553 * which should be called whenever any of the specified actions
2554 * are done.
2555 *
2556 * This is a good place to put code to clear caches, for instance.
2557 *
2558 * This is called on page move and undelete, as well as edit
2559 * @static
2560 * @param $title_obj a title object
2561 */
2562
2563 function onArticleCreate($title_obj) {
2564 global $wgUseSquid, $wgPostCommitUpdateList;
2565
2566 $title_obj->touchLinks();
2567 $titles = $title_obj->getLinksTo();
2568
2569 # Purge squid
2570 if ( $wgUseSquid ) {
2571 $urls = $title_obj->getSquidURLs();
2572 foreach ( $titles as $linkTitle ) {
2573 $urls[] = $linkTitle->getInternalURL();
2574 }
2575 $u = new SquidUpdate( $urls );
2576 array_push( $wgPostCommitUpdateList, $u );
2577 }
2578 }
2579
2580 function onArticleDelete( $title ) {
2581 global $wgMessageCache;
2582
2583 $title->touchLinks();
2584
2585 if( $title->getNamespace() == NS_MEDIAWIKI) {
2586 $wgMessageCache->replace( $title->getDBkey(), false );
2587 }
2588 }
2589
2590 /**
2591 * Purge caches on page update etc
2592 */
2593 function onArticleEdit( $title ) {
2594 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2595
2596 $urls = array();
2597
2598 // Template namespace? Purge all articles linking here.
2599 // FIXME: When a templatelinks table arrives, use it for all includes.
2600 if ( $title->getNamespace() == NS_TEMPLATE) {
2601 $titles = $title->getLinksTo();
2602 Title::touchArray( $titles );
2603 if ( $wgUseSquid ) {
2604 foreach ( $titles as $link ) {
2605 $urls[] = $link->getInternalURL();
2606 }
2607 }
2608 }
2609
2610 # Squid updates
2611 if ( $wgUseSquid ) {
2612 $urls = array_merge( $urls, $title->getSquidURLs() );
2613 $u = new SquidUpdate( $urls );
2614 array_push( $wgPostCommitUpdateList, $u );
2615 }
2616
2617 # File cache
2618 if ( $wgUseFileCache ) {
2619 $cm = new CacheManager( $title );
2620 @unlink( $cm->fileCacheName() );
2621 }
2622 }
2623
2624 /**#@-*/
2625
2626 /**
2627 * Info about this page
2628 * Called for ?action=info when $wgAllowPageInfo is on.
2629 *
2630 * @public
2631 */
2632 function info() {
2633 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2634 $fname = 'Article::info';
2635
2636 if ( !$wgAllowPageInfo ) {
2637 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2638 return;
2639 }
2640
2641 $page = $this->mTitle->getSubjectPage();
2642
2643 $wgOut->setPagetitle( $page->getPrefixedText() );
2644 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2645
2646 # first, see if the page exists at all.
2647 $exists = $page->getArticleId() != 0;
2648 if( !$exists ) {
2649 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2650 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2651 } else {
2652 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2653 }
2654 } else {
2655 $dbr =& wfGetDB( DB_SLAVE );
2656 $wl_clause = array(
2657 'wl_title' => $page->getDBkey(),
2658 'wl_namespace' => $page->getNamespace() );
2659 $numwatchers = $dbr->selectField(
2660 'watchlist',
2661 'COUNT(*)',
2662 $wl_clause,
2663 $fname,
2664 $this->getSelectOptions() );
2665
2666 $pageInfo = $this->pageCountInfo( $page );
2667 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2668
2669 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2670 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2671 if( $talkInfo ) {
2672 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2673 }
2674 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2675 if( $talkInfo ) {
2676 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2677 }
2678 $wgOut->addHTML( '</ul>' );
2679
2680 }
2681 }
2682
2683 /**
2684 * Return the total number of edits and number of unique editors
2685 * on a given page. If page does not exist, returns false.
2686 *
2687 * @param Title $title
2688 * @return array
2689 * @private
2690 */
2691 function pageCountInfo( $title ) {
2692 $id = $title->getArticleId();
2693 if( $id == 0 ) {
2694 return false;
2695 }
2696
2697 $dbr =& wfGetDB( DB_SLAVE );
2698
2699 $rev_clause = array( 'rev_page' => $id );
2700 $fname = 'Article::pageCountInfo';
2701
2702 $edits = $dbr->selectField(
2703 'revision',
2704 'COUNT(rev_page)',
2705 $rev_clause,
2706 $fname,
2707 $this->getSelectOptions() );
2708
2709 $authors = $dbr->selectField(
2710 'revision',
2711 'COUNT(DISTINCT rev_user_text)',
2712 $rev_clause,
2713 $fname,
2714 $this->getSelectOptions() );
2715
2716 return array( 'edits' => $edits, 'authors' => $authors );
2717 }
2718
2719 /**
2720 * Return a list of templates used by this article.
2721 * Uses the templatelinks table
2722 *
2723 * @return array Array of Title objects
2724 */
2725 function getUsedTemplates() {
2726 $result = array();
2727 $id = $this->mTitle->getArticleID();
2728 if( $id == 0 ) {
2729 return array();
2730 }
2731
2732 $dbr =& wfGetDB( DB_SLAVE );
2733 $res = $dbr->select( array( 'templatelinks' ),
2734 array( 'tl_namespace', 'tl_title' ),
2735 array( 'tl_from' => $id ),
2736 'Article:getUsedTemplates' );
2737 if ( false !== $res ) {
2738 if ( $dbr->numRows( $res ) ) {
2739 while ( $row = $dbr->fetchObject( $res ) ) {
2740 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2741 }
2742 }
2743 }
2744 $dbr->freeResult( $res );
2745 return $result;
2746 }
2747 }
2748
2749 ?>