public function testMessage()
 {
     $user = new MockSuperUser();
     $user->setId(123);
     $title = Title::newFromText('MediaWiki:translated/fi');
     $page = WikiPage::factory($title);
     $content = ContentHandler::makeContent('pupuliini', $title);
     $status = $page->doEditContent($content, __METHOD__, 0, false, $user);
     $value = $status->getValue();
     $rev = $value['revision'];
     $revision = $rev->getId();
     $group = MessageGroups::getGroup('test-group');
     $collection = $group->initCollection('fi');
     $collection->loadTranslations();
     /** @var TMessage $translated */
     $translated = $collection['translated'];
     $this->assertInstanceof('TMessage', $translated);
     $this->assertEquals('translated', $translated->key());
     $this->assertEquals('bunny', $translated->definition());
     $this->assertEquals('pupuliini', $translated->translation());
     $this->assertEquals('SuperUser', $translated->getProperty('last-translator-text'));
     $this->assertEquals(123, $translated->getProperty('last-translator-id'));
     $this->assertEquals('translated', $translated->getProperty('status'), 'message status is translated');
     $this->assertEquals($revision, $translated->getProperty('revision'));
     /** @var TMessage $untranslated */
     $untranslated = $collection['untranslated'];
     $this->assertInstanceof('TMessage', $untranslated);
     $this->assertEquals(null, $untranslated->translation(), 'no translation is null');
     $this->assertEquals(false, $untranslated->getProperty('last-translator-text'));
     $this->assertEquals(false, $untranslated->getProperty('last-translator-id'));
     $this->assertEquals('untranslated', $untranslated->getProperty('status'), 'message status is untranslated');
     $this->assertEquals(false, $untranslated->getProperty('revision'));
 }
 function run()
 {
     // Initialization
     $title = $this->title;
     list(, $code) = TranslateUtils::figureMessage($title->getPrefixedText());
     // Return the actual translation page...
     $page = TranslatablePage::isTranslationPage($title);
     if (!$page) {
         var_dump($this->params);
         var_dump($title);
         throw new MWException("Oops, this should not happen!");
     }
     $group = $page->getMessageGroup();
     $collection = $group->initCollection($code);
     $text = $page->getParse()->getTranslationPageText($collection);
     // Other stuff
     $user = $this->getUser();
     $summary = $this->getSummary();
     $flags = $this->getFlags();
     $page = WikiPage::factory($title);
     // @todo FuzzyBot hack
     PageTranslationHooks::$allowTargetEdit = true;
     $content = ContentHandler::makeContent($text, $page->getTitle());
     $page->doEditContent($content, $summary, $flags, false, $user);
     PageTranslationHooks::$allowTargetEdit = false;
     return true;
 }
 public function execute()
 {
     global $wgUser;
     $username = $this->getOption('username', false);
     if ($username === false) {
         $user = User::newSystemUser('ScriptImporter', ['steal' => true]);
     } else {
         $user = User::newFromName($username);
     }
     $wgUser = $user;
     $baseUrl = $this->getArg(1);
     $pageList = $this->fetchScriptList();
     $this->output('Importing ' . count($pageList) . " pages\n");
     foreach ($pageList as $page) {
         $title = Title::makeTitleSafe(NS_MEDIAWIKI, $page);
         if (!$title) {
             $this->error("{$page} is an invalid title; it will not be imported\n");
             continue;
         }
         $this->output("Importing {$page}\n");
         $url = wfAppendQuery($baseUrl, ['action' => 'raw', 'title' => "MediaWiki:{$page}"]);
         $text = Http::get($url, [], __METHOD__);
         $wikiPage = WikiPage::factory($title);
         $content = ContentHandler::makeContent($text, $wikiPage->getTitle());
         $wikiPage->doEditContent($content, "Importing from {$url}", 0, false, $user);
     }
 }
 public function getDefinitions()
 {
     $groups = MessageGroups::getAllGroups();
     $keys = array();
     /**
      * @var $g MessageGroup
      */
     foreach ($groups as $g) {
         $states = $g->getMessageGroupStates()->getStates();
         foreach (array_keys($states) as $state) {
             $keys["Translate-workflow-state-{$state}"] = $state;
         }
     }
     $defs = TranslateUtils::getContents(array_keys($keys), $this->getNamespace());
     foreach ($keys as $key => $state) {
         if (!isset($defs[$key])) {
             // @todo Use jobqueue
             $title = Title::makeTitleSafe($this->getNamespace(), $key);
             $page = new WikiPage($title);
             $content = ContentHandler::makeContent($state, $title);
             $page->doEditContent($content, wfMessage('translate-workflow-autocreated-summary', $state)->inContentLanguage()->text(), 0, false, FuzzyBot::getUser());
         } else {
             // Use the wiki translation as definition if available.
             // getContents returns array( content, last author )
             list($content, ) = $defs[$key];
             $keys[$key] = $content;
         }
     }
     return $keys;
 }
 public function testParsing()
 {
     $title = Title::newFromText('MediaWiki:Ugakey/nl');
     $page = WikiPage::factory($title);
     $content = ContentHandler::makeContent('$1 van $2', $title);
     $status = $page->doEditContent($content, __METHOD__);
     $value = $status->getValue();
     /**
      * @var Revision $rev
      */
     $rev = $value['revision'];
     $revision = $rev->getId();
     $dbw = wfGetDB(DB_MASTER);
     $conds = array('rt_page' => $title->getArticleID(), 'rt_type' => RevTag::getType('fuzzy'), 'rt_revision' => $revision);
     $index = array_keys($conds);
     $dbw->replace('revtag', array($index), $conds, __METHOD__);
     $handle = new MessageHandle($title);
     $this->assertTrue($handle->isValid(), 'Message is known');
     $this->assertTrue($handle->isFuzzy(), 'Message is fuzzy after database fuzzying');
     // Update the translation without the fuzzy string
     $content = ContentHandler::makeContent('$1 van $2', $title);
     $page->doEditContent($content, __METHOD__);
     $this->assertFalse($handle->isFuzzy(), 'Message is unfuzzy after edit');
     $content = ContentHandler::makeContent('!!FUZZY!!$1 van $2', $title);
     $page->doEditContent($content, __METHOD__);
     $this->assertTrue($handle->isFuzzy(), 'Message is fuzzy after manual fuzzying');
     // Update the translation without the fuzzy string
     $content = ContentHandler::makeContent('$1 van $2', $title);
     $page->doEditContent($content, __METHOD__);
     $this->assertFalse($handle->isFuzzy(), 'Message is unfuzzy after edit');
 }
 /**
  * Updates $title with the provided $text
  * @param Title title
  * @param string $text
  */
 public static function updatePage($title, $text)
 {
     $user = new User();
     $page = WikiPage::factory($title);
     $content = ContentHandler::makeContent($text, $page->getTitle());
     $page->doEditContent($content, "summary", 0, false, $user);
 }
 /**
  * @param string $text new page text
  *
  * @return int|null
  */
 private function editPageText($text)
 {
     $page = WikiPage::factory($this->title);
     $editResult = $page->doEditContent(ContentHandler::makeContent($text, $this->title), __METHOD__);
     /** @var Revision $revision */
     $revision = $editResult->value['revision'];
     $this->runJobs();
     return $revision->getId();
 }
 private function doPatrolledPageEdit(User $user, LinkTarget $target, $content, $summary, User $patrollingUser)
 {
     $title = Title::newFromLinkTarget($target);
     $page = WikiPage::factory($title);
     $status = $page->doEditContent(ContentHandler::makeContent($content, $title), $summary, 0, false, $user);
     /** @var Revision $rev */
     $rev = $status->value['revision'];
     $rc = $rev->getRecentChange();
     $rc->doMarkPatrolled($patrollingUser, false, []);
 }
 /**
  * Add or update message contents
  */
 function update($translation, $user)
 {
     $savePage = function ($title, $text) {
         $wikiPage = new WikiPage($title);
         $content = ContentHandler::makeContent($text, $title);
         $result = $wikiPage->doEditContent($content, '/* PR admin */', EDIT_FORCE_BOT);
         return $wikiPage;
     };
     $savePage($this->getTitle(), $translation);
 }
 /**
  *Test bug 25702
  *Prefixes of API search requests are not handled with case sensitivity and may result
  *in wrong search results
  */
 public function testPrefixNormalizationSearchBug()
 {
     $title = Title::newFromText('Category:Template:xyz');
     $page = WikiPage::factory($title);
     $page->doEditContent(ContentHandler::makeContent('Some text', $page->getTitle()), 'inserting content');
     $result = $this->doApiRequest(['action' => 'query', 'list' => 'allpages', 'apnamespace' => NS_CATEGORY, 'apprefix' => 'Template:x']);
     $this->assertArrayHasKey('query', $result[0]);
     $this->assertArrayHasKey('allpages', $result[0]['query']);
     $this->assertNotEquals(0, count($result[0]['query']['allpages']), 'allpages list does not contain page Category:Template:xyz');
 }
 /**
  * @return int[] Revision ids
  */
 protected function doEdits()
 {
     $title = $this->getTitle();
     $page = WikiPage::factory($title);
     $strings = array("it is a kitten", "two kittens", "three kittens", "four kittens");
     $revisions = array();
     foreach ($strings as $string) {
         $content = ContentHandler::makeContent($string, $title);
         $page->doEditContent($content, 'edit page');
         $revisions[] = $page->getLatest();
     }
     return $revisions;
 }
