예제 #1
0
 public function __construct()
 {
     parent::__construct();
     $this->prefUsers['noemail'] = new User();
     $this->prefUsers['notauth'] = new User();
     $this->prefUsers['notauth']->setEmail('*****@*****.**');
     $this->prefUsers['auth'] = new User();
     $this->prefUsers['auth']->setEmail('*****@*****.**');
     $this->prefUsers['auth']->setEmailAuthenticationTimestamp(1330946623);
     $this->context = new RequestContext();
     $this->context->setTitle(Title::newFromText('PreferencesTest'));
 }
 protected function setUp()
 {
     parent::setUp();
     global $wgLang;
     $this->setMwGlobals(array('wgLogTypes' => array('phpunit'), 'wgLogActionsHandlers' => array('phpunit/test' => 'LogFormatter', 'phpunit/param' => 'LogFormatter'), 'wgUser' => User::newFromName('Testuser'), 'wgExtensionMessagesFiles' => array('LogTests' => __DIR__ . '/LogTests.i18n.php')));
     Language::getLocalisationCache()->recache($wgLang->getCode());
     $this->user = User::newFromName('Testuser');
     $this->title = Title::newMainPage();
     $this->context = new RequestContext();
     $this->context->setUser($this->user);
     $this->context->setTitle($this->title);
     $this->context->setLanguage($wgLang);
 }
 /**
  * Test the relationship between title and wikipage in RequestContext
  * @covers RequestContext::getWikiPage
  * @covers RequestContext::getTitle
  */
 public function testWikiPageTitle()
 {
     $context = new RequestContext();
     $curTitle = Title::newFromText("A");
     $context->setTitle($curTitle);
     $this->assertTrue($curTitle->equals($context->getWikiPage()->getTitle()), "When a title is first set WikiPage should be created on-demand for that title.");
     $curTitle = Title::newFromText("B");
     $context->setWikiPage(WikiPage::factory($curTitle));
     $this->assertTrue($curTitle->equals($context->getTitle()), "Title must be updated when a new WikiPage is provided.");
     $curTitle = Title::newFromText("C");
     $context->setTitle($curTitle);
     $this->assertTrue($curTitle->equals($context->getWikiPage()->getTitle()), "When a title is updated the WikiPage should be purged " . "and recreated on-demand with the new title.");
 }
예제 #4
0
 protected function setUp()
 {
     parent::setUp();
     global $wgLang;
     $this->setMwGlobals(['wgLogTypes' => ['phpunit'], 'wgLogActionsHandlers' => ['phpunit/test' => 'LogFormatter', 'phpunit/param' => 'LogFormatter'], 'wgUser' => User::newFromName('Testuser'), 'wgExtensionMessagesFiles' => ['LogTests' => __DIR__ . '/LogTests.i18n.php']]);
     Language::getLocalisationCache()->recache($wgLang->getCode());
     $this->user = User::newFromName('Testuser');
     $this->title = Title::newFromText('SomeTitle');
     $this->target = Title::newFromText('TestTarget');
     $this->context = new RequestContext();
     $this->context->setUser($this->user);
     $this->context->setTitle($this->title);
     $this->context->setLanguage($wgLang);
     $this->user_comment = '<User comment about action>';
 }
