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