Example #12
0
	public function execute() {
		global $wgUser, $wgTitle;

		$userName = $this->getOption( 'user', 'Maintenance script' );
		$summary = $this->getOption( 'summary', '' );
		$minor = $this->hasOption( 'minor' );
		$bot = $this->hasOption( 'bot' );
		$autoSummary = $this->hasOption( 'autosummary' );
		$noRC = $this->hasOption( 'no-rc' );

		$wgUser = User::newFromName( $userName );
		$context = RequestContext::getMain();
		$context->setUser( $wgUser );
		if ( !$wgUser ) {
			$this->error( "Invalid username", true );
		}
		if ( $wgUser->isAnon() ) {
			$wgUser->addToDatabase();
		}

		$wgTitle = Title::newFromText( $this->getArg() );
		if ( !$wgTitle ) {
			$this->error( "Invalid title", true );
		}
		$context->setTitle( $wgTitle );

		$page = WikiPage::factory( $wgTitle );

		# Read the text
		$text = $this->getStdin( Maintenance::STDIN_ALL );
		$content = ContentHandler::makeContent( $text, $wgTitle );

		# Do the edit
		$this->output( "Saving... " );
		$status = $page->doEditContent( $content, $summary,
			( $minor ? EDIT_MINOR : 0 ) |
			( $bot ? EDIT_FORCE_BOT : 0 ) |
			( $autoSummary ? EDIT_AUTOSUMMARY : 0 ) |
			( $noRC ? EDIT_SUPPRESS_RC : 0 ) );
		if ( $status->isOK() ) {
			$this->output( "done\n" );
			$exit = 0;
		} else {
			$this->output( "failed\n" );
			$exit = 1;
		}
		if ( !$status->isGood() ) {
			$this->output( $status->getWikiText() . "\n" );
		}
		exit( $exit );
	}