예제 #5
0
 /**
  * @see BaseDependencyContainer::registerDefinitions
  *
  * @since  1.9
  *
  * @return array
  */
 protected function getDefinitions()
 {
     return array('ParserData' => $this->getParserData(), 'NamespaceExaminer' => $this->getNamespaceExaminer(), 'JobFactory' => function (DependencyBuilder $builder) {
         return new \SMW\MediaWiki\Jobs\JobFactory();
     }, 'ContentParser' => function (DependencyBuilder $builder) {
         return new ContentParser($builder->getArgument('Title'));
     }, 'RequestContext' => function (DependencyBuilder $builder) {
         $instance = new \RequestContext();
         if ($builder->hasArgument('Title')) {
             $instance->setTitle($builder->getArgument('Title'));
         }
         if ($builder->hasArgument('Language')) {
             $instance->setLanguage($builder->getArgument('Language'));
         }
         return $instance;
     }, 'WikiPage' => function (DependencyBuilder $builder) {
         return \WikiPage::factory($builder->getArgument('Title'));
     }, 'TitleCreator' => function (DependencyBuilder $builder) {
         return new TitleCreator(new PageCreator());
     }, 'PageCreator' => function (DependencyBuilder $builder) {
         return new PageCreator();
     }, 'MessageFormatter' => function (DependencyBuilder $builder) {
         return new MessageFormatter($builder->getArgument('Language'));
     });
 }
 /**
  * @dataProvider titleDataProvider
  */
 public function testProcess($setup, $expected)
 {
     $skin = $this->getMockBuilder('\\Skin')->disableOriginalConstructor()->getMock();
     $context = new \RequestContext();
     $context->setTitle($setup['title']);
     $context->setLanguage(Language::factory('en'));
     $outputPage = new OutputPage($context);
     $instance = new BeforePageDisplay($outputPage, $skin);
     $result = $instance->process();
     $this->assertInternalType('boolean', $result);
     $this->assertTrue($result);
     $contains = false;
     if (method_exists($outputPage, 'getHeadLinksArray')) {
         foreach ($outputPage->getHeadLinksArray() as $key => $value) {
             if (strpos($value, 'ExportRDF')) {
                 $contains = true;
                 break;
             }
         }
     } else {
         // MW 1.19
         if (strpos($outputPage->getHeadLinks(), 'ExportRDF')) {
             $contains = true;
         }
     }
     $expected['result'] ? $this->assertTrue($contains) : $this->assertFalse($contains);
 }
 public function getTestContext(User $user)
 {
     $context = new RequestContext();
     $context->setLanguage('en');
     $context->setUser($user);
     $title = Title::newFromText('RecentChanges', NS_SPECIAL);
     $context->setTitle($title);
     return $context;
 }
 function setUp()
 {
     $this->page = new MIMESearchPage();
     $context = new RequestContext();
     $context->setTitle(Title::makeTitle(NS_SPECIAL, 'MIMESearch'));
     $context->setRequest(new FauxRequest());
     $this->page->setContext($context);
     parent::setUp();
 }
 public function testTryPrependHtmlForNonViewAction()
 {
     $context = new \RequestContext();
     $context->setRequest(new \FauxRequest(array('action' => 'edit'), true));
     $context->setTitle(Title::newFromText(__METHOD__));
     $htmlBreadcrumbLinksBuilder = $this->getMockBuilder('\\SBL\\HtmlBreadcrumbLinksBuilder')->disableOriginalConstructor()->getMock();
     $title = $this->getMockBuilder('\\Title')->disableOriginalConstructor()->getMock();
     $title->expects($this->once())->method('isKnown')->will($this->returnValue(true));
     $title->expects($this->once())->method('isSpecialPage')->will($this->returnValue(false));
     $output = $this->getMockBuilder('\\OutputPage')->disableOriginalConstructor()->getMock();
     $output->expects($this->never())->method('prependHTML');
     $output->expects($this->once())->method('getContext')->will($this->returnValue($context));
     $output->expects($this->atLeastOnce())->method('getTitle')->will($this->returnValue($title));
     $instance = new SkinTemplateOutputModifier($htmlBreadcrumbLinksBuilder);
     $this->assertTrue($instance->modifyOutput($output));
 }
 /**
  * Make sure a nickname which is longer than $wgMaxSigChars
  * is not throwing a fatal error.
  *
  * Test specifications by Alexandre "ialex" Emsenhuber.
  * @todo give this test a real name explaining what is being tested here
  */
 public function testBug41337()
 {
     // Set a low limit
     $this->setMwGlobals('wgMaxSigChars', 2);
     $user = $this->getMock('User');
     $user->expects($this->any())->method('isAnon')->will($this->returnValue(false));
     # Yeah foreach requires an array, not NULL =(
     $user->expects($this->any())->method('getEffectiveGroups')->will($this->returnValue([]));
     # The mocked user has a long nickname
     $user->expects($this->any())->method('getOption')->will($this->returnValueMap([['nickname', null, false, 'superlongnickname']]));
     # Forge a request to call the special page
     $context = new RequestContext();
     $context->setRequest(new FauxRequest());
     $context->setUser($user);
     $context->setTitle(Title::newFromText('Test'));
     # Do the call, should not spurt a fatal error.
     $special = new SpecialPreferences();
     $special->setContext($context);
     $this->assertNull($special->execute([]));
 }
 /**
  * Check, if context modules aren't arrays. They will be added as an array with modules to
  * to load, which doesn't allow arrays as values.
  */
 public function testGetContextSpecificModules()
 {
     // try to cover all possible modules (maybe extent, if other modules added)
     $values = array('wgMFEnableBeta' => true);
     $this->setMwGlobals($values);
     // UTSysop will be a logged in user
     $user = User::newFromName('UTSysop');
     $user->load();
     // create a new RequestContext for this test case and set User and title
     $context = new RequestContext();
     $context->setUser($user);
     // UTPage is an existing page in the main namespace
     $context->setTitle(Title::newFromText('UTPage'));
     MobileContext::singleton()->setMobileMode('alpha');
     $skin = $this->getSkin();
     $skin->setContext($context);
     $modules = $skin->getContextSpecificModules();
     foreach ($modules as $module) {
         $this->assertFalse(is_array($module), 'Context specific modules can\'t be arrays.');
     }
 }
