e1d8adc40a2fbf79fad65adff374797e6691d0e2
[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 Wikipedia article and history.
18 *
19 * See design.doc 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 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mCountAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 /**#@-*/
38
39 /**
40 * Constructor and clear the article
41 * @param mixed &$title
42 */
43 function Article( &$title ) {
44 $this->mTitle =& $title;
45 $this->clear();
46 }
47
48 /**
49 * get the title object of the article
50 * @public
51 */
52 function getTitle() {
53 return $this->mTitle;
54 }
55
56 /**
57 * Clear the object
58 * @private
59 */
60 function clear() {
61 $this->mContentLoaded = false;
62 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
63 $this->mRedirectedFrom = $this->mUserText =
64 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
65 $this->mCountAdjustment = 0;
66 $this->mTouched = '19700101000000';
67 $this->mForUpdate = false;
68 }
69
70 /**
71 * Note that getContent/loadContent may follow redirects if
72 * not told otherwise, and so may cause a change to mTitle.
73 *
74 * @param $noredir
75 * @return Return the text of this revision
76 */
77 function getContent( $noredir ) {
78 global $wgRequest;
79
80 # Get variables from query string :P
81 $action = $wgRequest->getText( 'action', 'view' );
82 $section = $wgRequest->getText( 'section' );
83
84 $fname = 'Article::getContent';
85 wfProfileIn( $fname );
86
87 if ( 0 == $this->getID() ) {
88 if ( 'edit' == $action ) {
89 wfProfileOut( $fname );
90 return ''; # was "newarticletext", now moved above the box)
91 }
92 wfProfileOut( $fname );
93 return wfMsg( 'noarticletext' );
94 } else {
95 $this->loadContent( $noredir );
96 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
97 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
98 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle->getText()) &&
99 $action=='view'
100 ) {
101 wfProfileOut( $fname );
102 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
103 } else {
104 if($action=='edit') {
105 if($section!='') {
106 if($section=='new') {
107 wfProfileOut( $fname );
108 return '';
109 }
110
111 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
112 # comments to be stripped as well)
113 $rv=$this->getSection($this->mContent,$section);
114 wfProfileOut( $fname );
115 return $rv;
116 }
117 }
118 wfProfileOut( $fname );
119 return $this->mContent;
120 }
121 }
122 }
123
124 /**
125 * This function returns the text of a section, specified by a number ($section).
126 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
127 * the first section before any such heading (section 0).
128 *
129 * If a section contains subsections, these are also returned.
130 *
131 * @param string $text text to look in
132 * @param integer $section section number
133 * @return string text of the requested section
134 */
135 function getSection($text,$section) {
136
137 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
138 # comments to be stripped as well)
139 $striparray=array();
140 $parser=new Parser();
141 $parser->mOutputType=OT_WIKI;
142 $striptext=$parser->strip($text, $striparray, true);
143
144 # now that we can be sure that no pseudo-sections are in the source,
145 # split it up by section
146 $secs =
147 preg_split(
148 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
149 $striptext, -1,
150 PREG_SPLIT_DELIM_CAPTURE);
151 if($section==0) {
152 $rv=$secs[0];
153 } else {
154 $headline=$secs[$section*2-1];
155 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
156 $hlevel=$matches[1];
157
158 # translate wiki heading into level
159 if(strpos($hlevel,'=')!==false) {
160 $hlevel=strlen($hlevel);
161 }
162
163 $rv=$headline. $secs[$section*2];
164 $count=$section+1;
165
166 $break=false;
167 while(!empty($secs[$count*2-1]) && !$break) {
168
169 $subheadline=$secs[$count*2-1];
170 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
171 $subhlevel=$matches[1];
172 if(strpos($subhlevel,'=')!==false) {
173 $subhlevel=strlen($subhlevel);
174 }
175 if($subhlevel > $hlevel) {
176 $rv.=$subheadline.$secs[$count*2];
177 }
178 if($subhlevel <= $hlevel) {
179 $break=true;
180 }
181 $count++;
182
183 }
184 }
185 # reinsert stripped tags
186 $rv=$parser->unstrip($rv,$striparray);
187 $rv=$parser->unstripNoWiki($rv,$striparray);
188 $rv=trim($rv);
189 return $rv;
190
191 }
192
193 /**
194 * Return an array of the columns of the "cur"-table
195 */
196 function getContentFields() {
197 return $wgArticleContentFields = array(
198 'old_text','old_flags',
199 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
200 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
201 }
202
203 /**
204 * Return the oldid of the article that is to be shown.
205 * For requests with a "direction", this is not the oldid of the
206 * query
207 */
208 function getOldID() {
209 global $wgRequest, $wgOut;
210 static $lastid;
211
212 if ( isset( $lastid ) ) {
213 return $lastid;
214 }
215 # Query variables :P
216 $oldid = $wgRequest->getVal( 'oldid' );
217 if ( isset( $oldid ) ) {
218 $oldid = IntVal( $oldid );
219 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
220 $nextid = $this->mTitle->getNextRevisionID( $oldid );
221 if ( $nextid ) {
222 $oldid = $nextid;
223 } else {
224 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
225 }
226 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
227 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
228 if ( $previd ) {
229 $oldid = $previd;
230 } else {
231 # TODO
232 }
233 }
234 $lastid = $oldid;
235 }
236 return @$oldid; # "@" to be able to return "unset" without PHP complaining
237 }
238
239
240 /**
241 * Load the revision (including cur_text) into this object
242 */
243 function loadContent( $noredir = false ) {
244 global $wgOut, $wgRequest;
245
246 if ( $this->mContentLoaded ) return;
247
248 # Query variables :P
249 $oldid = $this->getOldID();
250 $redirect = $wgRequest->getVal( 'redirect' );
251
252 $fname = 'Article::loadContent';
253
254 # Pre-fill content with error message so that if something
255 # fails we'll have something telling us what we intended.
256
257 $t = $this->mTitle->getPrefixedText();
258
259 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no');
260 $this->mOldId = $oldid;
261 $this->fetchContent( $oldid, $noredir, true );
262 }
263
264 /**
265 * Get text of an article from database
266 * @param int $oldid 0 for whatever the latest revision is
267 * @param bool $noredir Set to true to avoid following redirects
268 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
269 * @return string
270 */
271 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
272 if ( $this->mContentLoaded ) {
273 return $this->mContent;
274 }
275 $dbr =& $this->getDB();
276 $fname = 'Article::fetchContent';
277
278 # Pre-fill content with error message so that if something
279 # fails we'll have something telling us what we intended.
280 $t = $this->mTitle->getPrefixedText();
281 if( $oldid ) {
282 $t .= ',oldid='.$oldid;
283 }
284 if( isset( $redirect ) ) {
285 $redirect = ($redirect == 'no') ? 'no' : 'yes';
286 $t .= ',redirect='.$redirect;
287 }
288 $this->mContent = wfMsg( 'missingarticle', $t );
289
290 if( !$oldid ) {
291 # Retrieve current version
292 $id = $this->getID();
293 if ( 0 == $id ) {
294 return false;
295 }
296
297 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
298 $this->getContentFields(),
299 "page_id='$id' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
300 $fname, $this->getSelectOptions() );
301 } else {
302 # Historical revision
303 $s = $dbr->selectRow( array( 'text', 'revision', 'page' ),
304 $this->getContentFields(),
305 "rev_page=page_id AND rev_id='$oldid' AND old_id=rev_id",
306 $fname, $this->getSelectOptions() );
307 }
308 if ( $s === false ) {
309 return false;
310 }
311
312 # If we got a redirect, follow it (unless we've been told
313 # not to by either the function parameter or the query
314 if ( !$oldid && !$noredir ) {
315 $rt = Title::newFromRedirect( Revision::getRevisionText( $s ) );
316 # process if title object is valid and not special:userlogout
317 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
318 # Gotta hand redirects to special pages differently:
319 # Fill the HTTP response "Location" header and ignore
320 # the rest of the page we're on.
321 if( $globalTitle ) {
322 global $wgOut;
323 if ( $rt->getInterwiki() != '' ) {
324 $wgOut->redirect( $rt->getFullURL() ) ;
325 return false;
326 }
327 if ( $rt->getNamespace() == NS_SPECIAL ) {
328 $wgOut->redirect( $rt->getFullURL() );
329 return false;
330 }
331 }
332 $rid = $rt->getArticleID();
333 if ( 0 != $rid ) {
334 $redirRow = $dbr->selectRow( array( 'text', 'revision', 'page' ),
335 $this->getContentFields(),
336 "page_id='$rid' AND rev_page=page_id AND rev_id=page_latest AND old_id=rev_id",
337 $fname, $this->getSelectOptions() );
338
339 if ( $redirRow !== false ) {
340 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
341 $this->mTitle = $rt;
342 $s = $redirRow;
343 }
344 }
345 }
346 }
347
348 # if the title's different from expected, update...
349 if( $globalTitle &&
350 ( $this->mTitle->getNamespace() != $s->page_namespace ||
351 $this->mTitle->getDBkey() != $s->page_title ) ) {
352 $oldTitle = Title::makeTitle( $s->page_namesapce, $s->page_title );
353 $this->mTitle = $oldTitle;
354 global $wgTitle;
355 $wgTitle = $oldTitle;
356 }
357
358 # Back to the business at hand...
359 $this->mCounter = $s->page_counter;
360 $this->mTitle->mRestrictions = explode( ',', trim( $s->page_restrictions ) );
361 $this->mTitle->mRestrictionsLoaded = true;
362 $this->mTouched = wfTimestamp( TS_MW, $s->page_touched );
363
364 $this->mContent = Revision::getRevisionText( $s );
365
366 $this->mUser = $s->rev_user;
367 $this->mUserText = $s->rev_user_text;
368 $this->mComment = $s->rev_comment;
369 $this->mTimestamp = wfTimestamp( TS_MW, $s->rev_timestamp );
370
371 $this->mContentLoaded = true;
372 return $this->mContent;
373 }
374
375 /**
376 * Gets the article text without using so many damn globals
377 * Returns false on error
378 *
379 * @param integer $oldid
380 */
381 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
382 return $this->fetchContent( $oldid, $noredir, false );
383 }
384
385 /**
386 * Read/write accessor to select FOR UPDATE
387 */
388 function forUpdate( $x = NULL ) {
389 return wfSetVar( $this->mForUpdate, $x );
390 }
391
392 /**
393 * Get the database which should be used for reads
394 */
395 function &getDB() {
396 if ( $this->mForUpdate ) {
397 return wfGetDB( DB_MASTER );
398 } else {
399 return wfGetDB( DB_SLAVE );
400 }
401 }
402
403 /**
404 * Get options for all SELECT statements
405 * Can pass an option array, to which the class-wide options will be appended
406 */
407 function getSelectOptions( $options = '' ) {
408 if ( $this->mForUpdate ) {
409 if ( is_array( $options ) ) {
410 $options[] = 'FOR UPDATE';
411 } else {
412 $options = 'FOR UPDATE';
413 }
414 }
415 return $options;
416 }
417
418 /**
419 * Return the Article ID
420 */
421 function getID() {
422 if( $this->mTitle ) {
423 return $this->mTitle->getArticleID();
424 } else {
425 return 0;
426 }
427 }
428
429 /**
430 * Get the view count for this article
431 */
432 function getCount() {
433 if ( -1 == $this->mCounter ) {
434 $id = $this->getID();
435 $dbr =& $this->getDB();
436 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
437 'Article::getCount', $this->getSelectOptions() );
438 }
439 return $this->mCounter;
440 }
441
442 /**
443 * Would the given text make this article a "good" article (i.e.,
444 * suitable for including in the article count)?
445 * @param string $text Text to analyze
446 * @return integer 1 if it can be counted else 0
447 */
448 function isCountable( $text ) {
449 global $wgUseCommaCount;
450
451 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
452 if ( $this->isRedirect( $text ) ) { return 0; }
453 $token = ($wgUseCommaCount ? ',' : '[[' );
454 if ( false === strstr( $text, $token ) ) { return 0; }
455 return 1;
456 }
457
458 /**
459 * Tests if the article text represents a redirect
460 */
461 function isRedirect( $text = false ) {
462 if ( $text === false ) {
463 $this->loadContent();
464 $titleObj = Title::newFromRedirect( $this->mText );
465 } else {
466 $titleObj = Title::newFromRedirect( $text );
467 }
468 return $titleObj !== NULL;
469 }
470
471 /**
472 * Loads everything except the text
473 * This isn't necessary for all uses, so it's only done if needed.
474 * @private
475 */
476 function loadLastEdit() {
477 global $wgOut;
478
479 if ( -1 != $this->mUser )
480 return;
481
482 # New or non-existent articles have no user information
483 $id = $this->getID();
484 if ( 0 == $id ) return;
485
486 $fname = 'Article::loadLastEdit';
487
488 $dbr =& $this->getDB();
489 $s = $dbr->selectRow( array( 'revision', 'page') ,
490 array( 'rev_user','rev_user_text','rev_timestamp', 'rev_comment','rev_minor_edit' ),
491 array( 'page_id' => $id, 'page_latest=rev_id' ), $fname, $this->getSelectOptions() );
492
493 if ( $s !== false ) {
494 $this->mUser = $s->rev_user;
495 $this->mUserText = $s->rev_user_text;
496 $this->mTimestamp = wfTimestamp(TS_MW,$s->rev_timestamp);
497 $this->mComment = $s->rev_comment;
498 $this->mMinorEdit = $s->rev_minor_edit;
499 }
500 }
501
502 function getTimestamp() {
503 $this->loadLastEdit();
504 return $this->mTimestamp;
505 }
506
507 function getUser() {
508 $this->loadLastEdit();
509 return $this->mUser;
510 }
511
512 function getUserText() {
513 $this->loadLastEdit();
514 return $this->mUserText;
515 }
516
517 function getComment() {
518 $this->loadLastEdit();
519 return $this->mComment;
520 }
521
522 function getMinorEdit() {
523 $this->loadLastEdit();
524 return $this->mMinorEdit;
525 }
526
527 function getContributors($limit = 0, $offset = 0) {
528 $fname = 'Article::getContributors';
529
530 # XXX: this is expensive; cache this info somewhere.
531
532 $title = $this->mTitle;
533 $contribs = array();
534 $dbr =& $this->getDB();
535 $revTable = $dbr->tableName( 'revision' );
536 $userTable = $dbr->tableName( 'user' );
537 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
538 $ns = $title->getNamespace();
539 $user = $this->getUser();
540 $pageId = $this->getId();
541
542 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
543 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
544 WHERE rev_page = $pageId
545 AND rev_user != $user
546 GROUP BY rev_user, rev_user_text, user_real_name
547 ORDER BY timestamp DESC";
548
549 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
550 $sql .= ' '. $this->getSelectOptions();
551
552 $res = $dbr->query($sql, $fname);
553
554 while ( $line = $dbr->fetchObject( $res ) ) {
555 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
556 }
557
558 $dbr->freeResult($res);
559 return $contribs;
560 }
561
562 /**
563 * This is the default action of the script: just view the page of
564 * the given title.
565 */
566 function view() {
567 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
568 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
569 global $wgEnotif;
570 $sk = $wgUser->getSkin();
571
572 $fname = 'Article::view';
573 wfProfileIn( $fname );
574 # Get variables from query string
575 $oldid = $this->getOldID();
576 $diff = $wgRequest->getVal( 'diff' );
577 $rcid = $wgRequest->getVal( 'rcid' );
578
579 $wgOut->setArticleFlag( true );
580 $wgOut->setRobotpolicy( 'index,follow' );
581 # If we got diff and oldid in the query, we want to see a
582 # diff page instead of the article.
583
584 if ( !is_null( $diff ) ) {
585 require_once( 'DifferenceEngine.php' );
586 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
587 $de = new DifferenceEngine( $oldid, $diff, $rcid );
588 $de->showDiffPage();
589 if( $diff == 0 ) {
590 # Run view updates for current revision only
591 $this->viewUpdates();
592 }
593 wfProfileOut( $fname );
594 return;
595 }
596 if ( empty( $oldid ) && $this->checkTouched() ) {
597 if( $wgOut->checkLastModified( $this->mTouched ) ){
598 wfProfileOut( $fname );
599 return;
600 } else if ( $this->tryFileCache() ) {
601 # tell wgOut that output is taken care of
602 $wgOut->disable();
603 $this->viewUpdates();
604 wfProfileOut( $fname );
605 return;
606 }
607 }
608 # Should the parser cache be used?
609 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
610 $pcache = true;
611 } else {
612 $pcache = false;
613 }
614
615 $outputDone = false;
616 if ( $pcache ) {
617 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
618 $outputDone = true;
619 }
620 }
621 if ( !$outputDone ) {
622 $text = $this->getContent( false ); # May change mTitle by following a redirect
623
624 # Another whitelist check in case oldid or redirects are altering the title
625 if ( !$this->mTitle->userCanRead() ) {
626 $wgOut->loginToUse();
627 $wgOut->output();
628 exit;
629 }
630
631
632 # We're looking at an old revision
633
634 if ( !empty( $oldid ) ) {
635 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
636 $wgOut->setRobotpolicy( 'noindex,follow' );
637 }
638 if ( '' != $this->mRedirectedFrom ) {
639 $sk = $wgUser->getSkin();
640 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
641 'redirect=no' );
642 $s = wfMsg( 'redirectedfrom', $redir );
643 $wgOut->setSubtitle( $s );
644
645 # Can't cache redirects
646 $pcache = false;
647 }
648
649 # wrap user css and user js in pre and don't parse
650 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
651 if (
652 $this->mTitle->getNamespace() == NS_USER &&
653 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
654 ) {
655 $wgOut->addWikiText( wfMsg('clearyourcache'));
656 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
657 } else if ( $rt = Title::newFromRedirect( $text ) ) {
658 # Display redirect
659 $imageUrl = $wgStylePath.'/common/images/redirect.png';
660 $targetUrl = $rt->escapeLocalURL();
661 $titleText = htmlspecialchars( $rt->getPrefixedText() );
662 $link = $sk->makeLinkObj( $rt );
663
664 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
665 '<span class="redirectText">'.$link.'</span>' );
666
667 } else if ( $pcache ) {
668 # Display content and save to parser cache
669 $wgOut->addPrimaryWikiText( $text, $this );
670 } else {
671 # Display content, don't attempt to save to parser cache
672 $wgOut->addWikiText( $text );
673 }
674 }
675 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
676 # If we have been passed an &rcid= parameter, we want to give the user a
677 # chance to mark this new article as patrolled.
678 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->getID() != 0 &&
679 ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
680 {
681 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
682 $sk->makeKnownLinkObj ( $this->mTitle, wfMsg ( 'markaspatrolledtext' ),
683 'action=markpatrolled&rcid='.$rcid )
684 ) );
685 }
686
687 # Put link titles into the link cache
688 $wgOut->transformBuffer();
689
690 # Add link titles as META keywords
691 $wgOut->addMetaTags() ;
692
693 $this->viewUpdates();
694 wfProfileOut( $fname );
695
696 $wgUser->clearNotification( $this->mTitle );
697 }
698
699 /**
700 * Theoretically we could defer these whole insert and update
701 * functions for after display, but that's taking a big leap
702 * of faith, and we want to be able to report database
703 * errors at some point.
704 * @private
705 */
706 function insertNewArticle( $text, $summary, $isminor, $watchthis ) {
707 global $wgOut, $wgUser;
708 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
709
710 $fname = 'Article::insertNewArticle';
711
712 $this->mCountAdjustment = $this->isCountable( $text );
713
714 $ns = $this->mTitle->getNamespace();
715 $ttl = $this->mTitle->getDBkey();
716 $text = $this->preSaveTransform( $text );
717 if ( $this->isRedirect( $text ) ) { $redir = 1; }
718 else { $redir = 0; }
719
720 $now = wfTimestampNow();
721 $won = wfInvertTimestamp( $now );
722 wfSeedRandom();
723 $rand = wfRandom();
724 $isminor = ( $isminor && $wgUser->getID() ) ? 1 : 0;
725
726 $mungedText = $text;
727 $flags = Revision::compressRevisionText( $mungedText );
728
729 $dbw =& wfGetDB( DB_MASTER );
730
731 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
732 $dbw->insert( 'text', array(
733 'old_id' => $old_id,
734 'old_text' => $mungedText,
735 'old_flags' => $flags,
736 ), $fname );
737 $revisionId = $dbw->insertId();
738
739 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
740 $dbw->insert( 'page', array(
741 'page_id' => $page_id,
742 'page_namespace' => $ns,
743 'page_title' => $ttl,
744 'page_counter' => 0,
745 'page_restrictions' => '',
746 'page_is_redirect' => $redir,
747 'page_is_new' => 1,
748 'page_random' => $rand,
749 'page_touched' => $dbw->timestamp($now),
750 'page_latest' => $revisionId,
751 ), $fname );
752 $newid = $dbw->insertId();
753
754 $dbw->insert( 'revision', array(
755 'rev_page' => $newid,
756 'rev_id' => $revisionId,
757 'rev_comment' => $summary,
758 'rev_user' => $wgUser->getID(),
759 'rev_timestamp' => $dbw->timestamp($now),
760 'rev_minor_edit' => $isminor,
761 'rev_user_text' => $wgUser->getName(),
762 'inverse_timestamp' => $won,
763 ), $fname );
764
765 $this->mTitle->resetArticleID( $newid );
766
767 Article::onArticleCreate( $this->mTitle );
768 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
769
770 if ($watchthis) {
771 if(!$this->mTitle->userIsWatching()) $this->watch();
772 } else {
773 if ( $this->mTitle->userIsWatching() ) {
774 $this->unwatch();
775 }
776 }
777
778 # The talk page isn't in the regular link tables, so we need to update manually:
779 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
780 $dbw->update( 'page',
781 array( 'page_touched' => $dbw->timestamp($now) ),
782 array( 'page_namespace' => $talkns,
783 'page_title' => $ttl ),
784 $fname );
785
786 # standard deferred updates
787 $this->editUpdates( $text, $summary, $isminor, $now );
788
789 $oldid = 0; # new article
790 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
791 }
792
793 /**
794 * Fetch and uncompress the text for a given revision.
795 * Can ask by rev_id number or timestamp (set $field)
796 */
797 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
798 $fname = 'Article::fetchRevisionText';
799 $dbw =& wfGetDB( DB_MASTER );
800 if( $revId ) {
801 $rev = $dbw->addQuotes( $revId );
802 } else {
803 $rev = 'page_latest';
804 }
805 $result = $dbw->query(
806 sprintf( "SELECT old_text, old_flags
807 FROM %s,%s,%s
808 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
809 AND %s=%s",
810 $dbw->tableName( 'page' ),
811 $dbw->tableName( 'revision' ),
812 $dbw->tableName( 'text' ),
813 IntVal( $this->mTitle->getArticleId() ),
814 $field,
815 $rev ),
816 $fname );
817 $obj = $dbw->fetchObject( $result );
818 $dbw->freeResult( $result );
819 $oldtext = Revision::getRevisionText( $obj );
820 return $oldtext;
821 }
822
823 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
824 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
825 if( is_null( $edittime ) ) {
826 $oldtext = $this->fetchRevisionText();
827 } else {
828 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
829 }
830 if ($section != '') {
831 if($section=='new') {
832 if($summary) $subject="== {$summary} ==\n\n";
833 $text=$oldtext."\n\n".$subject.$text;
834 } else {
835
836 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
837 # comments to be stripped as well)
838 $striparray=array();
839 $parser=new Parser();
840 $parser->mOutputType=OT_WIKI;
841 $oldtext=$parser->strip($oldtext, $striparray, true);
842
843 # now that we can be sure that no pseudo-sections are in the source,
844 # split it up
845 # Unfortunately we can't simply do a preg_replace because that might
846 # replace the wrong section, so we have to use the section counter instead
847 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
848 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
849 $secs[$section*2]=$text."\n\n"; // replace with edited
850
851 # section 0 is top (intro) section
852 if($section!=0) {
853
854 # headline of old section - we need to go through this section
855 # to determine if there are any subsections that now need to
856 # be erased, as the mother section has been replaced with
857 # the text of all subsections.
858 $headline=$secs[$section*2-1];
859 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
860 $hlevel=$matches[1];
861
862 # determine headline level for wikimarkup headings
863 if(strpos($hlevel,'=')!==false) {
864 $hlevel=strlen($hlevel);
865 }
866
867 $secs[$section*2-1]=''; // erase old headline
868 $count=$section+1;
869 $break=false;
870 while(!empty($secs[$count*2-1]) && !$break) {
871
872 $subheadline=$secs[$count*2-1];
873 preg_match(
874 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
875 $subhlevel=$matches[1];
876 if(strpos($subhlevel,'=')!==false) {
877 $subhlevel=strlen($subhlevel);
878 }
879 if($subhlevel > $hlevel) {
880 // erase old subsections
881 $secs[$count*2-1]='';
882 $secs[$count*2]='';
883 }
884 if($subhlevel <= $hlevel) {
885 $break=true;
886 }
887 $count++;
888
889 }
890
891 }
892 $text=join('',$secs);
893 # reinsert the stuff that we stripped out earlier
894 $text=$parser->unstrip($text,$striparray);
895 $text=$parser->unstripNoWiki($text,$striparray);
896 }
897
898 }
899 return $text;
900 }
901
902 /**
903 * Change an existing article. Puts the previous version back into the old table, updates RC
904 * and all necessary caches, mostly via the deferred update array.
905 *
906 * It is possible to call this function from a command-line script, but note that you should
907 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
908 */
909 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
910 global $wgOut, $wgUser;
911 global $wgDBtransactions, $wgMwRedir;
912 global $wgUseSquid, $wgInternalServer;
913
914 $fname = 'Article::updateArticle';
915 $good = true;
916
917 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
918 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
919 if ( $this->isRedirect( $text ) ) {
920 # Remove all content but redirect
921 # This could be done by reconstructing the redirect from a title given by
922 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
923 # wants to see
924 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
925 $redir = 1;
926 $text = $m[1] . "\n";
927 }
928 }
929 else { $redir = 0; }
930
931 $text = $this->preSaveTransform( $text );
932 $dbw =& wfGetDB( DB_MASTER );
933
934 # Update article, but only if changed.
935
936 # It's important that we either rollback or complete, otherwise an attacker could
937 # overwrite cur entries by sending precisely timed user aborts. Random bored users
938 # could conceivably have the same effect, especially if cur is locked for long periods.
939 if( $wgDBtransactions ) {
940 $dbw->query( 'BEGIN', $fname );
941 } else {
942 $userAbort = ignore_user_abort( true );
943 }
944
945 $oldtext = $this->getContent( true );
946
947 if ( 0 != strcmp( $text, $oldtext ) ) {
948 $this->mCountAdjustment = $this->isCountable( $text )
949 - $this->isCountable( $oldtext );
950 $now = wfTimestampNow();
951 $won = wfInvertTimestamp( $now );
952
953 $mungedText = $text;
954 $flags = Revision::compressRevisionText( $newtext );
955
956 $lastRevision = $dbw->selectField(
957 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
958
959 # Record the text to the text table
960 $old_id = $dbw->nextSequenceValue( 'text_old_id_val' );
961 $dbw->insert( 'text',
962 array(
963 'old_id' => $old_id,
964 'old_text' => $mungedText,
965 'old_flags' => $flags,
966 ), $fname
967 );
968 $revisionId = $dbw->insertId();
969
970 # Record the edit in revisions
971 $dbw->insert( 'revision',
972 array(
973 'rev_id' => $revisionId,
974 'rev_page' => $this->getID(),
975 'rev_comment' => $summary,
976 'rev_minor_edit' => $me2,
977 'rev_user' => $wgUser->getID(),
978 'rev_user_text' => $wgUser->getName(),
979 'rev_timestamp' => $dbw->timestamp( $now ),
980 'inverse_timestamp' => $won
981 ), $fname
982 );
983
984 # Update page
985 $dbw->update( 'page',
986 array( /* SET */
987 'page_latest' => $revisionId,
988 'page_touched' => $dbw->timestamp( $now ),
989 'page_is_new' => 0,
990 'page_is_redirect' => $redir,
991 ), array( /* WHERE */
992 'page_id' => $this->getID(),
993 'page_latest' => $lastRevision, # Paranoia
994 ), $fname
995 );
996
997 if( $dbw->affectedRows() == 0 ) {
998 /* Belated edit conflict! Run away!! */
999 $good = false;
1000 } else {
1001 # Update recentchanges and purge cache and whatnot
1002 $bot = (int)($wgUser->isBot() || $forceBot);
1003 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
1004 $lastRevision, $this->getTimestamp(), $bot );
1005 Article::onArticleEdit( $this->mTitle );
1006 }
1007 }
1008
1009 if( $wgDBtransactions ) {
1010 $dbw->query( 'COMMIT', $fname );
1011 } else {
1012 ignore_user_abort( $userAbort );
1013 }
1014
1015 if ( $good ) {
1016 if ($watchthis) {
1017 if (!$this->mTitle->userIsWatching()) $this->watch();
1018 } else {
1019 if ( $this->mTitle->userIsWatching() ) {
1020 $this->unwatch();
1021 }
1022 }
1023 # standard deferred updates
1024 $this->editUpdates( $text, $summary, $minor, $now );
1025
1026
1027 $urls = array();
1028 # Template namespace
1029 # Purge all articles linking here
1030 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1031 $titles = $this->mTitle->getLinksTo();
1032 Title::touchArray( $titles );
1033 if ( $wgUseSquid ) {
1034 foreach ( $titles as $title ) {
1035 $urls[] = $title->getInternalURL();
1036 }
1037 }
1038 }
1039
1040 # Squid updates
1041 if ( $wgUseSquid ) {
1042 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1043 $u = new SquidUpdate( $urls );
1044 $u->doUpdate();
1045 }
1046
1047 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1048 }
1049 return $good;
1050 }
1051
1052 /**
1053 * After we've either updated or inserted the article, update
1054 * the link tables and redirect to the new page.
1055 */
1056 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1057 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1058
1059 $wgLinkCache = new LinkCache();
1060 # Select for update
1061 $wgLinkCache->forUpdate( true );
1062
1063 # Get old version of link table to allow incremental link updates
1064 $wgLinkCache->preFill( $this->mTitle );
1065 $wgLinkCache->clear();
1066
1067 # Parse the text and replace links with placeholders
1068 $wgOut = new OutputPage();
1069 $wgOut->addWikiText( $text );
1070
1071 # Look up the links in the DB and add them to the link cache
1072 $wgOut->transformBuffer( RLH_FOR_UPDATE );
1073
1074 if( $this->isRedirect( $text ) )
1075 $r = 'redirect=no';
1076 else
1077 $r = '';
1078 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1079
1080 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1081 # this will be improved later (to-do)
1082
1083 include_once( "UserMailer.php" );
1084 $wgEnotif = new EmailNotification ();
1085 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle->getDBkey(), $this->mTitle->getNamespace(),$now, $summary, $me2, $oldid );
1086 }
1087
1088 /**
1089 * Validate article
1090 * @todo document this function a bit more
1091 */
1092 function validate () {
1093 global $wgOut, $wgUseValidation;
1094 if( $wgUseValidation ) {
1095 require_once ( 'SpecialValidate.php' ) ;
1096 $wgOut->setPagetitle( wfMsg( 'validate' ) . ': ' . $this->mTitle->getPrefixedText() );
1097 $wgOut->setRobotpolicy( 'noindex,follow' );
1098 if( $this->mTitle->getNamespace() != 0 ) {
1099 $wgOut->addHTML( wfMsg( 'val_validate_article_namespace_only' ) );
1100 return;
1101 }
1102 $v = new Validation;
1103 $v->validate_form( $this->mTitle->getDBkey() );
1104 } else {
1105 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
1106 }
1107 }
1108
1109 /**
1110 * Mark this particular edit as patrolled
1111 */
1112 function markpatrolled() {
1113 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1114 $wgOut->setRobotpolicy( 'noindex,follow' );
1115
1116 if ( !$wgUseRCPatrol )
1117 {
1118 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1119 return;
1120 }
1121 if ( $wgUser->getID() == 0 )
1122 {
1123 $wgOut->loginToUse();
1124 return;
1125 }
1126 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1127 {
1128 $wgOut->sysopRequired();
1129 return;
1130 }
1131 $rcid = $wgRequest->getVal( 'rcid' );
1132 if ( !is_null ( $rcid ) )
1133 {
1134 RecentChange::markPatrolled( $rcid );
1135 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1136 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1137
1138 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1139 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1140 }
1141 else
1142 {
1143 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1144 }
1145 }
1146
1147
1148 /**
1149 * Add this page to $wgUser's watchlist
1150 */
1151
1152 function watch() {
1153
1154 global $wgUser, $wgOut;
1155
1156 if ( 0 == $wgUser->getID() ) {
1157 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1158 return;
1159 }
1160 if ( wfReadOnly() ) {
1161 $wgOut->readOnlyPage();
1162 return;
1163 }
1164
1165 if (wfRunHooks('WatchArticle', $wgUser, $this)) {
1166
1167 $wgUser->addWatch( $this->mTitle );
1168 $wgUser->saveSettings();
1169
1170 wfRunHooks('WatchArticleComplete', $wgUser, $this);
1171
1172 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1173 $wgOut->setRobotpolicy( 'noindex,follow' );
1174
1175 $link = $this->mTitle->getPrefixedText();
1176 $text = wfMsg( 'addedwatchtext', $link );
1177 $wgOut->addWikiText( $text );
1178 }
1179
1180 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1181 }
1182
1183 /**
1184 * Stop watching a page
1185 */
1186
1187 function unwatch() {
1188
1189 global $wgUser, $wgOut;
1190
1191 if ( 0 == $wgUser->getID() ) {
1192 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1193 return;
1194 }
1195 if ( wfReadOnly() ) {
1196 $wgOut->readOnlyPage();
1197 return;
1198 }
1199
1200 if (wfRunHooks('UnwatchArticle', $wgUser, $this)) {
1201
1202 $wgUser->removeWatch( $this->mTitle );
1203 $wgUser->saveSettings();
1204
1205 wfRunHooks('UnwatchArticleComplete', $wgUser, $this);
1206
1207 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1208 $wgOut->setRobotpolicy( 'noindex,follow' );
1209
1210 $link = $this->mTitle->getPrefixedText();
1211 $text = wfMsg( 'removedwatchtext', $link );
1212 $wgOut->addWikiText( $text );
1213 }
1214
1215 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1216 }
1217
1218 /**
1219 * protect a page
1220 */
1221 function protect( $limit = 'sysop' ) {
1222 global $wgUser, $wgOut, $wgRequest;
1223
1224 if ( ! $wgUser->isAllowed('protect') ) {
1225 $wgOut->sysopRequired();
1226 return;
1227 }
1228 if ( wfReadOnly() ) {
1229 $wgOut->readOnlyPage();
1230 return;
1231 }
1232 $id = $this->mTitle->getArticleID();
1233 if ( 0 == $id ) {
1234 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1235 return;
1236 }
1237
1238 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1239 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1240 $reason = $wgRequest->getText( 'wpReasonProtect' );
1241
1242 if ( $confirm ) {
1243 $dbw =& wfGetDB( DB_MASTER );
1244 $dbw->update( 'page',
1245 array( /* SET */
1246 'page_touched' => $dbw->timestamp(),
1247 'page_restrictions' => (string)$limit
1248 ), array( /* WHERE */
1249 'page_id' => $id
1250 ), 'Article::protect'
1251 );
1252
1253 $restrictions = "move=" . $limit;
1254 if( !$moveonly ) {
1255 $restrictions .= ":edit=" . $limit;
1256 }
1257 if (wfRunHooks('ArticleProtect', $this, $wgUser, $limit == 'sysop', $reason, $moveonly)) {
1258
1259 $dbw =& wfGetDB( DB_MASTER );
1260 $dbw->update( 'page',
1261 array( /* SET */
1262 'page_touched' => $dbw->timestamp(),
1263 'page_restrictions' => $restrictions
1264 ), array( /* WHERE */
1265 'page_id' => $id
1266 ), 'Article::protect'
1267 );
1268
1269 wfRunHooks('ArticleProtectComplete', $this, $wgUser, $limit == 'sysop', $reason, $moveonly);
1270
1271 $log = new LogPage( 'protect' );
1272 if ( $limit === '' ) {
1273 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1274 } else {
1275 $log->addEntry( 'protect', $this->mTitle, $reason );
1276 }
1277 $wgOut->redirect( $this->mTitle->getFullURL() );
1278 }
1279 return;
1280 } else {
1281 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1282 return $this->confirmProtect( '', $reason, $limit );
1283 }
1284 }
1285
1286 /**
1287 * Output protection confirmation dialog
1288 */
1289 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1290 global $wgOut;
1291
1292 wfDebug( "Article::confirmProtect\n" );
1293
1294 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1295 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1296
1297 $check = '';
1298 $protcom = '';
1299 $moveonly = '';
1300
1301 if ( $limit === '' ) {
1302 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1303 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1304 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1305 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1306 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1307 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1308 } else {
1309 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1310 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1311 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1312 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1313 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1314 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1315 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1316 }
1317
1318 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1319
1320 $wgOut->addHTML( "
1321 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1322 <table border='0'>
1323 <tr>
1324 <td align='right'>
1325 <label for='wpReasonProtect'>{$protcom}:</label>
1326 </td>
1327 <td align='left'>
1328 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1329 </td>
1330 </tr>
1331 <tr>
1332 <td>&nbsp;</td>
1333 </tr>
1334 <tr>
1335 <td align='right'>
1336 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1337 </td>
1338 <td>
1339 <label for='wpConfirmProtect'>{$check}</label>
1340 </td>
1341 </tr> " );
1342 if($moveonly != '') {
1343 $wgOut->AddHTML( "
1344 <tr>
1345 <td align='right'>
1346 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1347 </td>
1348 <td>
1349 <label for='wpMoveOnly'>{$moveonly}</label>
1350 </td>
1351 </tr> " );
1352 }
1353 $wgOut->addHTML( "
1354 <tr>
1355 <td>&nbsp;</td>
1356 <td>
1357 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1358 </td>
1359 </tr>
1360 </table>
1361 </form>\n" );
1362
1363 $wgOut->returnToMain( false );
1364 }
1365
1366 /**
1367 * Unprotect the pages
1368 */
1369 function unprotect() {
1370 return $this->protect( '' );
1371 }
1372
1373 /*
1374 * UI entry point for page deletion
1375 */
1376 function delete() {
1377 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1378 $fname = 'Article::delete';
1379 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1380 $reason = $wgRequest->getText( 'wpReason' );
1381
1382 # This code desperately needs to be totally rewritten
1383
1384 # Check permissions
1385 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1386 $wgOut->sysopRequired();
1387 return;
1388 }
1389 if ( wfReadOnly() ) {
1390 $wgOut->readOnlyPage();
1391 return;
1392 }
1393
1394 # Better double-check that it hasn't been deleted yet!
1395 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1396 if ( ( '' == trim( $this->mTitle->getText() ) )
1397 or ( $this->mTitle->getArticleId() == 0 ) ) {
1398 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1399 return;
1400 }
1401
1402 if ( $confirm ) {
1403 $this->doDelete( $reason );
1404 return;
1405 }
1406
1407 # determine whether this page has earlier revisions
1408 # and insert a warning if it does
1409 # we select the text because it might be useful below
1410 $dbr =& $this->getDB();
1411 $ns = $this->mTitle->getNamespace();
1412 $title = $this->mTitle->getDBkey();
1413 $revisions = $dbr->select( array( 'page', 'revision' ),
1414 array( 'rev_id' ),
1415 array(
1416 'page_namespace' => $ns,
1417 'page_title' => $title,
1418 'rev_page = page_id'
1419 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'inverse_timestamp' ) )
1420 );
1421
1422 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1423 $skin=$wgUser->getSkin();
1424 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1425 $wgOut->addHTML( $skin->historyLink() .'</b>');
1426 }
1427
1428 # Fetch cur_text
1429 $s = $dbr->selectRow( array( 'page', 'text' ),
1430 array( 'old_text' ),
1431 array(
1432 'page_namespace' => $ns,
1433 'page_title' => $title,
1434 'page_latest = old_id'
1435 ), $fname, $this->getSelectOptions()
1436 );
1437
1438 if( $s !== false ) {
1439 # if this is a mini-text, we can paste part of it into the deletion reason
1440
1441 #if this is empty, an earlier revision may contain "useful" text
1442 $blanked = false;
1443 if($s->old_text != '') {
1444 $text=$s->old_text;
1445 } else {
1446 if($old) { # TODO
1447 $text = Revision::getRevisionText( $old );
1448 $blanked = true;
1449 }
1450
1451 }
1452
1453 $length=strlen($text);
1454
1455 # this should not happen, since it is not possible to store an empty, new
1456 # page. Let's insert a standard text in case it does, though
1457 if($length == 0 && $reason === '') {
1458 $reason = wfMsg('exblank');
1459 }
1460
1461 if($length < 500 && $reason === '') {
1462
1463 # comment field=255, let's grep the first 150 to have some user
1464 # space left
1465 $text=substr($text,0,150);
1466 # let's strip out newlines and HTML tags
1467 $text=preg_replace('/\"/',"'",$text);
1468 $text=preg_replace('/\</','&lt;',$text);
1469 $text=preg_replace('/\>/','&gt;',$text);
1470 $text=preg_replace("/[\n\r]/",'',$text);
1471 if(!$blanked) {
1472 $reason=wfMsg('excontent'). " '".$text;
1473 } else {
1474 $reason=wfMsg('exbeforeblank') . " '".$text;
1475 }
1476 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1477 $reason.="'";
1478 }
1479 }
1480
1481 return $this->confirmDelete( '', $reason );
1482 }
1483
1484 /**
1485 * Output deletion confirmation dialog
1486 */
1487 function confirmDelete( $par, $reason ) {
1488 global $wgOut;
1489
1490 wfDebug( "Article::confirmDelete\n" );
1491
1492 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1493 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1494 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1495 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1496
1497 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1498
1499 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1500 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1501 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1502
1503 $wgOut->addHTML( "
1504 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1505 <table border='0'>
1506 <tr>
1507 <td align='right'>
1508 <label for='wpReason'>{$delcom}:</label>
1509 </td>
1510 <td align='left'>
1511 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1512 </td>
1513 </tr>
1514 <tr>
1515 <td>&nbsp;</td>
1516 </tr>
1517 <tr>
1518 <td align='right'>
1519 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1520 </td>
1521 <td>
1522 <label for='wpConfirm'>{$check}</label>
1523 </td>
1524 </tr>
1525 <tr>
1526 <td>&nbsp;</td>
1527 <td>
1528 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1529 </td>
1530 </tr>
1531 </table>
1532 </form>\n" );
1533
1534 $wgOut->returnToMain( false );
1535 }
1536
1537
1538 /**
1539 * Perform a deletion and output success or failure messages
1540 */
1541 function doDelete( $reason ) {
1542 global $wgOut, $wgUser, $wgContLang;
1543 $fname = 'Article::doDelete';
1544 wfDebug( $fname."\n" );
1545
1546 if (wfRunHooks('ArticleDelete', $this, $wgUser, $reason)) {
1547 if ( $this->doDeleteArticle( $reason ) ) {
1548 $deleted = $this->mTitle->getPrefixedText();
1549
1550 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1551 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1552
1553 $sk = $wgUser->getSkin();
1554 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT ) .
1555 ':' . wfMsgForContent( 'dellogpage' ),
1556 wfMsg( 'deletionlog' ) );
1557
1558 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1559
1560 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1561 $wgOut->returnToMain( false );
1562 wfRunHooks('ArticleDeleteComplete', $this, $wgUser, $reason);
1563 } else {
1564 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1565 }
1566 }
1567 }
1568
1569 /**
1570 * Back-end article deletion
1571 * Deletes the article with database consistency, writes logs, purges caches
1572 * Returns success
1573 */
1574 function doDeleteArticle( $reason ) {
1575 global $wgUser;
1576 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1577
1578 $fname = 'Article::doDeleteArticle';
1579 wfDebug( $fname."\n" );
1580
1581 $dbw =& wfGetDB( DB_MASTER );
1582 $ns = $this->mTitle->getNamespace();
1583 $t = $this->mTitle->getDBkey();
1584 $id = $this->mTitle->getArticleID();
1585
1586 if ( $t == '' || $id == 0 ) {
1587 return false;
1588 }
1589
1590 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1591 array_push( $wgDeferredUpdateList, $u );
1592
1593 $linksTo = $this->mTitle->getLinksTo();
1594
1595 # Squid purging
1596 if ( $wgUseSquid ) {
1597 $urls = array(
1598 $this->mTitle->getInternalURL(),
1599 $this->mTitle->getInternalURL( 'history' )
1600 );
1601 foreach ( $linksTo as $linkTo ) {
1602 $urls[] = $linkTo->getInternalURL();
1603 }
1604
1605 $u = new SquidUpdate( $urls );
1606 array_push( $wgDeferredUpdateList, $u );
1607
1608 }
1609
1610 # Client and file cache invalidation
1611 Title::touchArray( $linksTo );
1612
1613 # Move article and history to the "archive" table
1614
1615 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1616 array(
1617 'ar_namespace' => 'page_namespace',
1618 'ar_title' => 'page_title',
1619 'ar_text' => 'old_text',
1620 'ar_comment' => 'rev_comment',
1621 'ar_user' => 'rev_user',
1622 'ar_user_text' => 'rev_user_text',
1623 'ar_timestamp' => 'rev_timestamp',
1624 'ar_minor_edit' => 'rev_minor_edit',
1625 'ar_flags' => 0,
1626 ), array(
1627 'page_namespace' => $ns,
1628 'page_title' => $t,
1629 'page_id = rev_page AND old_id = rev_id'
1630 ), $fname
1631 );
1632
1633 # Now that it's safely backed up, delete it
1634
1635 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1636 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1637 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1638
1639 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1640
1641 # Finally, clean up the link tables
1642 $t = $this->mTitle->getPrefixedDBkey();
1643
1644 Article::onArticleDelete( $this->mTitle );
1645
1646 # Insert broken links
1647 $brokenLinks = array();
1648 foreach ( $linksTo as $titleObj ) {
1649 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1650 $linkID = $titleObj->getArticleID();
1651 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1652 }
1653 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1654
1655 # Delete live links
1656 $dbw->delete( 'links', array( 'l_to' => $id ) );
1657 $dbw->delete( 'links', array( 'l_from' => $id ) );
1658 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1659 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1660 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1661
1662 # Log the deletion
1663 $log = new LogPage( 'delete' );
1664 $log->addEntry( 'delete', $this->mTitle, $reason );
1665
1666 # Clear the cached article id so the interface doesn't act like we exist
1667 $this->mTitle->resetArticleID( 0 );
1668 $this->mTitle->mArticleID = 0;
1669 return true;
1670 }
1671
1672 /**
1673 * Revert a modification
1674 */
1675 function rollback() {
1676 global $wgUser, $wgOut, $wgRequest;
1677 $fname = 'Article::rollback';
1678
1679 if ( ! $wgUser->isAllowed('rollback') ) {
1680 $wgOut->sysopRequired();
1681 return;
1682 }
1683 if ( wfReadOnly() ) {
1684 $wgOut->readOnlyPage( $this->getContent( true ) );
1685 return;
1686 }
1687 $dbw =& wfGetDB( DB_MASTER );
1688
1689 # Enhanced rollback, marks edits rc_bot=1
1690 $bot = $wgRequest->getBool( 'bot' );
1691
1692 # Replace all this user's current edits with the next one down
1693 $tt = $this->mTitle->getDBKey();
1694 $n = $this->mTitle->getNamespace();
1695
1696 # Get the last editor, lock table exclusively
1697 $s = $dbw->selectRow( array( 'page', 'revision' ),
1698 array( 'page_id','rev_user','rev_user_text','rev_comment' ),
1699 array( 'page_title' => $tt, 'page_namespace' => $n ),
1700 $fname, 'FOR UPDATE'
1701 );
1702 if( $s === false ) {
1703 # Something wrong
1704 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1705 return;
1706 }
1707 $ut = $dbw->strencode( $s->cur_user_text );
1708 $uid = $s->rev_user;
1709 $pid = $s->page_id;
1710
1711 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1712 if( $from != $s->rev_user_text ) {
1713 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1714 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1715 htmlspecialchars( $this->mTitle->getPrefixedText()),
1716 htmlspecialchars( $from ),
1717 htmlspecialchars( $s->rev_user_text ) ) );
1718 if($s->rev_comment != '') {
1719 $wgOut->addHTML(
1720 wfMsg('editcomment',
1721 htmlspecialchars( $s->rev_comment ) ) );
1722 }
1723 return;
1724 }
1725
1726 # Get the last edit not by this guy
1727 $s = $dbw->selectRow( 'old',
1728 array( 'old_text','old_user','old_user_text','old_timestamp','old_flags' ),
1729 array(
1730 'old_namespace' => $n,
1731 'old_title' => $tt,
1732 "old_user <> {$uid} OR old_user_text <> '{$ut}'"
1733 ), $fname, array( 'FOR UPDATE', 'USE INDEX' => 'name_title_timestamp' )
1734 );
1735 if( $s === false ) {
1736 # Something wrong
1737 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1738 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1739 return;
1740 }
1741
1742 if ( $bot ) {
1743 # Mark all reverted edits as bot
1744 $dbw->update( 'recentchanges',
1745 array( /* SET */
1746 'rc_bot' => 1
1747 ), array( /* WHERE */
1748 'rc_user' => $uid,
1749 "rc_timestamp > '{$s->old_timestamp}'",
1750 ), $fname
1751 );
1752 }
1753
1754 # Save it!
1755 $newcomment = wfMsg( 'revertpage', $s->old_user_text, $from );
1756 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1757 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1758 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1759 $this->updateArticle( Revision::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1760 Article::onArticleEdit( $this->mTitle );
1761 $wgOut->returnToMain( false );
1762 }
1763
1764
1765 /**
1766 * Do standard deferred updates after page view
1767 * @private
1768 */
1769 function viewUpdates() {
1770 global $wgDeferredUpdateList;
1771
1772 if ( 0 != $this->getID() ) {
1773 global $wgDisableCounters;
1774 if( !$wgDisableCounters ) {
1775 Article::incViewCount( $this->getID() );
1776 $u = new SiteStatsUpdate( 1, 0, 0 );
1777 array_push( $wgDeferredUpdateList, $u );
1778 }
1779 }
1780
1781 # Update newtalk status if user is reading their own
1782 # talk page
1783
1784 global $wgUser;
1785 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1786 $this->mTitle->getText() == $wgUser->getName()) {
1787 require_once( 'UserTalkUpdate.php' );
1788 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
1789 }
1790 }
1791
1792 /**
1793 * Do standard deferred updates after page edit.
1794 * Every 1000th edit, prune the recent changes table.
1795 * @private
1796 * @param string $text
1797 */
1798 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1799 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1800 global $wgMessageCache, $wgUser;
1801
1802 wfSeedRandom();
1803 if ( 0 == mt_rand( 0, 999 ) ) {
1804 # Periodically flush old entries from the recentchanges table.
1805 global $wgRCMaxAge;
1806 $dbw =& wfGetDB( DB_MASTER );
1807 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1808 $recentchanges = $dbw->tableName( 'recentchanges' );
1809 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1810 $dbw->query( $sql );
1811 }
1812 $id = $this->getID();
1813 $title = $this->mTitle->getPrefixedDBkey();
1814 $shortTitle = $this->mTitle->getDBkey();
1815
1816 $adj = $this->mCountAdjustment;
1817
1818 if ( 0 != $id ) {
1819 $u = new LinksUpdate( $id, $title );
1820 array_push( $wgDeferredUpdateList, $u );
1821 $u = new SiteStatsUpdate( 0, 1, $adj );
1822 array_push( $wgDeferredUpdateList, $u );
1823 $u = new SearchUpdate( $id, $title, $text );
1824 array_push( $wgDeferredUpdateList, $u );
1825
1826 # If this is another user's talk page,
1827 # create a watchlist entry for this page
1828
1829 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1830 $shortTitle != $wgUser->getName()) {
1831 require_once( 'UserTalkUpdate.php' );
1832 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1833 }
1834
1835 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1836 $wgMessageCache->replace( $shortTitle, $text );
1837 }
1838 }
1839 }
1840
1841 /**
1842 * @todo document this function
1843 * @private
1844 * @param string $oldid Revision ID of this article revision
1845 */
1846 function setOldSubtitle( $oldid=0 ) {
1847 global $wgLang, $wgOut, $wgUser;
1848
1849 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1850 $sk = $wgUser->getSkin();
1851 $lnk = $sk->makeKnownLinkObj ( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
1852 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1853 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1854 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1855 $wgOut->setSubtitle( $r );
1856 }
1857
1858 /**
1859 * This function is called right before saving the wikitext,
1860 * so we can do things like signatures and links-in-context.
1861 *
1862 * @param string $text
1863 */
1864 function preSaveTransform( $text ) {
1865 global $wgParser, $wgUser;
1866 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1867 }
1868
1869 /* Caching functions */
1870
1871 /**
1872 * checkLastModified returns true if it has taken care of all
1873 * output to the client that is necessary for this request.
1874 * (that is, it has sent a cached version of the page)
1875 */
1876 function tryFileCache() {
1877 static $called = false;
1878 if( $called ) {
1879 wfDebug( " tryFileCache() -- called twice!?\n" );
1880 return;
1881 }
1882 $called = true;
1883 if($this->isFileCacheable()) {
1884 $touched = $this->mTouched;
1885 $cache = new CacheManager( $this->mTitle );
1886 if($cache->isFileCacheGood( $touched )) {
1887 global $wgOut;
1888 wfDebug( " tryFileCache() - about to load\n" );
1889 $cache->loadFromFileCache();
1890 return true;
1891 } else {
1892 wfDebug( " tryFileCache() - starting buffer\n" );
1893 ob_start( array(&$cache, 'saveToFileCache' ) );
1894 }
1895 } else {
1896 wfDebug( " tryFileCache() - not cacheable\n" );
1897 }
1898 }
1899
1900 /**
1901 * Check if the page can be cached
1902 * @return bool
1903 */
1904 function isFileCacheable() {
1905 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1906 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1907
1908 return $wgUseFileCache
1909 and (!$wgShowIPinHeader)
1910 and ($this->getID() != 0)
1911 and ($wgUser->getId() == 0)
1912 and (!$wgUser->getNewtalk())
1913 and ($this->mTitle->getNamespace() != NS_SPECIAL )
1914 and (empty( $action ) || $action == 'view')
1915 and (!isset($oldid))
1916 and (!isset($diff))
1917 and (!isset($redirect))
1918 and (!isset($printable))
1919 and (!$this->mRedirectedFrom);
1920 }
1921
1922 /**
1923 * Loads cur_touched and returns a value indicating if it should be used
1924 *
1925 */
1926 function checkTouched() {
1927 $fname = 'Article::checkTouched';
1928 $id = $this->getID();
1929 $dbr =& $this->getDB();
1930 $s = $dbr->selectRow( 'page', array( 'page_touched', 'page_is_redirect' ),
1931 array( 'page_id' => $id ), $fname, $this->getSelectOptions() );
1932 if( $s !== false ) {
1933 $this->mTouched = wfTimestamp( TS_MW, $s->page_touched );
1934 return !$s->page_is_redirect;
1935 } else {
1936 return false;
1937 }
1938 }
1939
1940 /**
1941 * Edit an article without doing all that other stuff
1942 *
1943 * @param string $text text submitted
1944 * @param string $comment comment submitted
1945 * @param integer $minor whereas it's a minor modification
1946 */
1947 function quickEdit( $text, $comment = '', $minor = 0 ) {
1948 global $wgUser;
1949 $fname = 'Article::quickEdit';
1950
1951 #wfDebugDieBacktrace( "$fname called." );
1952
1953 wfProfileIn( $fname );
1954
1955 $dbw =& wfGetDB( DB_MASTER );
1956 $ns = $this->mTitle->getNamespace();
1957 $dbkey = $this->mTitle->getDBkey();
1958 $encDbKey = $dbw->strencode( $dbkey );
1959 $timestamp = wfTimestampNow();
1960 # insert new text
1961 $dbw->insert( 'text', array(
1962 'old_text' => $text,
1963 'old_flags' => "" ), $fname );
1964 $text_id = $dbw->insertID();
1965
1966 # update page
1967 $dbw->update( 'page', array(
1968 'page_is_new' => 0,
1969 'page_touched' => $timestamp,
1970 'page_is_redirect' => $this->isRedirect( $text ) ? 1 : 0,
1971 'page_latest' => $text_id ),
1972 array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1973 # Retrieve page ID
1974 $page_id = $dbw->selectField( 'page', 'page_id', array( 'page_namespace' => $ns, 'page_title' => $dbkey ), $fname );
1975
1976 # update revision
1977 $dbw->insert( 'revision', array(
1978 'rev_id' => $text_id,
1979 'rev_page' => $page_id,
1980 'rev_comment' => $comment,
1981 'rev_user' => $wgUser->getID(),
1982 'rev_user_text' => $wgUser->getName(),
1983 'rev_timestamp' => $timestamp,
1984 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1985 'rev_minor_edit' => intval($minor) ),
1986 $fname );
1987 wfProfileOut( $fname );
1988 }
1989
1990 /**
1991 * Used to increment the view counter
1992 *
1993 * @static
1994 * @param integer $id article id
1995 */
1996 function incViewCount( $id ) {
1997 $id = intval( $id );
1998 global $wgHitcounterUpdateFreq;
1999
2000 $dbw =& wfGetDB( DB_MASTER );
2001 $pageTable = $dbw->tableName( 'page' );
2002 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2003 $acchitsTable = $dbw->tableName( 'acchits' );
2004
2005 if( $wgHitcounterUpdateFreq <= 1 ){ //
2006 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2007 return;
2008 }
2009
2010 # Not important enough to warrant an error page in case of failure
2011 $oldignore = $dbw->ignoreErrors( true );
2012
2013 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2014
2015 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2016 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2017 # Most of the time (or on SQL errors), skip row count check
2018 $dbw->ignoreErrors( $oldignore );
2019 return;
2020 }
2021
2022 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2023 $row = $dbw->fetchObject( $res );
2024 $rown = intval( $row->n );
2025 if( $rown >= $wgHitcounterUpdateFreq ){
2026 wfProfileIn( 'Article::incViewCount-collect' );
2027 $old_user_abort = ignore_user_abort( true );
2028
2029 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2030 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2031 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2032 'GROUP BY hc_id');
2033 $dbw->query("DELETE FROM $hitcounterTable");
2034 $dbw->query('UNLOCK TABLES');
2035 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2036 'WHERE cur_id = hc_id');
2037 $dbw->query("DROP TABLE $acchitsTable");
2038
2039 ignore_user_abort( $old_user_abort );
2040 wfProfileOut( 'Article::incViewCount-collect' );
2041 }
2042 $dbw->ignoreErrors( $oldignore );
2043 }
2044
2045 /**#@+
2046 * The onArticle*() functions are supposed to be a kind of hooks
2047 * which should be called whenever any of the specified actions
2048 * are done.
2049 *
2050 * This is a good place to put code to clear caches, for instance.
2051 *
2052 * This is called on page move and undelete, as well as edit
2053 * @static
2054 * @param $title_obj a title object
2055 */
2056
2057 function onArticleCreate($title_obj) {
2058 global $wgUseSquid, $wgDeferredUpdateList;
2059
2060 $titles = $title_obj->getBrokenLinksTo();
2061
2062 # Purge squid
2063 if ( $wgUseSquid ) {
2064 $urls = $title_obj->getSquidURLs();
2065 foreach ( $titles as $linkTitle ) {
2066 $urls[] = $linkTitle->getInternalURL();
2067 }
2068 $u = new SquidUpdate( $urls );
2069 array_push( $wgDeferredUpdateList, $u );
2070 }
2071
2072 # Clear persistent link cache
2073 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2074 }
2075
2076 function onArticleDelete($title_obj) {
2077 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
2078 }
2079 function onArticleEdit($title_obj) {
2080 LinkCache::linksccClearPage( $title_obj->getArticleID() );
2081 }
2082 /**#@-*/
2083
2084 /**
2085 * Info about this page
2086 */
2087 function info() {
2088 global $wgUser, $wgTitle, $wgOut, $wgAllowPageInfo;
2089 $fname = 'Article::info';
2090
2091 wfDebugDieBacktrace( 'This function is apparently not called by any other PHP file and might be obsolete.' );
2092
2093 if ( !$wgAllowPageInfo ) {
2094 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2095 return;
2096 }
2097
2098 $dbr =& $this->getDB();
2099
2100 $basenamespace = $wgTitle->getNamespace() & (~1);
2101 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace );
2102 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace );
2103 $wl_clause = array( 'wl_title' => $wgTitle->getDBkey(), 'wl_namespace' => $basenamespace );
2104 $fullTitle = $wgTitle->makeName($basenamespace, $wgTitle->getDBKey());
2105 $wgOut->setPagetitle( $fullTitle );
2106 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2107
2108 # first, see if the page exists at all.
2109 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2110 if ($exists < 1) {
2111 $wgOut->addHTML( wfMsg('noarticletext') );
2112 } else {
2113 $numwatchers = $dbr->selectField( 'watchlist', 'COUNT(*)', $wl_clause, $fname,
2114 $this->getSelectOptions() );
2115 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $numwatchers) . '</li>' );
2116 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2117 $wgOut->addHTML( "<li>" . wfMsg('numedits', $old + 1) . '</li>');
2118
2119 # to find number of distinct authors, we need to do some
2120 # funny stuff because of the cur/old table split:
2121 # - first, find the name of the 'cur' author
2122 # - then, find the number of *other* authors in 'old'
2123
2124 # find 'cur' author
2125 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2126 $this->getSelectOptions() );
2127
2128 # find number of 'old' authors excluding 'cur' author
2129 $authors = $dbr->selectField( 'old', 'COUNT(DISTINCT old_user_text)',
2130 $old_clause + array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ), $fname,
2131 $this->getSelectOptions() ) + 1;
2132
2133 # now for the Talk page ...
2134 $cur_clause = array( 'cur_title' => $wgTitle->getDBkey(), 'cur_namespace' => $basenamespace+1 );
2135 $old_clause = array( 'old_title' => $wgTitle->getDBkey(), 'old_namespace' => $basenamespace+1 );
2136
2137 # does it exist?
2138 $exists = $dbr->selectField( 'cur', 'COUNT(*)', $cur_clause, $fname, $this->getSelectOptions() );
2139
2140 # number of edits
2141 if ($exists > 0) {
2142 $old = $dbr->selectField( 'old', 'COUNT(*)', $old_clause, $fname, $this->getSelectOptions() );
2143 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $old + 1) . '</li>');
2144 }
2145 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $authors) . '</li>' );
2146
2147 # number of authors
2148 if ($exists > 0) {
2149 $cur_author = $dbr->selectField( 'cur', 'cur_user_text', $cur_clause, $fname,
2150 $this->getSelectOptions() );
2151 $authors = $dbr->selectField( 'cur', 'COUNT(DISTINCT old_user_text)',
2152 $old_clause + array( 'old_user_text<>' . $dbr->addQuotes( $cur_author ) ),
2153 $fname, $this->getSelectOptions() );
2154
2155 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $authors) . '</li></ul>' );
2156 }
2157 }
2158 }
2159 }
2160
2161 /**
2162 * Check whether an article is a stub
2163 *
2164 * @public
2165 * @param integer $articleID ID of the article that is to be checked
2166 */
2167 function wfArticleIsStub( $articleID ) {
2168 global $wgUser;
2169 $fname = 'wfArticleIsStub';
2170
2171 wfDebugDieBacktrace( 'This function seems to be unused. Pending removal.' );
2172
2173 $threshold = $wgUser->getOption('stubthreshold') ;
2174 if ( $threshold > 0 ) {
2175 $dbr =& wfGetDB( DB_SLAVE );
2176 $s = $dbr->selectRow( array('page', 'text'),
2177 array( 'LENGTH(old_text) AS len', 'page_namespace', 'page_is_redirect' ),
2178 array( 'page_id' => $articleID, "page.page_latest=text.old_id" ),
2179 $fname ) ;
2180 if ( $s == false OR $s->page_is_redirect OR $s->page_namespace != NS_MAIN ) {
2181 return false;
2182 }
2183 $size = $s->len;
2184 return ( $size < $threshold );
2185 }
2186 return false;
2187 }
2188
2189 ?>