Example #13
0
 /**
  * Helper function for addDBData -- adds a simple page to the database
  *
  * @param string $title Title of page to be created
  * @param string $lang Language and content of the created page
  * @param string|null $content Content of the created page, or null for a generic string
  */
 protected function makePage($title, $lang, $content = null)
 {
     global $wgContLang;
     if ($content === null) {
         $content = $lang;
     }
     if ($lang !== $wgContLang->getCode()) {
         $title = "{$title}/{$lang}";
     }
     $title = Title::newFromText($title, NS_MEDIAWIKI);
     $wikiPage = new WikiPage($title);
     $contentHandler = ContentHandler::makeContent($content, $title);
     $wikiPage->doEditContent($contentHandler, "{$lang} translation test case");
 }
 /**
  * Adds a revision to a page, while returning the resuting revision's id
  *
  * @param $page WikiPage: page to add the revision to
  * @param $text string: revisions text
  * @param $text string: revisions summare
  *
  * @throws MWExcepion
  */
 protected function addRevision(Page $page, $text, $summary)
 {
     $status = $page->doEditContent(ContentHandler::makeContent($text, $page->getTitle()), $summary);
     if ($status->isGood()) {
         $value = $status->getValue();
         $revision = $value['revision'];
         $revision_id = $revision->getId();
         $text_id = $revision->getTextId();
         if ($revision_id > 0 && $text_id > 0) {
             return array($revision_id, $text_id);
         }
     }
     throw new MWException("Could not determine revision id (" . $status->getWikiText() . ")");
 }
Example #15
0
 /**
  * Adds a revision to a page, while returning the resuting revision's id
  *
  * @param Page $page Page to add the revision to
  * @param string $text Revisions text
  * @param string $summary Revisions summary
  * @param string $model The model ID (defaults to wikitext)
  *
  * @throws MWException
  * @return array
  */
 protected function addRevision(Page $page, $text, $summary, $model = CONTENT_MODEL_WIKITEXT)
 {
     $status = $page->doEditContent(ContentHandler::makeContent($text, $page->getTitle(), $model), $summary);
     if ($status->isGood()) {
         $value = $status->getValue();
         $revision = $value['revision'];
         $revision_id = $revision->getId();
         $text_id = $revision->getTextId();
         if ($revision_id > 0 && $text_id > 0) {
             return [$revision_id, $text_id];
         }
     }
     throw new MWException("Could not determine revision id (" . $status->getWikiText(false, false, 'en') . ")");
 }
Example #16
0
 public function execute()
 {
     global $wgUser;
     $userName = $this->getOption('user', false);
     $summary = $this->getOption('summary', '');
     $minor = $this->hasOption('minor');
     $bot = $this->hasOption('bot');
     $autoSummary = $this->hasOption('autosummary');
     $noRC = $this->hasOption('no-rc');
     if ($userName === false) {
         $wgUser = User::newSystemUser('Maintenance script', array('steal' => true));
     } else {
         $wgUser = User::newFromName($userName);
     }
     if (!$wgUser) {
         $this->error("Invalid username", true);
     }
     if ($wgUser->isAnon()) {
         $wgUser->addToDatabase();
     }
     $title = Title::newFromText($this->getArg());
     if (!$title) {
         $this->error("Invalid title", true);
     }
     if ($this->hasOption('nocreate') && !$title->exists()) {
         $this->error("Page does not exist", true);
     } elseif ($this->hasOption('createonly') && $title->exists()) {
         $this->error("Page already exists", true);
     }
     $page = WikiPage::factory($title);
     # Read the text
     $text = $this->getStdin(Maintenance::STDIN_ALL);
     $content = ContentHandler::makeContent($text, $title);
     # Do the edit
     $this->output("Saving... ");
     $status = $page->doEditContent($content, $summary, ($minor ? EDIT_MINOR : 0) | ($bot ? EDIT_FORCE_BOT : 0) | ($autoSummary ? EDIT_AUTOSUMMARY : 0) | ($noRC ? EDIT_SUPPRESS_RC : 0));
     if ($status->isOK()) {
         $this->output("done\n");
         $exit = 0;
     } else {
         $this->output("failed\n");
         $exit = 1;
     }
     if (!$status->isGood()) {
         $this->output($status->getWikiText() . "\n");
     }
     exit($exit);
 }
 public function execute()
 {
     $out = $this->mSpecial->getOutput();
     $dbr = wfGetDB(DB_SLAVE);
     $row = $dbr->selectRow('moderation', array('mod_namespace AS namespace', 'mod_title AS title', 'mod_text AS text'), array('mod_id' => $this->id), __METHOD__);
     if (!$row) {
         throw new ModerationError('moderation-edit-not-found');
     }
     $title = Title::makeTitle($row->namespace, $row->title);
     $popts = $out->parserOptions();
     $popts->setEditSection(false);
     $content = ContentHandler::makeContent($row->text, null, $title->getContentModel());
     $pout = $content->getParserOutput($title, 0, $popts, true);
     $out->setPageTitle(wfMessage('moderation-preview-title', $title->getPrefixedText()));
     $out->addParserOutput($pout);
 }