예제 #12
0
 /**
  * @dataProvider providerShowRedLinks
  */
 public function testRedLinks($showRedLinks, $showRedLinksAnon, $username, $expected)
 {
     // set config variables, which we test here
     $values = array('wgMFShowRedLinks' => $showRedLinks, 'wgMFShowRedLinksAnon' => $showRedLinksAnon, 'wgMFEnableBeta' => true);
     $this->setMwGlobals($values);
     // create our specific user object
     $user = User::newFromName($username);
     $user->load();
     // create a new RequestContext for this test case and set User and title
     $context = new RequestContext();
     $context->setUser($user);
     $context->setTitle(Title::newFromText('Main_page'));
     // create SkinMinerva to test
     $skin = $this->getSkin();
     $skin->setContext($context);
     // set the fake mobile mode
     MobileContext::singleton()->setMobileMode($this->getMode());
     // test now
     $vars = $skin->getSkinConfigVariables();
     $this->assertEquals($expected, $vars['wgMFShowRedLinks']);
 }
예제 #13
0
 /**
  * Just like executePath() except it returns the HTML instead of outputting it
  * Returns false if there was no such special page, or a title object if it was
  * a redirect.
  *
  * Also saves the current $wgTitle, $wgOut, and $wgRequest variables so that
  * the special page will get the context it'd expect on a normal request,
  * and then restores them to their previous values after.
  *
  * @param $title Title
  *
  * @return String: HTML fragment
  */
 static function capturePath(&$title)
 {
     global $wgOut, $wgTitle, $wgRequest;
     $oldTitle = $wgTitle;
     $oldOut = $wgOut;
     $oldRequest = $wgRequest;
     // Don't want special pages interpreting ?feed=atom parameters.
     $wgRequest = new FauxRequest(array());
     $context = new RequestContext();
     $context->setTitle($title);
     $context->setRequest($wgRequest);
     $wgOut = $context->getOutput();
     $ret = self::executePath($title, $context, true);
     if ($ret === true) {
         $ret = $wgOut->getHTML();
     }
     $wgTitle = $oldTitle;
     $wgOut = $oldOut;
     $wgRequest = $oldRequest;
     return $ret;
 }
