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