Example #18
0
 /**
  * @param Page $page
  * @param ParserOptions $parserOptions ParserOptions to use for the parse
  * @param int $revid ID of the revision being parsed.
  * @param bool $useParserCache Whether to use the parser cache.
  *   operation.
  * @param Content|string $content Content to parse or null to load it; may
  *   also be given as a wikitext string, for BC.
  */
 public function __construct(Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $content = null)
 {
     if (is_string($content)) {
         // BC: old style call
         $modelId = $page->getRevision()->getContentModel();
         $format = $page->getRevision()->getContentFormat();
         $content = ContentHandler::makeContent($content, $page->getTitle(), $modelId, $format);
     }
     $this->page = $page;
     $this->revid = $revid;
     $this->cacheable = $useParserCache;
     $this->parserOptions = $parserOptions;
     $this->content = $content;
     $this->cacheKey = ParserCache::singleton()->getKey($page, $parserOptions);
     parent::__construct('ArticleView', $this->cacheKey . ':revid:' . $revid);
 }
 /**
  * @group medium
  */
 public function testContentComesWithContentModelAndFormat()
 {
     $pageName = 'Help:' . __METHOD__;
     $title = Title::newFromText($pageName);
     $page = WikiPage::factory($title);
     $page->doEditContent(ContentHandler::makeContent('Some text', $page->getTitle()), 'inserting content');
     $apiResult = $this->doApiRequest(['action' => 'query', 'prop' => 'revisions', 'titles' => $pageName, 'rvprop' => 'content']);
     $this->assertArrayHasKey('query', $apiResult[0]);
     $this->assertArrayHasKey('pages', $apiResult[0]['query']);
     foreach ($apiResult[0]['query']['pages'] as $page) {
         $this->assertArrayHasKey('revisions', $page);
         foreach ($page['revisions'] as $revision) {
             $this->assertArrayHasKey('contentformat', $revision, 'contentformat should be included when asking content so client knows how to interpret it');
             $this->assertArrayHasKey('contentmodel', $revision, 'contentmodel should be included when asking content so client knows how to interpret it');
         }
     }
 }
 public function testTranslationPageRestrictions()
 {
     $superUser = new MockSuperUser();
     $title = Title::newFromText('Translatable page');
     $page = WikiPage::factory($title);
     $content = ContentHandler::makeContent('<translate>Hello</translate>', $title);
     $status = $page->doEditContent($content, 'New page', 0, false, $superUser);
     $revision = $status->value['revision']->getId();
     $translatablePage = TranslatablePage::newFromRevision($title, $revision);
     $translatablePage->addMarkedTag($revision);
     MessageGroups::singleton()->recache();
     $translationPage = Title::newFromText('Translatable page/fi');
     TranslateRenderJob::newJob($translationPage)->run();
     $this->assertTrue($translationPage->userCan('read', $superUser), 'Users can read existing translation pages');
     $this->assertFalse($translationPage->userCan('edit', $superUser), 'Users can not edit existing translation pages');
     $translationPage = Title::newFromText('Translatable page/ab');
     $this->assertTrue($translationPage->userCan('read', $superUser), 'Users can read non-existing translation pages');
     $this->assertFalse($translationPage->userCan('edit', $superUser), 'Users can not edit non-existing translation pages');
 }
 public function testPreventCategorization()
 {
     $user = new MockSuperUser();
     $title = Title::makeTitle(NS_MEDIAWIKI, 'ugakey1/fi');
     $wikipage = WikiPage::factory($title);
     $content = ContentHandler::makeContent('[[Category:Shouldnotbe]]', $title);
     $wikipage->doEditContent($content, __METHOD__, 0, false, $user);
     $this->assertEquals(array(), $title->getParentCategories(), 'translation of known message');
     $title = Title::makeTitle(NS_MEDIAWIKI, 'ugakey2/qqq');
     $wikipage = WikiPage::factory($title);
     $content = ContentHandler::makeContent('[[Category:Shouldbe]]', $title);
     $wikipage->doEditContent($content, __METHOD__, 0, false, $user);
     $this->assertEquals(array('Category:Shouldbe' => 'MediaWiki:ugakey2/qqq'), $title->getParentCategories(), 'message docs');
     $title = Title::makeTitle(NS_MEDIAWIKI, 'ugakey3/no');
     $wikipage = WikiPage::factory($title);
     $content = ContentHandler::makeContent('[[Category:Shouldbealso]]', $title);
     $wikipage->doEditContent($content, __METHOD__, 0, false, $user);
     $this->assertEquals(array(), $title->getParentCategories(), 'unknown message');
 }
 /**
 	@brief Intercept image uploads and queue them for moderation.
 */
 public static function onUploadVerifyFile($upload, $mime, &$status)
 {
     global $wgRequest, $wgUser, $wgOut;
     if (ModerationCanSkip::canSkip($wgUser)) {
         return;
     }
     $result = $upload->validateName();
     if ($result !== true) {
         $status = array($upload->getVerificationErrorCode($result['status']));
         return;
     }
     $special = new ModerationSpecialUpload($wgRequest);
     $special->publicLoadRequest();
     $title = $upload->getTitle();
     $model = $title->getContentModel();
     try {
         $file = $upload->stashFile($wgUser);
     } catch (MWException $e) {
         $status = array("api-error-stashfailed");
         return;
     }
     $key = $file->getFileKey();
     $pageText = '';
     if (!$special->mForReUpload) {
         $pageText = $special->getInitialPageText($special->mComment, $special->mLicense, $special->mCopyrightStatus, $special->mCopyrightSource);
     }
     $content = ContentHandler::makeContent($pageText, null, $model);
     /* Step 1. Create a page in File namespace (it will be queued for moderation) */
     $page = new WikiPage($title);
     $status = $page->doEditContent($content, $special->mComment, 0, $title->getLatestRevID(), $wgUser);
     $wgOut->redirect('');
     # Disable redirection after doEditContent()
     /*
     	Step 2. Populate mod_stash_key field in newly inserted row
     	of the moderation table (to indicate that this is an upload,
     	not just editing the text on image page)
     */
     $dbw = wfGetDB(DB_MASTER);
     $dbw->update('moderation', array('mod_stash_key' => $key), array('mod_id' => ModerationEditHooks::$LastInsertId), __METHOD__);
     $status = array("moderation-image-queued");
 }