예제 #14
0
 /**
  * Return the text of a template, after recursively
  * replacing any variables or templates within the template.
  *
  * @param array $piece The parts of the template
  *  $piece['title']: the title, i.e. the part before the |
  *  $piece['parts']: the parameter array
  *  $piece['lineStart']: whether the brace was at the start of a line
  * @param PPFrame $frame The current frame, contains template arguments
  * @throws MWException
  * @return string The text of the template
  * @private
  */
 function braceSubstitution($piece, $frame)
 {
     wfProfileIn(__METHOD__);
     wfProfileIn(__METHOD__ . '-setup');
     # Flags
     $found = false;
     # $text has been filled
     $nowiki = false;
     # wiki markup in $text should be escaped
     $isHTML = false;
     # $text is HTML, armour it against wikitext transformation
     $forceRawInterwiki = false;
     # Force interwiki transclusion to be done in raw mode not rendered
     $isChildObj = false;
     # $text is a DOM node needing expansion in a child frame
     $isLocalObj = false;
     # $text is a DOM node needing expansion in the current frame
     # Title object, where $text came from
     $title = false;
     # $part1 is the bit before the first |, and must contain only title characters.
     # Various prefixes will be stripped from it later.
     $titleWithSpaces = $frame->expand($piece['title']);
     $part1 = trim($titleWithSpaces);
     $titleText = false;
     # Original title text preserved for various purposes
     $originalTitle = $part1;
     # $args is a list of argument nodes, starting from index 0, not including $part1
     # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
     $args = null == $piece['parts'] ? array() : $piece['parts'];
     wfProfileOut(__METHOD__ . '-setup');
     $titleProfileIn = null;
     // profile templates
     # SUBST
     wfProfileIn(__METHOD__ . '-modifiers');
     if (!$found) {
         $substMatch = $this->mSubstWords->matchStartAndRemove($part1);
         # Possibilities for substMatch: "subst", "safesubst" or FALSE
         # Decide whether to expand template or keep wikitext as-is.
         if ($this->ot['wiki']) {
             if ($substMatch === false) {
                 $literal = true;
                 # literal when in PST with no prefix
             } else {
                 $literal = false;
                 # expand when in PST with subst: or safesubst:
             }
         } else {
             if ($substMatch == 'subst') {
                 $literal = true;
                 # literal when not in PST with plain subst:
             } else {
                 $literal = false;
                 # expand when not in PST with safesubst: or no prefix
             }
         }
         if ($literal) {
             $text = $frame->virtualBracketedImplode('{{', '|', '}}', $titleWithSpaces, $args);
             $isLocalObj = true;
             $found = true;
         }
     }
     # Variables
     if (!$found && $args->getLength() == 0) {
         $id = $this->mVariables->matchStartToEnd($part1);
         if ($id !== false) {
             $text = $this->getVariableValue($id, $frame);
             if (MagicWord::getCacheTTL($id) > -1) {
                 $this->mOutput->updateCacheExpiry(MagicWord::getCacheTTL($id));
             }
             $found = true;
         }
     }
     # MSG, MSGNW and RAW
     if (!$found) {
         # Check for MSGNW:
         $mwMsgnw = MagicWord::get('msgnw');
         if ($mwMsgnw->matchStartAndRemove($part1)) {
             $nowiki = true;
         } else {
             # Remove obsolete MSG:
             $mwMsg = MagicWord::get('msg');
             $mwMsg->matchStartAndRemove($part1);
         }
         # Check for RAW:
         $mwRaw = MagicWord::get('raw');
         if ($mwRaw->matchStartAndRemove($part1)) {
             $forceRawInterwiki = true;
         }
     }
     wfProfileOut(__METHOD__ . '-modifiers');
     # Parser functions
     if (!$found) {
         wfProfileIn(__METHOD__ . '-pfunc');
         $colonPos = strpos($part1, ':');
         if ($colonPos !== false) {
             $func = substr($part1, 0, $colonPos);
             $funcArgs = array(trim(substr($part1, $colonPos + 1)));
             for ($i = 0; $i < $args->getLength(); $i++) {
                 $funcArgs[] = $args->item($i);
             }
             try {
                 $result = $this->callParserFunction($frame, $func, $funcArgs);
             } catch (Exception $ex) {
                 wfProfileOut(__METHOD__ . '-pfunc');
                 wfProfileOut(__METHOD__);
                 throw $ex;
             }
             # The interface for parser functions allows for extracting
             # flags into the local scope. Extract any forwarded flags
             # here.
             extract($result);
         }
         wfProfileOut(__METHOD__ . '-pfunc');
     }
     # Finish mangling title and then check for loops.
     # Set $title to a Title object and $titleText to the PDBK
     if (!$found) {
         $ns = NS_TEMPLATE;
         # Split the title into page and subpage
         $subpage = '';
         $relative = $this->maybeDoSubpageLink($part1, $subpage);
         if ($part1 !== $relative) {
             $part1 = $relative;
             $ns = $this->mTitle->getNamespace();
         }
         $title = Title::newFromText($part1, $ns);
         if ($title) {
             $titleText = $title->getPrefixedText();
             # Check for language variants if the template is not found
             if ($this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0) {
                 $this->getConverterLanguage()->findVariantLink($part1, $title, true);
             }
             # Do recursion depth check
             $limit = $this->mOptions->getMaxTemplateDepth();
             if ($frame->depth >= $limit) {
                 $found = true;
                 $text = '<span class="error">' . wfMessage('parser-template-recursion-depth-warning')->numParams($limit)->inContentLanguage()->text() . '</span>';
             }
         }
     }
     # Load from database
     if (!$found && $title) {
         if (!Profiler::instance()->isPersistent()) {
             # Too many unique items can kill profiling DBs/collectors
             $titleProfileIn = __METHOD__ . "-title-" . $title->getPrefixedDBkey();
             wfProfileIn($titleProfileIn);
             // template in
         }
         wfProfileIn(__METHOD__ . '-loadtpl');
         if (!$title->isExternal()) {
             if ($title->isSpecialPage() && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html']) {
                 // Pass the template arguments as URL parameters.
                 // "uselang" will have no effect since the Language object
                 // is forced to the one defined in ParserOptions.
                 $pageArgs = array();
                 for ($i = 0; $i < $args->getLength(); $i++) {
                     $bits = $args->item($i)->splitArg();
                     if (strval($bits['index']) === '') {
                         $name = trim($frame->expand($bits['name'], PPFrame::STRIP_COMMENTS));
                         $value = trim($frame->expand($bits['value']));
                         $pageArgs[$name] = $value;
                     }
                 }
                 // Create a new context to execute the special page
                 $context = new RequestContext();
                 $context->setTitle($title);
                 $context->setRequest(new FauxRequest($pageArgs));
                 $context->setUser($this->getUser());
                 $context->setLanguage($this->mOptions->getUserLangObj());
                 $ret = SpecialPageFactory::capturePath($title, $context);
                 if ($ret) {
                     $text = $context->getOutput()->getHTML();
                     $this->mOutput->addOutputPageMetadata($context->getOutput());
                     $found = true;
                     $isHTML = true;
                     $this->disableCache();
                 }
             } elseif (MWNamespace::isNonincludable($title->getNamespace())) {
                 $found = false;
                 # access denied
                 wfDebug(__METHOD__ . ": template inclusion denied for " . $title->getPrefixedDBkey() . "\n");
             } else {
                 list($text, $title) = $this->getTemplateDom($title);
                 if ($text !== false) {
                     $found = true;
                     $isChildObj = true;
                 }
             }
             # If the title is valid but undisplayable, make a link to it
             if (!$found && ($this->ot['html'] || $this->ot['pre'])) {
                 $text = "[[:{$titleText}]]";
                 $found = true;
             }
         } elseif ($title->isTrans()) {
             # Interwiki transclusion
             if ($this->ot['html'] && !$forceRawInterwiki) {
                 $text = $this->interwikiTransclude($title, 'render');
                 $isHTML = true;
             } else {
                 $text = $this->interwikiTransclude($title, 'raw');
                 # Preprocess it like a template
                 $text = $this->preprocessToDom($text, self::PTD_FOR_INCLUSION);
                 $isChildObj = true;
             }
             $found = true;
         }
         # Do infinite loop check
         # This has to be done after redirect resolution to avoid infinite loops via redirects
         if (!$frame->loopCheck($title)) {
             $found = true;
             $text = '<span class="error">' . wfMessage('parser-template-loop-warning', $titleText)->inContentLanguage()->text() . '</span>';
             wfDebug(__METHOD__ . ": template loop broken at '{$titleText}'\n");
         }
         wfProfileOut(__METHOD__ . '-loadtpl');
     }
     # If we haven't found text to substitute by now, we're done
     # Recover the source wikitext and return it
     if (!$found) {
         $text = $frame->virtualBracketedImplode('{{', '|', '}}', $titleWithSpaces, $args);
         if ($titleProfileIn) {
             wfProfileOut($titleProfileIn);
             // template out
         }
         wfProfileOut(__METHOD__);
         return array('object' => $text);
     }
     # Expand DOM-style return values in a child frame
     if ($isChildObj) {
         # Clean up argument array
         $newFrame = $frame->newChild($args, $title);
         if ($nowiki) {
             $text = $newFrame->expand($text, PPFrame::RECOVER_ORIG);
         } elseif ($titleText !== false && $newFrame->isEmpty()) {
             # Expansion is eligible for the empty-frame cache
             if (isset($this->mTplExpandCache[$titleText])) {
                 $text = $this->mTplExpandCache[$titleText];
             } else {
                 $text = $newFrame->expand($text);
                 $this->mTplExpandCache[$titleText] = $text;
             }
         } else {
             # Uncached expansion
             $text = $newFrame->expand($text);
         }
     }
     if ($isLocalObj && $nowiki) {
         $text = $frame->expand($text, PPFrame::RECOVER_ORIG);
         $isLocalObj = false;
     }
     if ($titleProfileIn) {
         wfProfileOut($titleProfileIn);
         // template out
     }
     # Replace raw HTML by a placeholder
     if ($isHTML) {
         $text = $this->insertStripItem($text);
     } elseif ($nowiki && ($this->ot['html'] || $this->ot['pre'])) {
         # Escape nowiki-style return values
         $text = wfEscapeWikiText($text);
     } elseif (is_string($text) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\\*)/', $text)) {
         # Bug 529: if the template begins with a table or block-level
         # element, it should be treated as beginning a new line.
         # This behavior is somewhat controversial.
         $text = "\n" . $text;
     }
     if (is_string($text) && !$this->incrementIncludeSize('post-expand', strlen($text))) {
         # Error, oversize inclusion
         if ($titleText !== false) {
             # Make a working, properly escaped link if possible (bug 23588)
             $text = "[[:{$titleText}]]";
         } else {
             # This will probably not be a working link, but at least it may
             # provide some hint of where the problem is
             preg_replace('/^:/', '', $originalTitle);
             $text = "[[:{$originalTitle}]]";
         }
         $text .= $this->insertStripItem('<!-- WARNING: template omitted, post-expand include size too large -->');
         $this->limitationWarn('post-expand-template-inclusion');
     }
     if ($isLocalObj) {
         $ret = array('object' => $text);
     } else {
         $ret = array('text' => $text);
     }
     wfProfileOut(__METHOD__);
     return $ret;
 }
