/** * @since 2.1 * * @param Title $title * * @return text */ public function getContentAsText(Title $title) { $this->page = new \WikiPage($title); if (method_exists($this->page, 'getContent')) { $content = $this->page->getContent(); if ($content instanceof TextContent) { return $content->getNativeData(); } else { return ''; } } return $this->page->getText(); }
/** * @return bool */ public function doWork() { global $wgUseFileCache; // @todo several of the methods called on $this->page are not declared in Page, but present // in WikiPage and delegated by Article. $isCurrent = $this->revid === $this->page->getLatest(); if ($this->content !== null) { $content = $this->content; } elseif ($isCurrent) { // XXX: why use RAW audience here, and PUBLIC (default) below? $content = $this->page->getContent(Revision::RAW); } else { $rev = Revision::newFromTitle($this->page->getTitle(), $this->revid); if ($rev === null) { $content = null; } else { // XXX: why use PUBLIC audience here (default), and RAW above? $content = $rev->getContent(); } } if ($content === null) { return false; } // Reduce effects of race conditions for slow parses (bug 46014) $cacheTime = wfTimestampNow(); $time = -microtime(true); $this->parserOutput = $content->getParserOutput($this->page->getTitle(), $this->revid, $this->parserOptions); $time += microtime(true); // Timing hack if ($time > 3) { // TODO: Use Parser's logger (once it has one) $logger = MediaWiki\Logger\LoggerFactory::getInstance('slow-parse'); $logger->info('{time} {title}', ['time' => number_format($time, 2), 'title' => $this->page->getTitle()->getPrefixedDBkey(), 'trigger' => 'view']); } if ($this->cacheable && $this->parserOutput->isCacheable() && $isCurrent) { ParserCache::singleton()->save($this->parserOutput, $this->page, $this->parserOptions, $cacheTime, $this->revid); } // Make sure file cache is not used on uncacheable content. // Output that has magic words in it can still use the parser cache // (if enabled), though it will generally expire sooner. if (!$this->parserOutput->isCacheable()) { $wgUseFileCache = false; } if ($isCurrent) { $this->page->triggerOpportunisticLinksUpdate($this->parserOutput); } return true; }
/** * Gets the text contents of a page with the passed-in Title object. */ public static function getPageText($title) { if (method_exists('WikiPage', 'getContent')) { // MW 1.21+ $wikiPage = new WikiPage($title); $content = $wikiPage->getContent(); if ($content !== null) { return $content->getNativeData(); } else { return null; } } else { // MW <= 1.20 $article = new Article($title); return $article->getContent(); } }
static function newFromTitle($title) { // see if we already have this as our main instance... if (self::$instance && self::$instance->mTitle == $title) { return self::$instance; } $wikiPage = new WikiPage($title); if (!$wikiPage) { return null; } $whow = new WikihowArticleEditor(); $whow->mTitleObj = $wikiPage->getTitle(); $whow->mWikiPage = $wikiPage; $whow->mTitle = $wikiPage->getTitle()->getText(); $text = ContentHandler::getContentText($wikiPage->getContent(Revision::RAW)); $whow->loadFromText($text); return $whow; }
function savePage(WikiPage $p) { $db = new DatabaseConnection(); // Read values $ns = $p->getNs(); $uri = $p->getUri(); $title = $p->getTitle(); $content = $p->getContent(); $author = User::getActiveUserId(); // Update try { // pull the latest revision of the page $rs = $db->getSingleRow('SELECT MAX(revision) AS latest FROM wiki WHERE ns=\'%s\' AND uri=\'%s\'', $ns, $uri); $currev = $rs ? $rs['latest'] : 0; // set to 0 if no record returned // bump revision (if no record, 0 becomes 1) $currev++; // and insert the new data $db->updateRow("INSERT INTO wiki SET content='%s',revision='%d',title='%s',ns='%s',uri='%s',lastedit=NOW(),author='%d'", $content, $currev, $title, $ns, $uri, $author); } catch (DBXException $e) { throw $e; } }
function deleteUnneededTaskBoxTemplates() { $results = self::getQueryResults("[[Category:Page with Task]]", array('title'), true); if ($results->getCount() === 0) { return FALSE; } while ($row = $results->getNext()) { $pageTitle = $row[0]->getNextObject(); $targetTitle = Title::newFromText($pageTitle->getLongWikiText()); if (!$targetTitle instanceof Title) { throw new MWException(wfMessage('tm-error-title')); } $page = new WikiPage($targetTitle); $content = $page->getContent(); if (strpos($content->getNativeData(), '{{TaskBox}}') !== false) { $resultsTasks = self::getQueryResults("[[Category:Task(s)]] [[Entity::" . $pageTitle->getLongWikiText() . "]]", array('title'), true); if ($resultsTasks->getCount() === 0) { $newContent = new WikitextContent(str_replace('{{TaskBox}}', '', $content->getNativeData())); $page->doEditContent($newContent, wfMessage('tm-tasbox-removed'), EDIT_MINOR); } } } return TRUE; }
} $wikiList = $searchResult; } else { $message = $langWikiSearchMissingKeywords; $style = 'caution'; $action = 'rqSearch'; } break; // show differences // show differences case 'diff': include 'modules/wiki/lib/lib.diff.php'; if ($wikiStore->pageExists($wikiId, $wiki_title)) { // older version $wikiPage->loadPageVersion($old); $old = $wikiPage->getContent(); $oldTime = $wikiPage->getCurrentVersionMtime(); $oldEditor = $wikiPage->getEditorId(); // newer version $wikiPage->loadPageVersion($new); $new = $wikiPage->getContent(); $newTime = $wikiPage->getCurrentVersionMtime(); $newEditor = $wikiPage->getEditorId(); // get differences $diff = '<table style="border: 0;">' . diff($old, $new, true, 'format_table_line') . '</table>'; } break; // page history //case 'history': // recent changes // page history
/** * @dataProvider provideEditAppend */ public function testEditAppend($text, $op, $append, $expected) { static $count = 0; $count++; // assume NS_HELP defaults to wikitext $name = "Help:ApiEditPageTest_testEditAppend_{$count}"; // -- create page (or not) ----------------------------------------- if ($text !== null) { list($re) = $this->doApiRequestWithToken(array('action' => 'edit', 'title' => $name, 'text' => $text)); $this->assertEquals('Success', $re['edit']['result']); // sanity } // -- try append/prepend -------------------------------------------- list($re) = $this->doApiRequestWithToken(array('action' => 'edit', 'title' => $name, $op . 'text' => $append)); $this->assertEquals('Success', $re['edit']['result']); // -- validate ----------------------------------------------------- $page = new WikiPage(Title::newFromText($name)); $content = $page->getContent(); $this->assertNotNull($content, 'Page should have been created'); $text = $content->getNativeData(); $this->assertEquals($expected, $text); }
static function getPageRawTextFromPage($pageTitle) { global $wgParser, $wgMemc, $wgUser; $wgParserOptions = new ParserOptions($wgUser); if ($pageTitle->isExternal()) { $content = $wgParser->interwikiTransclude($pageTitle, 'raw'); $output = $wgParser->preprocess($content, $pageTitle, $wgParserOptions); $key = wfForeignMemcKey('huiji', '', 'page', 'getPageRaw', 'shared', $pageTitle->getFullText()); $wgMemc->set($key, $output); } else { if (!$pageTitle->isKnown()) { return 'Create the page [[' . $pageTitle->getFullText() . ']]'; } else { $key = wfMemcKey('page', 'getPageRaw', 'all', $pageTitle->getFullText()); $page = new WikiPage($pageTitle); // get the text as static wiki text, but with already expanded templates, // which also e.g. to use {{#dpl}} (DPL third party extension) for dynamic menus. $output = $wgParser->preprocess($page->getContent()->getNativeData(), $pageTitle, $wgParserOptions); $wgMemc->set($key, $output); } } return $output; }
/** * @covers WikiPage::doRollback */ public function testDoRollbackFailureSameContent() { $admin = new User(); $admin->setName("Admin"); $admin->addGroup("sysop"); #XXX: make the test user a sysop... $text = "one"; $page = $this->newPage("WikiPageTest_testDoRollback"); $page->doEditContent(ContentHandler::makeContent($text, $page->getTitle(), CONTENT_MODEL_WIKITEXT), "section one", EDIT_NEW, false, $admin); $rev1 = $page->getRevision(); $user1 = new User(); $user1->setName("127.0.1.11"); $user1->addGroup("sysop"); #XXX: make the test user a sysop... $text .= "\n\ntwo"; $page = new WikiPage($page->getTitle()); $page->doEditContent(ContentHandler::makeContent($text, $page->getTitle(), CONTENT_MODEL_WIKITEXT), "adding section two", 0, false, $user1); # now, do a the rollback from the same user was doing the edit before $resultDetails = array(); $token = $user1->getEditToken(array($page->getTitle()->getPrefixedText(), $user1->getName()), null); $errors = $page->doRollback($user1->getName(), "testing revert same user", $token, false, $resultDetails, $admin); $this->assertEquals(array(), $errors, "Rollback failed same user"); # now, try the rollback $resultDetails = array(); $token = $admin->getEditToken(array($page->getTitle()->getPrefixedText(), $user1->getName()), null); $errors = $page->doRollback($user1->getName(), "testing revert", $token, false, $resultDetails, $admin); $this->assertEquals(array(array('alreadyrolled', 'WikiPageTest testDoRollback', '127.0.1.11', 'Admin')), $errors, "Rollback not failed"); $page = new WikiPage($page->getTitle()); $this->assertEquals($rev1->getSha1(), $page->getRevision()->getSha1(), "rollback did not revert to the correct revision"); $this->assertEquals("one", $page->getContent()->getNativeData()); }
} $wikiList = $searchResult; } else { $message = get_lang("Missing search keywords"); $dialogBox->error($message); $action = 'rqSearch'; } break; // show differences // show differences case 'diff': require_once 'lib/lib.diff.php'; if ($wikiStore->pageExists($wikiId, $title)) { // older version $wikiPage->loadPageVersion($old); $old = $wikiPage->getContent(); $oldTime = $wikiPage->getCurrentVersionMtime(); $oldEditor = $wikiPage->getEditorId(); // newer version $wikiPage->loadPageVersion($new); $new = $wikiPage->getContent(); $newTime = $wikiPage->getCurrentVersionMtime(); $newEditor = $wikiPage->getEditorId(); // protect against dangerous html $old = claro_htmlspecialchars($old); $new = claro_htmlspecialchars($new); // get differences $diff = '<table style="border: 0;">' . diff($new, $old, true, 'format_table_line') . '</table>'; } break; // page history
/** * @param Content|null $def_content The default value to return * * @return Content|null Content on success, $def_content for invalid sections * * @since 1.21 */ protected function getContentObject($def_content = null) { global $wgOut, $wgRequest, $wgUser, $wgContLang; $content = false; // For message page not locally set, use the i18n message. // For other non-existent articles, use preload text if any. if (!$this->mTitle->exists() || $this->section == 'new') { if ($this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new') { # If this is a system message, get the default text. $msg = $this->mTitle->getDefaultMessageText(); $content = $this->toEditContent($msg); } if ($content === false) { # If requested, preload some text. $preload = $wgRequest->getVal('preload', $this->section === 'new' ? 'MediaWiki:addsection-preload' : ''); $params = $wgRequest->getArray('preloadparams', array()); $content = $this->getPreloadedContent($preload, $params); } // For existing pages, get text based on "undo" or section parameters. } else { if ($this->section != '') { // Get section edit text (returns $def_text for invalid sections) $orig = $this->getOriginalContent($wgUser); $content = $orig ? $orig->getSection($this->section) : null; if (!$content) { $content = $def_content; } } else { $undoafter = $wgRequest->getInt('undoafter'); $undo = $wgRequest->getInt('undo'); if ($undo > 0 && $undoafter > 0) { $undorev = Revision::newFromId($undo); $oldrev = Revision::newFromId($undoafter); # Sanity check, make sure it's the right page, # the revisions exist and they were not deleted. # Otherwise, $content will be left as-is. if (!is_null($undorev) && !is_null($oldrev) && !$undorev->isDeleted(Revision::DELETED_TEXT) && !$oldrev->isDeleted(Revision::DELETED_TEXT)) { $content = $this->page->getUndoContent($undorev, $oldrev); if ($content === false) { # Warn the user that something went wrong $undoMsg = 'failure'; } else { $oldContent = $this->page->getContent(Revision::RAW); $popts = ParserOptions::newFromUserAndLang($wgUser, $wgContLang); $newContent = $content->preSaveTransform($this->mTitle, $wgUser, $popts); if ($newContent->equals($oldContent)) { # Tell the user that the undo results in no change, # i.e. the revisions were already undone. $undoMsg = 'nochange'; $content = false; } else { # Inform the user of our success and set an automatic edit summary $undoMsg = 'success'; # If we just undid one rev, use an autosummary $firstrev = $oldrev->getNext(); if ($firstrev && $firstrev->getId() == $undo) { $userText = $undorev->getUserText(); if ($userText === '') { $undoSummary = wfMessage('undo-summary-username-hidden', $undo)->inContentLanguage()->text(); } else { $undoSummary = wfMessage('undo-summary', $undo, $userText)->inContentLanguage()->text(); } if ($this->summary === '') { $this->summary = $undoSummary; } else { $this->summary = $undoSummary . wfMessage('colon-separator')->inContentLanguage()->text() . $this->summary; } $this->undidRev = $undo; } $this->formtype = 'diff'; } } } else { // Failed basic sanity checks. // Older revisions may have been removed since the link // was created, or we may simply have got bogus input. $undoMsg = 'norev'; } // Messages: undo-success, undo-failure, undo-norev, undo-nochange $class = ($undoMsg == 'success' ? '' : 'error ') . "mw-undo-{$undoMsg}"; $this->editFormPageTop .= $wgOut->parse("<div class=\"{$class}\">" . wfMessage('undo-' . $undoMsg)->plain() . '</div>', true, true); } if ($content === false) { $content = $this->getOriginalContent($wgUser); } } } return $content; }
function view($u = null) { global $wgOut, $wgTitle, $wgUser, $wgRequest; $diff = $wgRequest->getVal('diff'); $rcid = $wgRequest->getVal('rcid'); $this->user = $u ? $u : User::newFromName($wgTitle->getDBKey()); if (!$u && $this->mTitle->getNamespace() != NS_USER || !$this->user || isset($diff) || isset($rcid)) { return Article::view(); } if ($this->user->getID() == 0) { header('HTTP/1.1 404 Not Found'); $wgOut->setRobotpolicy('noindex,nofollow'); $wgOut->showErrorPage('nosuchuser', 'Noarticletext_user'); return; } $this->isPageOwner = $wgUser->getID() == $this->user->getID(); if ($this->user->isBlocked() && $this->isPageOwner) { $wgOut->blockedPage(); return; } $wgOut->setRobotpolicy('index,follow'); $skin = $this->getContext()->getSkin(); //user settings $checkStats = $this->user->getOption('profilebox_stats') == 1; $checkStartedEdited = $this->user->getOption('profilebox_startedEdited') == 1; $profileStats = new ProfileStats($this->user); $badgeData = $profileStats->getBadges(); $wgOut->addHTML(ProfileBox::getDisplayBadge($badgeData)); if (!$u) { $skin->addWidget($this->getRCUserWidget()); } if ($checkStats || $checkStartedEdited) { $createdData = $profileStats->getArticlesCreated(0); } //stats if ($checkStats) { $stats = ProfileBox::fetchStats("User:"******"<div class='clearall'></div>"); } }
/** * Return fields to be indexed by search engine * as representation of this document. * Overriding class should call parent function or take care of calling * the SearchDataForIndex hook. * @param WikiPage $page Page to index * @param ParserOutput $output * @param SearchEngine $engine Search engine for which we are indexing * @return array Map of name=>value for fields * @since 1.28 */ public function getDataForSearchIndex(WikiPage $page, ParserOutput $output, SearchEngine $engine) { $fieldData = []; $content = $page->getContent(); if ($content) { $searchDataExtractor = new ParserOutputSearchDataExtractor(); $fieldData['category'] = $searchDataExtractor->getCategories($output); $fieldData['external_link'] = $searchDataExtractor->getExternalLinks($output); $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks($output); $fieldData['template'] = $searchDataExtractor->getTemplates($output); $text = $content->getTextForSearchIndex(); $fieldData['text'] = $text; $fieldData['source_text'] = $text; $fieldData['text_bytes'] = $content->getSize(); } Hooks::run('SearchDataForIndex', [&$fieldData, $this, $page, $output, $engine]); return $fieldData; }
/** * Get the content for the given page and the requested section. * * @param WikiPage $page * @param int $pageId * @return Content */ private function getContent(WikiPage $page, $pageId = null) { $content = $page->getContent(Revision::RAW); // XXX: really raw? if ($this->section !== false && $content !== null) { $content = $this->getSectionContent($content, !is_null($pageId) ? 'page id ' . $pageId : $page->getTitle()->getPrefixedText()); } return $content; }
/** * @covers ContentHandler::getDataForSearchIndex */ public function testDataIndexFields() { $mockEngine = $this->getMock('SearchEngine'); $title = Title::newFromText('Not_Main_Page', NS_MAIN); $page = new WikiPage($title); $this->setTemporaryHook('SearchDataForIndex', function (&$fields, ContentHandler $handler, WikiPage $page, ParserOutput $output, SearchEngine $engine) { $fields['testDataField'] = 'test content'; }); $output = $page->getContent()->getParserOutput($title); $data = $page->getContentHandler()->getDataForSearchIndex($page, $output, $mockEngine); $this->assertArrayHasKey('text', $data); $this->assertArrayHasKey('text_bytes', $data); $this->assertArrayHasKey('language', $data); $this->assertArrayHasKey('testDataField', $data); $this->assertEquals('test content', $data['testDataField']); }
/** * @param WikiPage $page * @return bool * @throws MWException */ private function doRestorePage(WikiPage $page) { $oldContent = $page->getContent(); if ($oldContent === null || !$this->isArchivedPage($page)) { return false; } $text = $oldContent->getNativeData(); $text = str_replace($this->archiveMarker, '', $text); $page->doEditContent(new WikitextContent($text), 'restored by ContentStaging'); return true; }
/** * @todo FIXME: the above rollback test is better, but it keeps failing in jenkins for some reason. */ public function testDoRollback() { $admin = new User(); $admin->setName("Admin"); $text = "one"; $page = $this->newPage("WikiPageTest_testDoRollback"); $page->doEditContent(ContentHandler::makeContent($text, $page->getTitle(), CONTENT_MODEL_WIKITEXT), "section one", EDIT_NEW, false, $admin); $rev1 = $page->getRevision(); $user1 = new User(); $user1->setName("127.0.1.11"); $text .= "\n\ntwo"; $page = new WikiPage($page->getTitle()); $page->doEditContent(ContentHandler::makeContent($text, $page->getTitle(), CONTENT_MODEL_WIKITEXT), "adding section two", 0, false, $user1); # now, try the rollback $admin->addGroup("sysop"); #XXX: make the test user a sysop... $token = $admin->getEditToken(array($page->getTitle()->getPrefixedText(), $user1->getName()), null); $errors = $page->doRollback($user1->getName(), "testing revert", $token, false, $details, $admin); if ($errors) { $this->fail("Rollback failed:\n" . print_r($errors, true) . ";\n" . print_r($details, true)); } $page = new WikiPage($page->getTitle()); $this->assertEquals($rev1->getSha1(), $page->getRevision()->getSha1(), "rollback did not revert to the correct revision"); $this->assertEquals("one", $page->getContent()->getNativeData()); }
/** * Run a dtImport job * @return boolean success */ function run() { wfProfileIn(__METHOD__); if (is_null($this->title)) { $this->error = "dtImport: Invalid title"; wfProfileOut(__METHOD__); return false; } if (method_exists('WikiPage', 'getContent')) { $wikiPage = new WikiPage($this->title); if (!$wikiPage) { $this->error = 'dtImport: Wiki page not found "' . $this->title->getPrefixedDBkey() . '"'; wfProfileOut(__METHOD__); return false; } } else { $article = new Article($this->title); if (!$article) { $this->error = 'dtImport: Article not found "' . $this->title->getPrefixedDBkey() . '"'; wfProfileOut(__METHOD__); return false; } } $for_pages_that_exist = $this->params['for_pages_that_exist']; if ($for_pages_that_exist == 'skip' && $this->title->exists()) { return true; } // Change global $wgUser variable to the one specified by // the job only for the extent of this import. global $wgUser; $actual_user = $wgUser; $wgUser = User::newFromId($this->params['user_id']); $text = $this->params['text']; if ($this->title->exists()) { if ($for_pages_that_exist == 'append') { if (method_exists('WikiPage', 'getContent')) { // MW >= 1.21 $existingText = $wikiPage->getContent()->getNativeData(); } else { $existingText = $article->getContent(); } $text = $existingText . "\n" . $text; } elseif ($for_pages_that_exist == 'merge') { $existingPageStructure = DTPageStructure::newFromTitle($this->title); $newPageStructure = new DTPageStructure(); $newPageStructure->parsePageContents($text); $existingPageStructure->mergeInPageStructure($newPageStructure); $text = $existingPageStructure->toWikitext(); } // otherwise, $for_pages_that_exist == 'overwrite' } $edit_summary = $this->params['edit_summary']; if (method_exists('WikiPage', 'getContent')) { $new_content = new WikitextContent($text); $wikiPage->doEditContent($new_content, $edit_summary); } else { $article->doEdit($text, $edit_summary); } $wgUser = $actual_user; wfProfileOut(__METHOD__); return true; }
private function updateContent(Docman_Item $item, array &$update_data) { $item_factory = Docman_ItemFactory::instance($item->getGroupId()); $item_type = $item_factory->getItemTypeForItem($item); switch ($item_type) { case PLUGIN_DOCMAN_ITEM_TYPE_EMPTY: break; case PLUGIN_DOCMAN_ITEM_TYPE_WIKI: $wiki_page = new WikiPage($item->getGroupId(), $item->getPagename()); $this->request_data_factory->updateContent($update_data, $wiki_page->getContent()); break; case PLUGIN_DOCMAN_ITEM_TYPE_LINK: $this->request_data_factory->updateContent($update_data, $item->getUrl()); break; case PLUGIN_DOCMAN_ITEM_TYPE_EMBEDDEDFILE: case PLUGIN_DOCMAN_ITEM_TYPE_FILE: $this->request_data_factory->updateFile($update_data, $item->getCurrentVersion()->getPath()); break; default: $this->logger->debug("unrecognized item type, can't update content"); break; } }
public static function newFromTitle($pageTitle) { $pageStructure = new DTPageStructure(); $pageStructure->mPageTitle = $pageTitle; if (method_exists('WikiPage', 'getContent')) { $wiki_page = new WikiPage($pageTitle); $page_contents = $wiki_page->getContent()->getNativeData(); } else { $article = new Article($pageTitle); $page_contents = $article->getContent(); } $pageStructure->parsePageContents($page_contents); // Now, go through the field values and see if any of them // hold template calls - if any of them do, parse the value // as if it's the full contents of a page, and add the // resulting "components" to that field. foreach ($pageStructure->mComponents as $pageComponent) { if ($pageComponent->mIsTemplate) { foreach ($pageComponent->mFields as $fieldName => $fieldValue) { if (strpos($fieldValue, '{{') !== false) { $dummyPageStructure = new DTPageStructure(); $dummyPageStructure->parsePageContents($fieldValue); $pageComponent->mFields[$fieldName] = $dummyPageStructure->mComponents; } } } } return $pageStructure; }
/** * @param $page WikiPage * @param $popts ParserOptions * @param $pageId Int * @param $getWikitext Bool * @return ParserOutput */ private function getParsedContent(WikiPage $page, $popts, $pageId = null, $getWikitext = false) { $this->content = $page->getContent(Revision::RAW); //XXX: really raw? if ($this->section !== false && $this->content !== null) { $this->content = $this->getSectionContent($this->content, !is_null($pageId) ? 'page id ' . $pageId : $page->getTitle()->getText()); // Not cached (save or load) return $this->content->getParserOutput($page->getTitle(), null, $popts); } else { // Try the parser cache first // getParserOutput will save to Parser cache if able $pout = $page->getParserOutput($popts); if (!$pout) { $this->dieUsage("There is no revision ID {$page->getLatest()}", 'missingrev'); } if ($getWikitext) { $this->content = $page->getContent(Revision::RAW); } return $pout; } }
/** * Run a replaceText job * @return boolean success */ function run() { wfProfileIn(__METHOD__); if (is_null($this->title)) { $this->error = "replaceText: Invalid title"; wfProfileOut(__METHOD__); return false; } if (array_key_exists('move_page', $this->params)) { global $wgUser; $actual_user = $wgUser; $wgUser = User::newFromId($this->params['user_id']); $cur_page_name = $this->title->getText(); if ($this->params['use_regex']) { $new_page_name = preg_replace("/" . $this->params['target_str'] . "/U", $this->params['replacement_str'], $cur_page_name); } else { $new_page_name = str_replace($this->params['target_str'], $this->params['replacement_str'], $cur_page_name); } $new_title = Title::newFromText($new_page_name, $this->title->getNamespace()); $reason = $this->params['edit_summary']; $create_redirect = $this->params['create_redirect']; $this->title->moveTo($new_title, true, $reason, $create_redirect); if ($this->params['watch_page']) { if (class_exists('WatchAction')) { // Class was added in MW 1.19 WatchAction::doWatch($new_title, $wgUser); } else { Action::factory('watch', new WikiPage($new_title))->execute(); } } $wgUser = $actual_user; } else { // WikiPage::getContent() replaced // Article::fetchContent() starting in MW 1.21. if (method_exists('WikiPage', 'getContent')) { if ($this->title->getContentModel() !== CONTENT_MODEL_WIKITEXT) { $this->error = 'replaceText: Wiki page "' . $this->title->getPrefixedDBkey() . '" does not hold regular wikitext.'; wfProfileOut(__METHOD__); return false; } $wikiPage = new WikiPage($this->title); // Is this check necessary? if (!$wikiPage) { $this->error = 'replaceText: Wiki page not found for "' . $this->title->getPrefixedDBkey() . '."'; wfProfileOut(__METHOD__); return false; } $article_text = $wikiPage->getContent()->getNativeData(); } else { $article = new Article($this->title, 0); if (!$article) { $this->error = 'replaceText: Article not found for "' . $this->title->getPrefixedDBkey() . '"'; wfProfileOut(__METHOD__); return false; } $article_text = $article->fetchContent(); } wfProfileIn(__METHOD__ . '-replace'); $target_str = $this->params['target_str']; $replacement_str = $this->params['replacement_str']; // @todo FIXME eh? $num_matches; if ($this->params['use_regex']) { $new_text = preg_replace('/' . $target_str . '/U', $replacement_str, $article_text, -1, $num_matches); } else { $new_text = str_replace($target_str, $replacement_str, $article_text, $num_matches); } // If there's at least one replacement, modify the page, // using the passed-in edit summary. if ($num_matches > 0) { // Change global $wgUser variable to the one // specified by the job only for the extent of // this replacement. global $wgUser; $actual_user = $wgUser; $wgUser = User::newFromId($this->params['user_id']); $edit_summary = $this->params['edit_summary']; $flags = EDIT_MINOR; if ($wgUser->isAllowed('bot')) { $flags |= EDIT_FORCE_BOT; } if (method_exists('WikiPage', 'getContent')) { $new_content = new WikitextContent($new_text); $wikiPage->doEditContent($new_content, $edit_summary, $flags); } else { $article->doEdit($new_text, $edit_summary, $flags); } $wgUser = $actual_user; } wfProfileOut(__METHOD__ . '-replace'); } wfProfileOut(__METHOD__); return true; }