Example #23
0
 public function execute()
 {
     $user = User::newFromName($this->getOption('user'));
     if (!$user->getId()) {
         $this->error("No such user exists.", 1);
     }
     $count = $this->getOption('count');
     $namespace = (int) $this->getOption('namespace', 0);
     for ($i = 0; $i < $count; ++$i) {
         $title = Title::makeTitleSafe($namespace, "Page " . wfRandomString(2));
         $page = WikiPage::factory($title);
         $content = ContentHandler::makeContent(wfRandomString(), $title);
         $summary = "Change " . wfRandomString(6);
         $page->doEditContent($content, $summary, 0, false, $user);
         $this->output("Edited {$title}\n");
         if ($i && $i % $this->mBatchSize == 0) {
             wfWaitForSlaves();
         }
     }
     $this->output("Done\n");
 }
 /**
  * @dataProvider provider_backlinks
  */
 public function testRefreshLinks($ns, $dbKey, $pages)
 {
     $title = Title::makeTitle($ns, $dbKey);
     foreach ($pages as $page) {
         list($bns, $bdbkey) = $page;
         $bpage = WikiPage::factory(Title::makeTitle($bns, $bdbkey));
         $content = ContentHandler::makeContent("[[{$title->getPrefixedText()}]]", $bpage->getTitle());
         $bpage->doEditContent($content, "test");
     }
     $title->getBacklinkCache()->clear();
     $this->assertEquals(20, $title->getBacklinkCache()->getNumLinks('pagelinks'), 'Correct number of backlinks');
     $job = new RefreshLinksJob($title, array('recursive' => true, 'table' => 'pagelinks') + Job::newRootJobParams("refreshlinks:pagelinks:{$title->getPrefixedText()}"));
     $extraParams = $job->getRootJobParams();
     $jobs = BacklinkJobUtils::partitionBacklinkJob($job, 9, 1, array('params' => $extraParams));
     $this->assertEquals(10, count($jobs), 'Correct number of sub-jobs');
     $this->assertEquals($pages[0], current($jobs[0]->params['pages']), 'First job is leaf job with proper title');
     $this->assertEquals($pages[8], current($jobs[8]->params['pages']), 'Last leaf job is leaf job with proper title');
     $this->assertEquals(true, isset($jobs[9]->params['recursive']), 'Last job is recursive sub-job');
     $this->assertEquals(true, $jobs[9]->params['recursive'], 'Last job is recursive sub-job');
     $this->assertEquals(true, is_array($jobs[9]->params['range']), 'Last job is recursive sub-job');
     $this->assertEquals($title->getPrefixedText(), $jobs[0]->getTitle()->getPrefixedText(), 'Base job title retainend in leaf job');
     $this->assertEquals($title->getPrefixedText(), $jobs[9]->getTitle()->getPrefixedText(), 'Base job title retainend recursive sub-job');
     $this->assertEquals($extraParams['rootJobSignature'], $jobs[0]->params['rootJobSignature'], 'Leaf job has root params');
     $this->assertEquals($extraParams['rootJobSignature'], $jobs[9]->params['rootJobSignature'], 'Recursive sub-job has root params');
     $jobs2 = BacklinkJobUtils::partitionBacklinkJob($jobs[9], 9, 1, array('params' => $extraParams));
     $this->assertEquals(10, count($jobs2), 'Correct number of sub-jobs');
     $this->assertEquals($pages[9], current($jobs2[0]->params['pages']), 'First job is leaf job with proper title');
     $this->assertEquals($pages[17], current($jobs2[8]->params['pages']), 'Last leaf job is leaf job with proper title');
     $this->assertEquals(true, isset($jobs2[9]->params['recursive']), 'Last job is recursive sub-job');
     $this->assertEquals(true, $jobs2[9]->params['recursive'], 'Last job is recursive sub-job');
     $this->assertEquals(true, is_array($jobs2[9]->params['range']), 'Last job is recursive sub-job');
     $this->assertEquals($extraParams['rootJobSignature'], $jobs2[0]->params['rootJobSignature'], 'Leaf job has root params');
     $this->assertEquals($extraParams['rootJobSignature'], $jobs2[9]->params['rootJobSignature'], 'Recursive sub-job has root params');
     $jobs3 = BacklinkJobUtils::partitionBacklinkJob($jobs2[9], 9, 1, array('params' => $extraParams));
     $this->assertEquals(2, count($jobs3), 'Correct number of sub-jobs');
     $this->assertEquals($pages[18], current($jobs3[0]->params['pages']), 'First job is leaf job with proper title');
     $this->assertEquals($extraParams['rootJobSignature'], $jobs3[0]->params['rootJobSignature'], 'Leaf job has root params');
     $this->assertEquals($pages[19], current($jobs3[1]->params['pages']), 'Last job is leaf job with proper title');
     $this->assertEquals($extraParams['rootJobSignature'], $jobs3[1]->params['rootJobSignature'], 'Last leaf job has root params');
 }
 function run()
 {
     global $wgTranslateDocumentationLanguageCode;
     $title = $this->title;
     $params = $this->params;
     $user = FuzzyBot::getUser();
     $flags = EDIT_DEFER_UPDATES | EDIT_FORCE_BOT;
     $wikiPage = WikiPage::factory($title);
     $summary = wfMessage('translate-manage-import-summary')->inContentLanguage()->plain();
     $content = ContentHandler::makeContent($params['content'], $title);
     $wikiPage->doEditContent($content, $summary, $flags, false, $user);
     // NOTE: message documentation is excluded from fuzzying!
     if ($params['fuzzy']) {
         $handle = new MessageHandle($title);
         $key = $handle->getKey();
         $languages = TranslateUtils::getLanguageNames('en');
         unset($languages[$wgTranslateDocumentationLanguageCode]);
         $languages = array_keys($languages);
         $dbw = wfGetDB(DB_MASTER);
         $fields = array('page_id', 'page_latest');
         $conds = array('page_namespace' => $title->getNamespace());
         $pages = array();
         foreach ($languages as $code) {
             $otherTitle = Title::makeTitleSafe($title->getNamespace(), "{$key}/{$code}");
             $pages[$otherTitle->getDBKey()] = true;
         }
         unset($pages[$title->getDBKey()]);
         if (count($pages) === 0) {
             return true;
         }
         $conds['page_title'] = array_keys($pages);
         $res = $dbw->select('page', $fields, $conds, __METHOD__);
         $inserts = array();
         foreach ($res as $row) {
             $inserts[] = array('rt_type' => RevTag::getType('fuzzy'), 'rt_page' => $row->page_id, 'rt_revision' => $row->page_latest);
         }
         $dbw->replace('revtag', array(array('rt_type', 'rt_page', 'rt_revision')), $inserts, __METHOD__);
     }
     return true;
 }
 /**
  * @dataProvider dataGetSecondaryDataUpdates
  * @group Database
  */
 public function testGetSecondaryDataUpdates($title, $model, $text, $expectedStuff)
 {
     $title = Title::newFromText($title);
     $title->resetArticleID(2342);
     //dummy id. fine as long as we don't try to execute the updates!
     $content = ContentHandler::makeContent($text, $title, $model);
     $updates = $content->getSecondaryDataUpdates($title);
     // make updates accessible by class name
     foreach ($updates as $update) {
         $class = get_class($update);
         $updates[$class] = $update;
     }
     foreach ($expectedStuff as $class => $fieldValues) {
         $this->assertArrayHasKey($class, $updates, "missing an update of type {$class}");
         $update = $updates[$class];
         foreach ($fieldValues as $field => $value) {
             $v = $update->{$field};
             #if the field doesn't exist, just crash and burn
             $this->assertEquals($value, $v, "unexpected value for field {$field} in instance of {$class}");
         }
     }
 }