예제 #15
0
 public function execute()
 {
     global $wgRequestTime;
     if (!$this->enabled) {
         $this->error("Nothing to do -- \$wgUseFileCache is disabled.", true);
     }
     $start = $this->getOption('start', "0");
     if (!ctype_digit($start)) {
         $this->error("Invalid value for start parameter.", true);
     }
     $start = intval($start);
     $end = $this->getOption('end', "0");
     if (!ctype_digit($end)) {
         $this->error("Invalid value for end parameter.", true);
     }
     $end = intval($end);
     $this->output("Building content page file cache from page {$start}!\n");
     $dbr = $this->getDB(DB_REPLICA);
     $overwrite = $this->getOption('overwrite', false);
     $start = $start > 0 ? $start : $dbr->selectField('page', 'MIN(page_id)', false, __METHOD__);
     $end = $end > 0 ? $end : $dbr->selectField('page', 'MAX(page_id)', false, __METHOD__);
     if (!$start) {
         $this->error("Nothing to do.", true);
     }
     $_SERVER['HTTP_ACCEPT_ENCODING'] = 'bgzip';
     // hack, no real client
     # Do remaining chunk
     $end += $this->mBatchSize - 1;
     $blockStart = $start;
     $blockEnd = $start + $this->mBatchSize - 1;
     $dbw = $this->getDB(DB_MASTER);
     // Go through each page and save the output
     while ($blockEnd <= $end) {
         // Get the pages
         $res = $dbr->select('page', ['page_namespace', 'page_title', 'page_id'], ['page_namespace' => MWNamespace::getContentNamespaces(), "page_id BETWEEN {$blockStart} AND {$blockEnd}"], __METHOD__, ['ORDER BY' => 'page_id ASC', 'USE INDEX' => 'PRIMARY']);
         $this->beginTransaction($dbw, __METHOD__);
         // for any changes
         foreach ($res as $row) {
             $rebuilt = false;
             $title = Title::makeTitleSafe($row->page_namespace, $row->page_title);
             if (null == $title) {
                 $this->output("Page {$row->page_id} has bad title\n");
                 continue;
                 // broken title?
             }
             $context = new RequestContext();
             $context->setTitle($title);
             $article = Article::newFromTitle($title, $context);
             $context->setWikiPage($article->getPage());
             // If the article is cacheable, then load it
             if ($article->isFileCacheable(HTMLFileCache::MODE_REBUILD)) {
                 $viewCache = new HTMLFileCache($title, 'view');
                 $historyCache = new HTMLFileCache($title, 'history');
                 if ($viewCache->isCacheGood() && $historyCache->isCacheGood()) {
                     if ($overwrite) {
                         $rebuilt = true;
                     } else {
                         $this->output("Page '{$title}' (id {$row->page_id}) already cached\n");
                         continue;
                         // done already!
                     }
                 }
                 MediaWiki\suppressWarnings();
                 // header notices
                 // Cache ?action=view
                 $wgRequestTime = microtime(true);
                 # bug 22852
                 ob_start();
                 $article->view();
                 $context->getOutput()->output();
                 $context->getOutput()->clearHTML();
                 $viewHtml = ob_get_clean();
                 $viewCache->saveToFileCache($viewHtml);
                 // Cache ?action=history
                 $wgRequestTime = microtime(true);
                 # bug 22852
                 ob_start();
                 Action::factory('history', $article, $context)->show();
                 $context->getOutput()->output();
                 $context->getOutput()->clearHTML();
                 $historyHtml = ob_get_clean();
                 $historyCache->saveToFileCache($historyHtml);
                 MediaWiki\restoreWarnings();
                 if ($rebuilt) {
                     $this->output("Re-cached page '{$title}' (id {$row->page_id})...");
                 } else {
                     $this->output("Cached page '{$title}' (id {$row->page_id})...");
                 }
                 $this->output("[view: " . strlen($viewHtml) . " bytes; " . "history: " . strlen($historyHtml) . " bytes]\n");
             } else {
                 $this->output("Page '{$title}' (id {$row->page_id}) not cacheable\n");
             }
         }
         $this->commitTransaction($dbw, __METHOD__);
         // commit any changes (just for sanity)
         $blockStart += $this->mBatchSize;
         $blockEnd += $this->mBatchSize;
     }
     $this->output("Done!\n");
 }
 public function execute()
 {
     global $wgUseFileCache, $wgReadOnly, $wgContentNamespaces, $wgRequestTime;
     global $wgOut;
     if (!$wgUseFileCache) {
         $this->error("Nothing to do -- \$wgUseFileCache is disabled.", true);
     }
     $wgReadOnly = 'Building cache';
     // avoid DB writes (like enotif/counters)
     $start = $this->getOption('start', "0");
     if (!ctype_digit($start)) {
         $this->error("Invalid value for start parameter.", true);
     }
     $start = intval($start);
     $end = $this->getOption('end', "0");
     if (!ctype_digit($end)) {
         $this->error("Invalid value for end parameter.", true);
     }
     $end = intval($end);
     $this->output("Building content page file cache from page {$start}!\n");
     $dbr = $this->getDB(DB_SLAVE);
     $overwrite = $this->getOption('overwrite', false);
     $start = $start > 0 ? $start : $dbr->selectField('page', 'MIN(page_id)', false, __FUNCTION__);
     $end = $end > 0 ? $end : $dbr->selectField('page', 'MAX(page_id)', false, __FUNCTION__);
     if (!$start) {
         $this->error("Nothing to do.", true);
     }
     $_SERVER['HTTP_ACCEPT_ENCODING'] = 'bgzip';
     // hack, no real client
     # Do remaining chunk
     $end += $this->mBatchSize - 1;
     $blockStart = $start;
     $blockEnd = $start + $this->mBatchSize - 1;
     $dbw = $this->getDB(DB_MASTER);
     // Go through each page and save the output
     while ($blockEnd <= $end) {
         // Get the pages
         $res = $dbr->select('page', array('page_namespace', 'page_title', 'page_id'), array('page_namespace' => $wgContentNamespaces, "page_id BETWEEN {$blockStart} AND {$blockEnd}"), array('ORDER BY' => 'page_id ASC', 'USE INDEX' => 'PRIMARY'));
         $this->beginTransaction($dbw, __METHOD__);
         // for any changes
         foreach ($res as $row) {
             $rebuilt = false;
             $wgRequestTime = microtime(true);
             # bug 22852
             $title = Title::makeTitleSafe($row->page_namespace, $row->page_title);
             if (null == $title) {
                 $this->output("Page {$row->page_id} has bad title\n");
                 continue;
                 // broken title?
             }
             $context = new RequestContext();
             $context->setTitle($title);
             $article = Article::newFromTitle($title, $context);
             $context->setWikiPage($article->getPage());
             $wgOut = $context->getOutput();
             // set display title
             // If the article is cacheable, then load it
             if ($article->isFileCacheable()) {
                 $cache = HTMLFileCache::newFromTitle($title, 'view');
                 if ($cache->isCacheGood()) {
                     if ($overwrite) {
                         $rebuilt = true;
                     } else {
                         $this->output("Page {$row->page_id} already cached\n");
                         continue;
                         // done already!
                     }
                 }
                 ob_start(array(&$cache, 'saveToFileCache'));
                 // save on ob_end_clean()
                 $wgUseFileCache = false;
                 // hack, we don't want $article fiddling with filecache
                 $article->view();
                 MediaWiki\suppressWarnings();
                 // header notices
                 $wgOut->output();
                 MediaWiki\restoreWarnings();
                 $wgUseFileCache = true;
                 ob_end_clean();
                 // clear buffer
                 if ($rebuilt) {
                     $this->output("Re-cached page {$row->page_id}\n");
                 } else {
                     $this->output("Cached page {$row->page_id}\n");
                 }
             } else {
                 $this->output("Page {$row->page_id} not cacheable\n");
             }
         }
         $this->commitTransaction($dbw, __METHOD__);
         // commit any changes (just for sanity)
         $blockStart += $this->mBatchSize;
         $blockEnd += $this->mBatchSize;
     }
     $this->output("Done!\n");
 }
예제 #17
0
 public function execute()
 {
     global $wgUseFileCache, $wgDisableCounters, $wgContentNamespaces, $wgRequestTime;
     global $wgTitle, $wgOut;
     if (!$wgUseFileCache) {
         $this->error("Nothing to do -- \$wgUseFileCache is disabled.", true);
     }
     $wgDisableCounters = false;
     $start = $this->getArg(0, "0");
     if (!ctype_digit($start)) {
         $this->error("Invalid value for start parameter.", true);
     }
     $start = intval($start);
     $overwrite = $this->hasArg(1) && $this->getArg(1) === 'overwrite';
     $this->output("Building content page file cache from page {$start}!\n");
     $dbr = wfGetDB(DB_SLAVE);
     $start = $start > 0 ? $start : $dbr->selectField('page', 'MIN(page_id)', false, __FUNCTION__);
     $end = $dbr->selectField('page', 'MAX(page_id)', false, __FUNCTION__);
     if (!$start) {
         $this->error("Nothing to do.", true);
     }
     $_SERVER['HTTP_ACCEPT_ENCODING'] = 'bgzip';
     // hack, no real client
     # Do remaining chunk
     $end += $this->mBatchSize - 1;
     $blockStart = $start;
     $blockEnd = $start + $this->mBatchSize - 1;
     $dbw = wfGetDB(DB_MASTER);
     // Go through each page and save the output
     while ($blockEnd <= $end) {
         // Get the pages
         $res = $dbr->select('page', array('page_namespace', 'page_title', 'page_id'), array('page_namespace' => $wgContentNamespaces, "page_id BETWEEN {$blockStart} AND {$blockEnd}"), array('ORDER BY' => 'page_id ASC', 'USE INDEX' => 'PRIMARY'));
         foreach ($res as $row) {
             $rebuilt = false;
             $wgRequestTime = wfTime();
             # bug 22852
             $context = new RequestContext();
             $wgTitle = Title::makeTitleSafe($row->page_namespace, $row->page_title);
             $context->setTitle($wgTitle);
             if (null == $wgTitle) {
                 $this->output("Page {$row->page_id} has bad title\n");
                 continue;
                 // broken title?
             }
             $wgOut = $context->getOutput();
             // set display title
             $article = new Article($wgTitle);
             // If the article is cacheable, then load it
             if ($article->isFileCacheable()) {
                 $cache = new HTMLFileCache($wgTitle);
                 if ($cache->isFileCacheGood()) {
                     if ($overwrite) {
                         $rebuilt = true;
                     } else {
                         $this->output("Page {$row->page_id} already cached\n");
                         continue;
                         // done already!
                     }
                 }
                 ob_start(array(&$cache, 'saveToFileCache'));
                 // save on ob_end_clean()
                 $wgUseFileCache = false;
                 // hack, we don't want $article fiddling with filecache
                 $article->view();
                 wfSuppressWarnings();
                 // header notices
                 $wgOut->output();
                 wfRestoreWarnings();
                 $wgUseFileCache = true;
                 ob_end_clean();
                 // clear buffer
                 if ($rebuilt) {
                     $this->output("Re-cached page {$row->page_id}\n");
                 } else {
                     $this->output("Cached page {$row->page_id}\n");
                 }
             } else {
                 $this->output("Page {$row->page_id} not cacheable\n");
             }
             $dbw->commit();
             // commit any changes
         }
         $blockStart += $this->mBatchSize;
         $blockEnd += $this->mBatchSize;
         wfWaitForSlaves();
     }
     $this->output("Done!\n");
     // Remove these to be safe
     if (isset($wgTitle)) {
         unset($wgTitle);
     }
 }