Example #27
0
 /**
  * Hook function for APIEditBeforeSave.
  * This allows blacklist matches to be reported directly in the result structure
  * of the API call.
  *
  * @param $editPage EditPage
  * @param $text string
  * @param $resultArr array
  * @return bool
  */
 static function filterAPIEditBeforeSave($editPage, $text, &$resultArr)
 {
     $title = $editPage->mArticle->getTitle();
     // get the links from the not-yet-saved page content.
     $content = ContentHandler::makeContent($text, $editPage->getTitle(), $editPage->contentModel, $editPage->contentFormat);
     $editInfo = $editPage->mArticle->prepareContentForEdit($content, null, null, $editPage->contentFormat);
     $pout = $editInfo->output;
     $links = array_keys($pout->getExternalLinks());
     // HACK: treat the edit summary as a link
     $summary = $editPage->summary;
     if ($summary !== '') {
         $links[] = $summary;
     }
     $spamObj = BaseBlacklist::getInstance('spam');
     $matches = $spamObj->filter($links, $title);
     if ($matches !== false) {
         $resultArr['spamblacklist'] = implode('|', $matches);
     }
     // mark the title, so filterMergedContent can skip it.
     $title->spamBlackListFiltered = true;
     // return convention for hooks is the inverse of $wgFilterCallback
     return $matches === false;
 }
 /**
  * @dataProvider dataGetSecondaryDataUpdates
  * @group Database
  * @covers WikitextContent::getSecondaryDataUpdates
  */
 public function testGetSecondaryDataUpdates($title, $model, $text, $expectedStuff)
 {
     $ns = $this->getDefaultWikitextNS();
     $title = Title::newFromText($title, $ns);
     $content = ContentHandler::makeContent($text, $title, $model);
     $page = WikiPage::factory($title);
     $page->doEditContent($content, '');
     $updates = $content->getSecondaryDataUpdates($title);
     // make updates accessible by class name
     foreach ($updates as $update) {
         $class = get_class($update);
         $updates[$class] = $update;
     }
     foreach ($expectedStuff as $class => $fieldValues) {
         $this->assertArrayHasKey($class, $updates, "missing an update of type {$class}");
         $update = $updates[$class];
         foreach ($fieldValues as $field => $value) {
             $v = $update->{$field};
             # if the field doesn't exist, just crash and burn
             $this->assertEquals($value, $v, "unexpected value for field {$field} in instance of {$class}");
         }
     }
     $page->doDeleteArticle('');
 }
 public function testgetReviewBlockers()
 {
     $superUser1 = new MockSuperUser();
     $superUser1->setId(1);
     $superUser2 = new MockSuperUser();
     $superUser2->setId(2);
     $plainUser = User::newFromName('PlainUser');
     $title = Title::makeTitle(NS_MEDIAWIKI, 'Ugakey1/fi');
     $content = ContentHandler::makeContent('trans1', $title);
     WikiPage::factory($title)->doEditContent($content, __METHOD__, 0, false, $superUser1);
     $title = Title::makeTitle(NS_MEDIAWIKI, 'Ugakey2/fi');
     $content = ContentHandler::makeContent('!!FUZZY!!trans2', $title);
     WikiPage::factory($title)->doEditContent($content, __METHOD__, 0, false, $superUser2);
     $title = Title::makeTitle(NS_MEDIAWIKI, 'Ugakey3/fi');
     $content = ContentHandler::makeContent('unknown message', $title);
     WikiPage::factory($title)->doEditContent($content, __METHOD__, 0, false, $superUser1);
     $testcases = array(array('permissiondenied', $plainUser, 'Ugakey1/fi', 'Unpriviledged user is not allowed to change state'), array('owntranslation', $superUser1, 'Ugakey1/fi', 'Cannot approve own translation'), array('fuzzymessage', $superUser1, 'Ugakey2/fi', 'Cannot approve fuzzy translation'), array('unknownmessage', $superUser1, 'Ugakey3/fi', 'Cannot approve unknown translation'), array('', $superUser2, 'Ugakey1/fi', 'Can approve non-fuzzy known non-own translation'));
     foreach ($testcases as $case) {
         list($expected, $user, $page, $comment) = $case;
         $revision = Revision::newFromTitle(Title::makeTitle(NS_MEDIAWIKI, $page));
         $ok = ApiTranslationReview::getReviewBlockers($user, $revision);
         $this->assertEquals($expected, $ok, $comment);
     }
 }