예제 #18
0
 /**
  * Really find the title match.
  */
 private static function getNearMatchInternal($searchterm)
 {
     global $wgContLang;
     $allSearchTerms = array($searchterm);
     if ($wgContLang->hasVariants()) {
         $allSearchTerms = array_merge($allSearchTerms, $wgContLang->autoConvertToAllVariants($searchterm));
     }
     $titleResult = null;
     if (!wfRunHooks('SearchGetNearMatchBefore', array($allSearchTerms, &$titleResult))) {
         return $titleResult;
     }
     $context = new RequestContext();
     foreach ($allSearchTerms as $term) {
         # Exact match? No need to look further.
         $title = Title::newFromText($term);
         if (is_null($title)) {
             return null;
         }
         if ($title->getNamespace() == NS_SPECIAL || $title->isExternal() || $title->exists()) {
             return $title;
         }
         # See if it still otherwise has content is some sane sense
         $context->setTitle($title);
         $article = Article::newFromTitle($title, $context);
         if ($article->hasViewableContent()) {
             return $title;
         }
         # Now try all lower case (i.e. first letter capitalized)
         #
         $title = Title::newFromText($wgContLang->lc($term));
         if ($title && $title->exists()) {
             return $title;
         }
         # Now try capitalized string
         #
         $title = Title::newFromText($wgContLang->ucwords($term));
         if ($title && $title->exists()) {
             return $title;
         }
         # Now try all upper case
         #
         $title = Title::newFromText($wgContLang->uc($term));
         if ($title && $title->exists()) {
             return $title;
         }
         # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
         $title = Title::newFromText($wgContLang->ucwordbreaks($term));
         if ($title && $title->exists()) {
             return $title;
         }
         // Give hooks a chance at better match variants
         $title = null;
         if (!wfRunHooks('SearchGetNearMatch', array($term, &$title))) {
             return $title;
         }
     }
     $title = Title::newFromText($searchterm);
     # Entering an IP address goes to the contributions page
     if ($title->getNamespace() == NS_USER && User::isIP($title->getText()) || User::isIP(trim($searchterm))) {
         return SpecialPage::getTitleFor('Contributions', $title->getDBkey());
     }
     # Entering a user goes to the user page whether it's there or not
     if ($title->getNamespace() == NS_USER) {
         return $title;
     }
     # Go to images that exist even if there's no local page.
     # There may have been a funny upload, or it may be on a shared
     # file repository such as Wikimedia Commons.
     if ($title->getNamespace() == NS_FILE) {
         $image = wfFindFile($title);
         if ($image) {
             return $title;
         }
     }
     # MediaWiki namespace? Page may be "implied" if not customized.
     # Just return it, with caps forced as the message system likes it.
     if ($title->getNamespace() == NS_MEDIAWIKI) {
         return Title::makeTitle(NS_MEDIAWIKI, $wgContLang->ucfirst($title->getText()));
     }
     # Quoted term? Try without the quotes...
     $matches = array();
     if (preg_match('/^"([^"]+)"$/', $searchterm, $matches)) {
         return SearchEngine::getNearMatch($matches[1]);
     }
     return null;
 }