Example #30
0
 public function execute()
 {
     // The data is hot but user-dependent, like page views, so we set vary cookies
     $this->getMain()->setCacheMode('anon-public-user-private');
     // Get parameters
     $params = $this->extractRequestParams();
     $text = $params['text'];
     $title = $params['title'];
     $page = $params['page'];
     $pageid = $params['pageid'];
     $oldid = $params['oldid'];
     $model = $params['contentmodel'];
     $format = $params['contentformat'];
     if (!is_null($page) && (!is_null($text) || $title != 'API')) {
         $this->dieUsage('The page parameter cannot be used together with the text and title parameters', 'params');
     }
     $prop = array_flip($params['prop']);
     if (isset($params['section'])) {
         $this->section = $params['section'];
     } else {
         $this->section = false;
     }
     // The parser needs $wgTitle to be set, apparently the
     // $title parameter in Parser::parse isn't enough *sigh*
     // TODO: Does this still need $wgTitle?
     global $wgParser, $wgTitle;
     // Currently unnecessary, code to act as a safeguard against any change in current behaviour of uselang breaks
     $oldLang = null;
     if (isset($params['uselang']) && $params['uselang'] != $this->getContext()->getLanguage()->getCode()) {
         $oldLang = $this->getContext()->getLanguage();
         // Backup language
         $this->getContext()->setLanguage(Language::factory($params['uselang']));
     }
     $redirValues = null;
     // Return result
     $result = $this->getResult();
     if (!is_null($oldid) || !is_null($pageid) || !is_null($page)) {
         if (!is_null($oldid)) {
             // Don't use the parser cache
             $rev = Revision::newFromID($oldid);
             if (!$rev) {
                 $this->dieUsage("There is no revision ID {$oldid}", 'missingrev');
             }
             if (!$rev->userCan(Revision::DELETED_TEXT, $this->getUser())) {
                 $this->dieUsage("You don't have permission to view deleted revisions", 'permissiondenied');
             }
             $titleObj = $rev->getTitle();
             $wgTitle = $titleObj;
             $pageObj = WikiPage::factory($titleObj);
             $popts = $pageObj->makeParserOptions($this->getContext());
             $popts->enableLimitReport(!$params['disablepp']);
             // If for some reason the "oldid" is actually the current revision, it may be cached
             if ($rev->isCurrent()) {
                 // May get from/save to parser cache
                 $p_result = $this->getParsedContent($pageObj, $popts, $pageid, isset($prop['wikitext']));
             } else {
                 // This is an old revision, so get the text differently
                 $this->content = $rev->getContent(Revision::FOR_THIS_USER, $this->getUser());
                 if ($this->section !== false) {
                     $this->content = $this->getSectionContent($this->content, 'r' . $rev->getId());
                 }
                 // Should we save old revision parses to the parser cache?
                 $p_result = $this->content->getParserOutput($titleObj, $rev->getId(), $popts);
             }
         } else {
             // Not $oldid, but $pageid or $page
             if ($params['redirects']) {
                 $reqParams = array('action' => 'query', 'redirects' => '');
                 if (!is_null($pageid)) {
                     $reqParams['pageids'] = $pageid;
                 } else {
                     // $page
                     $reqParams['titles'] = $page;
                 }
                 $req = new FauxRequest($reqParams);
                 $main = new ApiMain($req);
                 $main->execute();
                 $data = $main->getResultData();
                 $redirValues = isset($data['query']['redirects']) ? $data['query']['redirects'] : array();
                 $to = $page;
                 foreach ((array) $redirValues as $r) {
                     $to = $r['to'];
                 }
                 $pageParams = array('title' => $to);
             } elseif (!is_null($pageid)) {
                 $pageParams = array('pageid' => $pageid);
             } else {
                 // $page
                 $pageParams = array('title' => $page);
             }
             $pageObj = $this->getTitleOrPageId($pageParams, 'fromdb');
             $titleObj = $pageObj->getTitle();
             if (!$titleObj || !$titleObj->exists()) {
                 $this->dieUsage("The page you specified doesn't exist", 'missingtitle');
             }
             $wgTitle = $titleObj;
             if (isset($prop['revid'])) {
                 $oldid = $pageObj->getLatest();
             }
             $popts = $pageObj->makeParserOptions($this->getContext());
             $popts->enableLimitReport(!$params['disablepp']);
             // Potentially cached
             $p_result = $this->getParsedContent($pageObj, $popts, $pageid, isset($prop['wikitext']));
         }
     } else {
         // Not $oldid, $pageid, $page. Hence based on $text
         $titleObj = Title::newFromText($title);
         if (!$titleObj) {
             $this->dieUsageMsg(array('invalidtitle', $title));
         }
         if (!$titleObj->canExist()) {
             $this->dieUsage("Namespace doesn't allow actual pages", 'pagecannotexist');
         }
         $wgTitle = $titleObj;
         $pageObj = WikiPage::factory($titleObj);
         $popts = $pageObj->makeParserOptions($this->getContext());
         $popts->enableLimitReport(!$params['disablepp']);
         if (is_null($text)) {
             $this->dieUsage('The text parameter should be passed with the title parameter. Should you be using the "page" parameter instead?', 'params');
         }
         try {
             $this->content = ContentHandler::makeContent($text, $titleObj, $model, $format);
         } catch (MWContentSerializationException $ex) {
             $this->dieUsage($ex->getMessage(), 'parseerror');
         }
         if ($this->section !== false) {
             $this->content = $this->getSectionContent($this->content, $titleObj->getText());
         }
         if ($params['pst'] || $params['onlypst']) {
             $this->pstContent = $this->content->preSaveTransform($titleObj, $this->getUser(), $popts);
         }
         if ($params['onlypst']) {
             // Build a result and bail out
             $result_array = array();
             $result_array['text'] = array();
             $result->setContent($result_array['text'], $this->pstContent->serialize($format));
             if (isset($prop['wikitext'])) {
                 $result_array['wikitext'] = array();
                 $result->setContent($result_array['wikitext'], $this->content->serialize($format));
             }
             $result->addValue(null, $this->getModuleName(), $result_array);
             return;
         }
         // Not cached (save or load)
         if ($params['pst']) {
             $p_result = $this->pstContent->getParserOutput($titleObj, null, $popts);
         } else {
             $p_result = $this->content->getParserOutput($titleObj, null, $popts);
         }
     }
     $result_array = array();
     $result_array['title'] = $titleObj->getPrefixedText();
     if (!is_null($oldid)) {
         $result_array['revid'] = intval($oldid);
     }
     if ($params['redirects'] && !is_null($redirValues)) {
         $result_array['redirects'] = $redirValues;
     }
     if (isset($prop['text'])) {
         $result_array['text'] = array();
         $result->setContent($result_array['text'], $p_result->getText());
     }
     if (!is_null($params['summary'])) {
         $result_array['parsedsummary'] = array();
         $result->setContent($result_array['parsedsummary'], Linker::formatComment($params['summary'], $titleObj));
     }
     if (isset($prop['langlinks'])) {
         $result_array['langlinks'] = $this->formatLangLinks($p_result->getLanguageLinks());
     }
     if (isset($prop['languageshtml'])) {
         $languagesHtml = $this->languagesHtml($p_result->getLanguageLinks());
         $result_array['languageshtml'] = array();
         $result->setContent($result_array['languageshtml'], $languagesHtml);
     }
     if (isset($prop['categories'])) {
         $result_array['categories'] = $this->formatCategoryLinks($p_result->getCategories());
     }
     if (isset($prop['categorieshtml'])) {
         $categoriesHtml = $this->categoriesHtml($p_result->getCategories());
         $result_array['categorieshtml'] = array();
         $result->setContent($result_array['categorieshtml'], $categoriesHtml);
     }
     if (isset($prop['links'])) {
         $result_array['links'] = $this->formatLinks($p_result->getLinks());
     }
     if (isset($prop['templates'])) {
         $result_array['templates'] = $this->formatLinks($p_result->getTemplates());
     }
     if (isset($prop['images'])) {
         $result_array['images'] = array_keys($p_result->getImages());
     }
     if (isset($prop['externallinks'])) {
         $result_array['externallinks'] = array_keys($p_result->getExternalLinks());
     }
     if (isset($prop['sections'])) {
         $result_array['sections'] = $p_result->getSections();
     }
     if (isset($prop['displaytitle'])) {
         $result_array['displaytitle'] = $p_result->getDisplayTitle() ? $p_result->getDisplayTitle() : $titleObj->getPrefixedText();
     }
     if (isset($prop['headitems']) || isset($prop['headhtml'])) {
         $context = $this->getContext();
         $context->setTitle($titleObj);
         $context->getOutput()->addParserOutputNoText($p_result);
         if (isset($prop['headitems'])) {
             $headItems = $this->formatHeadItems($p_result->getHeadItems());
             $css = $this->formatCss($context->getOutput()->buildCssLinksArray());
             $scripts = array($context->getOutput()->getHeadScripts());
             $result_array['headitems'] = array_merge($headItems, $css, $scripts);
         }
         if (isset($prop['headhtml'])) {
             $result_array['headhtml'] = array();
             $result->setContent($result_array['headhtml'], $context->getOutput()->headElement($context->getSkin()));
         }
     }
     if (isset($prop['iwlinks'])) {
         $result_array['iwlinks'] = $this->formatIWLinks($p_result->getInterwikiLinks());
     }
     if (isset($prop['wikitext'])) {
         $result_array['wikitext'] = array();
         $result->setContent($result_array['wikitext'], $this->content->serialize($format));
         if (!is_null($this->pstContent)) {
             $result_array['psttext'] = array();
             $result->setContent($result_array['psttext'], $this->pstContent->serialize($format));
         }
     }
     if (isset($prop['properties'])) {
         $result_array['properties'] = $this->formatProperties($p_result->getProperties());
     }
     if ($params['generatexml']) {
         if ($this->content->getModel() != CONTENT_MODEL_WIKITEXT) {
             $this->dieUsage("generatexml is only supported for wikitext content", "notwikitext");
         }
         $wgParser->startExternalParse($titleObj, $popts, OT_PREPROCESS);
         $dom = $wgParser->preprocessToDom($this->content->getNativeData());
         if (is_callable(array($dom, 'saveXML'))) {
             $xml = $dom->saveXML();
         } else {
             $xml = $dom->__toString();
         }
         $result_array['parsetree'] = array();
         $result->setContent($result_array['parsetree'], $xml);
     }
     $result_mapping = array('redirects' => 'r', 'langlinks' => 'll', 'categories' => 'cl', 'links' => 'pl', 'templates' => 'tl', 'images' => 'img', 'externallinks' => 'el', 'iwlinks' => 'iw', 'sections' => 's', 'headitems' => 'hi', 'properties' => 'pp');
     $this->setIndexedTagNames($result_array, $result_mapping);
     $result->addValue(null, $this->getModuleName(), $result_array);
     if (!is_null($oldLang)) {
         $this->getContext()->setLanguage($oldLang);
         // Reset language to $oldLang
     }
 }