コード例 #1
0
 /**
  * @see Bug 8689
  * @covers Parser::parse
  */
 public function testLongNumericLinesDontKillTheParser()
 {
     $longLine = '1.' . str_repeat('1234567890', 100000) . "\n";
     $title = Title::newFromText('Unit test');
     $options = ParserOptions::newFromUser(new User());
     $this->assertEquals("<p>{$longLine}</p>", $this->parser->parse($longLine, $title, $options)->getText());
 }
コード例 #2
0
 function getMessagesFormatted($severity = self::MESSAGE_WARNING, $header = null)
 {
     global $wgTitle, $wgUser;
     $ret = '';
     foreach ($this->mMessages as $message) {
         if ($message[1] <= $severity) {
             $ret .= '* ' . $message[0] . "\n";
         }
     }
     if ($ret != '') {
         if (!$this->mParser) {
             $parser = new Parser();
         }
         if ($header == null) {
             $header = '';
         } elseif ($header != '') {
             $header = Html::rawElement('div', array('class' => 'heading'), $header);
         }
         $ret = Html::rawElement('div', array('class' => 'messages'), $header . "\n" . $ret);
         $ret = $parser->parse($ret, $wgTitle, ParserOptions::newFromUser($wgUser));
     } else {
         $ret = null;
     }
     return $ret;
 }
コード例 #3
0
 function initialise(&$memCached, $useDB, $expiry, $memcPrefix)
 {
     $fname = 'MessageCache::initialise';
     wfProfileIn($fname);
     $this->mUseCache = !is_null($memCached);
     $this->mMemc =& $memCached;
     $this->mDisable = !$useDB;
     $this->mExpiry = $expiry;
     $this->mDisableTransform = false;
     $this->mMemcKey = $memcPrefix . ':messages';
     $this->mKeys = false;
     # initialised on demand
     $this->mInitialised = true;
     wfProfileIn($fname . '-parseropt');
     $this->mParserOptions = ParserOptions::newFromUser($u = NULL);
     wfProfileOut($fname . '-parseropt');
     wfProfileIn($fname . '-parser');
     $this->mParser = new Parser();
     wfProfileOut($fname . '-parser');
     # When we first get asked for a message,
     # then we'll fill up the cache. If we
     # can return a cache hit, this saves
     # some extra milliseconds
     $this->mDeferred = true;
     wfProfileOut($fname);
 }
コード例 #4
0
 function genParserOptions()
 {
     global $wgUser;
     $this->mParserOptions = ParserOptions::newFromUser($wgUser);
     $this->mParserOptions->setDateFormat(MW_DATE_DEFAULT);
     $this->mParserOptions->setEditSection(false);
 }
コード例 #5
0
	function sandboxParse($wikiText){
		global $wgUser;
		$myParser = new Parser();
		$myParserOptions = ParserOptions::newFromUser( $wgUser );
		$result = $myParser->parse($wikiText, $this->getTitle(), $myParserOptions);
		return $result->getText();
	}
コード例 #6
0
ファイル: FlagView.class.php プロジェクト: Tjorriemorrie/app
 /**
  * Parses the wrapped wikitext and returns an HTML block of code with rendered flags.
  * @param array $templateCalls
  * @param $pageId
  * @return ParserOutput
  */
 public function renderFlags(array $templateCalls, $pageId)
 {
     global $wgUser;
     $wikitext = $this->wrapAllFlags($templateCalls);
     $title = \Title::newFromID($pageId);
     return \ParserPool::parse($wikitext, $title, \ParserOptions::newFromUser($wgUser));
 }
コード例 #7
0
 public function checkOptions()
 {
     if ($this->hasOption('save-failed')) {
         $this->saveFailed = $this->getOption('save-failed');
     }
     $this->stripParametersEnabled = $this->hasOption('strip-parameters');
     $this->showParsedOutput = $this->hasOption('show-parsed-output');
     $this->showDiff = $this->hasOption('show-diff');
     if ($this->showDiff) {
         $bin = $this->getOption('diff-bin', getenv('DIFF'));
         if ($bin != '') {
             global $wgDiff;
             $wgDiff = $bin;
         }
     }
     $user = new User();
     $this->options = ParserOptions::newFromUser($user);
     if ($this->hasOption('tidy')) {
         global $wgUseTidy;
         if (!$wgUseTidy) {
             $this->error('Tidy was requested but $wgUseTidy is not set in LocalSettings.php', true);
         }
         $this->options->setTidy(true);
     }
     $this->failed = 0;
 }
コード例 #8
0
 function testBug8689()
 {
     global $wgUser;
     $longLine = '1.' . str_repeat('1234567890', 100000) . "\n";
     $t = Title::newFromText('Unit test');
     $options = ParserOptions::newFromUser($wgUser);
     $this->assertEquals("<p>{$longLine}</p>", $this->parser->parse($longLine, $t, $options)->getText());
 }
コード例 #9
0
 /**
  * Get template and image versions from parsing a revision
  * @param Page $article
  * @param Revision $rev
  * @param User $user
  * @param string $regen use 'regen' to force regeneration
  * @return array( templateIds, fileSHA1Keys )
  * templateIds like ParserOutput->mTemplateIds
  * fileSHA1Keys like ParserOutput->mImageTimeKeys
  */
 public static function getRevIncludes(Page $article, Revision $rev, User $user, $regen = '')
 {
     global $wgParser, $wgMemc;
     wfProfileIn(__METHOD__);
     $versions = false;
     $key = self::getCacheKey($article->getTitle(), $rev->getId());
     if ($regen !== 'regen') {
         // check cache
         $versions = FlaggedRevs::getMemcValue($wgMemc->get($key), $article, 'allowStale');
     }
     if (!is_array($versions)) {
         // cache miss
         $pOut = false;
         if ($rev->isCurrent()) {
             $parserCache = ParserCache::singleton();
             # Try current version parser cache (as anon)...
             $pOut = $parserCache->get($article, $article->makeParserOptions($user));
             if ($pOut == false && $rev->getUser()) {
                 // try the user who saved the change
                 $author = User::newFromId($rev->getUser());
                 $pOut = $parserCache->get($article, $article->makeParserOptions($author));
             }
         }
         // ParserOutput::mImageTimeKeys wasn't always there
         if ($pOut == false || !FlaggedRevs::parserOutputIsVersioned($pOut)) {
             $title = $article->getTitle();
             $pOpts = ParserOptions::newFromUser($user);
             // Note: tidy off
             $pOut = $wgParser->parse($rev->getText(), $title, $pOpts, true, true, $rev->getId());
         }
         # Get the template/file versions used...
         $versions = array($pOut->getTemplateIds(), $pOut->getFileSearchOptions());
         # Save to cache (check cache expiry for dynamic elements)...
         $data = FlaggedRevs::makeMemcObj($versions);
         $wgMemc->set($key, $data, $pOut->getCacheExpiry());
     } else {
         $tVersions =& $versions[0];
         // templates
         # Do a link batch query for page_latest...
         $lb = new LinkBatch();
         foreach ($tVersions as $ns => $tmps) {
             foreach ($tmps as $dbKey => $revIdDraft) {
                 $lb->add($ns, $dbKey);
             }
         }
         $lb->execute();
         # Update array with the current page_latest values.
         # This kludge is there since $newTemplates (thus $revIdDraft) is cached.
         foreach ($tVersions as $ns => &$tmps) {
             foreach ($tmps as $dbKey => &$revIdDraft) {
                 $title = Title::makeTitle($ns, $dbKey);
                 $revIdDraft = (int) $title->getLatestRevID();
             }
         }
     }
     wfProfileOut(__METHOD__);
     return $versions;
 }
コード例 #10
0
 /**
  * Get template and image versions from parsing a revision
  * @param Page $article
  * @param Revision $rev
  * @param User $user
  * @param string $regen use 'regen' to force regeneration
  * @return array( templateIds, fileSHA1Keys )
  * templateIds like ParserOutput->mTemplateIds
  * fileSHA1Keys like ParserOutput->mImageTimeKeys
  */
 public static function getRevIncludes(Page $article, Revision $rev, User $user, $regen = '')
 {
     global $wgMemc;
     wfProfileIn(__METHOD__);
     $key = self::getCacheKey($article->getTitle(), $rev->getId());
     if ($regen === 'regen') {
         $versions = false;
         // skip cache
     } elseif ($rev->isCurrent()) {
         // Check cache entry against page_touched
         $versions = FlaggedRevs::getMemcValue($wgMemc->get($key), $article);
     } else {
         // Old revs won't always be invalidated with template/file changes.
         // Also, we don't care if page_touched changed due to a direct edit.
         $versions = FlaggedRevs::getMemcValue($wgMemc->get($key), $article, 'allowStale');
         if (is_array($versions)) {
             // entry exists
             // Sanity check that the cache is reasonably up to date
             list($templates, $files) = $versions;
             if (self::templatesStale($templates) || self::filesStale($files)) {
                 $versions = false;
                 // no good
             }
         }
     }
     if (!is_array($versions)) {
         // cache miss
         $pOut = false;
         if ($rev->isCurrent()) {
             $parserCache = ParserCache::singleton();
             # Try current version parser cache for this user...
             $pOut = $parserCache->get($article, $article->makeParserOptions($user));
             if ($pOut == false) {
                 # Try current version parser cache for the revision author...
                 $optsUser = $rev->getUser() ? User::newFromId($rev->getUser()) : 'canonical';
                 $pOut = $parserCache->get($article, $article->makeParserOptions($optsUser));
             }
         }
         // ParserOutput::mImageTimeKeys wasn't always there
         if ($pOut == false || !FlaggedRevs::parserOutputIsVersioned($pOut)) {
             $content = $rev->getContent(Revision::RAW);
             if (!$content) {
                 // Just for extra sanity
                 $pOut = new ParserOutput();
             } else {
                 $pOut = $content->getParserOutput($article->getTitle(), $rev->getId(), ParserOptions::newFromUser($user));
             }
         }
         # Get the template/file versions used...
         $versions = array($pOut->getTemplateIds(), $pOut->getFileSearchOptions());
         # Save to cache (check cache expiry for dynamic elements)...
         $data = FlaggedRevs::makeMemcObj($versions);
         $wgMemc->set($key, $data, $pOut->getCacheExpiry());
     }
     wfProfileOut(__METHOD__);
     return $versions;
 }
コード例 #11
0
 function parseText($text)
 {
     #still need to make it actually parse the input.
     global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
     $parserOptions = ParserOptions::newFromUser($wgUser);
     $parserOptions->setEditSection(false);
     $output = $wgParser->parse($text, $wgTitle, $parserOptions);
     $wgOut->setArticleBodyOnly(true);
     $wgOut->addHTML($output->mText);
 }
コード例 #12
0
 function getPages($query)
 {
     global $wgTitle, $wgParser, $wgUser;
     $fname = 'NukeDPLForm::getNewPages';
     $query = trim($query) . "\nmode=userformat\nlistseparators=,\\n\$\$\$%PAGE%\$\$\$,,\n";
     $opt = ParserOptions::newFromUser($wgUser);
     $out = $wgParser->parse("<dpl>{$query}</dpl>", $wgTitle, $opt, false, true);
     preg_match_all('|\\${3}(.+?)\\${3}|m', $out->getText(), $matches);
     return str_replace(array('&nbsp;', '&amp;'), array(' ', '&'), $matches[1]);
 }
コード例 #13
0
 /**
  * @dataProvider providePreSaveTransform
  * @covers Parser::preSaveTransform
  */
 public function testPreSaveTransform($text, $expected)
 {
     global $wgParser;
     $title = Title::newFromText(str_replace('::', '__', __METHOD__));
     $user = new User();
     $user->setName("127.0.0.1");
     $popts = ParserOptions::newFromUser($user);
     $text = $wgParser->preSaveTransform($text, $title, $user, $popts);
     $this->assertEquals($expected, $text);
 }
コード例 #14
0
 function execute($params)
 {
     global $wgRequest, $wgOut, $wgTitle, $wgUser;
     global $wgContLang, $wgProxyKey, $wgParser;
     $article = $wgRequest->getText('article', $params);
     $map = $wgRequest->getText('map', $params);
     $wgOut->disable();
     header("Cache-Control: no-cache, must-revalidate");
     header("Content-type: application/vnd.google-earth.kml+xml");
     header('Content-Disposition: attachment; filename="' . $article . '.kml"');
     $title = Title::newFromText($article);
     /* Wikia change begin - @author: Sebastian Marzjan */
     /* fogbugz BugID #18043 */
     if ($title instanceof Title) {
         /* Wikia change end */
         $revision = Revision::newFromTitle($title);
         /* Wikia change begin - @author: Sebastian Marzjan */
         /* fogbugz BugID #18043 */
         if (!$revision instanceof Revision) {
             $errorMessage = 'SpecialGoogleMapsKML.php ' . __LINE__ . ' - no revision for ' . $article . ' / ' . $title->getArticleID();
             Wikia::log(__METHOD__, false, $errorMessage);
             echo "No article revisions found by the name of {$article}";
             return false;
         }
         /* Wikia change end */
         $mapOptions = GoogleMaps::getMapSettings($title, array('icons' => 'http://maps.google.com/mapfiles/kml/pal4/{label}.png', 'icon' => 'icon57'));
         $exporter = new GoogleMapsKmlExporter($wgContLang, str_replace('{label}', $mapOptions['icon'], $mapOptions['icons']));
         $wgParser->mOptions = ParserOptions::newFromUser($wgUser);
         $wgParser->mOptions->setEditSection(false);
         $wgParser->mTitle = $wgTitle;
         $wgParser->clearState();
         $localParser = new Parser();
         $localParser->mTitle = $title;
         $localParser->mOptions = $wgParser->mOptions;
         if (preg_match_all("/<googlemap( .*?|)>(.*?)<\\/googlemap>/s", $revision->getText(), $matches)) {
             $exporter->addFileHeader();
             for ($i = 0; $i < count($matches[2]); $i++) {
                 $attrs = Sanitizer::decodeTagAttributes($matches[1][$i]);
                 $mapOptions['version'] = isset($attrs['version']) ? $attrs['version'] : "0";
                 $exporter->addHeader(isset($attrs['title']) ? $attrs['title'] : "Map #" . ($i + 1));
                 GoogleMaps::renderContent($matches[2][$i], $wgParser, $localParser, $exporter, $mapOptions);
                 $exporter->addTrailer();
             }
             $exporter->addFileTrailer();
             echo $exporter->render();
         } else {
             echo "No maps in {$article}!";
         }
     } else {
         echo "No article found by the name of {$article}";
     }
 }
コード例 #15
0
 function getPages($query)
 {
     global $wgParser;
     $user = $this->getUser();
     $title = $this->getTitle();
     $query = trim($query) . PHP_EOL . "format=,\$\$\$%PAGE%\$\$\$,,";
     //Enclose each title with $$$
     $parserOptions = ParserOptions::newFromUser($user);
     $parserOutput = $wgParser->parse('<dpl>' . $query . '</dpl>', $title, $parserOptions, false, true);
     preg_match_all('|\\$\\$\\$(.+)\\$\\$\\$|U', $parserOutput->getText(), $matches);
     //Extract the titles from the output
     return $matches[1];
     //Return an array of titles
 }
コード例 #16
0
ファイル: SpecialEvents.php プロジェクト: schwarer2006/wikia
 function execute($par)
 {
     global $wgOut, $wgRequest, $wgParser, $wgTitle, $wgUser;
     $year = isset($_GET['year']) ? $_REQUEST['year'] : null;
     $month = isset($_GET['month']) ? $_REQUEST['month'] : null;
     $day = isset($_GET['day']) ? $_REQUEST['day'] : null;
     if ($year == "") {
         $year = date("Y");
     }
     if ($month == "") {
         $month = date("m");
     }
     # Don't show the navigation if we're including the page
     if (!$this->mIncluding) {
         $this->setHeaders();
         $wgOut->addWikiText(wfMsg('events-header'));
     }
     if ($day == "") {
         $wgOut->AddWikiText('<calendar>upcoming=off</calendar>');
         $day = "__";
     }
     //build the SQL query
     $dbr =& wfGetDB(DB_SLAVE);
     $sPageTable = $dbr->tableName('page');
     $categorylinks = $dbr->tableName('categorylinks');
     $sSqlSelect = "SELECT page_namespace, page_title, page_id, clike1.cl_to catlike1 ";
     $sSqlSelectFrom = "FROM {$sPageTable} INNER JOIN {$categorylinks} AS c1 ON page_id = c1.cl_from AND c1.cl_to='Events' INNER JOIN {$categorylinks} " . "AS clike1 ON page_id = clike1.cl_from AND clike1.cl_to LIKE '{$year}/{$month}/{$day}'";
     $sSqlWhere = ' WHERE page_is_redirect = 0 ';
     $sSqlOrderby = ' ORDER BY catlike1 ASC';
     //DEBUG: output SQL query
     //$wgOut->addHTML('[' . $sSqlSelect . $sSqlSelectFrom . $sSqlWhere . $sSqlOrderby . ']');
     $res = $dbr->query($sSqlSelect . $sSqlSelectFrom . $sSqlWhere . $sSqlOrderby);
     $sk =& $wgUser->getSkin();
     while ($row = $dbr->fetchObject($res)) {
         $title = Title::makeTitle($row->page_namespace, $row->page_title);
         $wgOut->addHTML('<div class="eventsblock">');
         $title_text = $title->getSubpageText();
         $wgOut->addHTML('<b>' . $sk->makeKnownLinkObj($title, $title_text) . '</b><br>');
         $wl_article = new Article($title);
         $wl = $wl_article->getContent();
         $parserOptions = ParserOptions::newFromUser($wgUser);
         $parserOptions->setEditSection(false);
         $parserOptions->setTidy(true);
         $parserOutput = $wgParser->parse($wl, $title, $parserOptions);
         $previewHTML = $parserOutput->getText();
         $wgOut->addHTML($previewHTML);
         $wgOut->addHTML('</div>');
     }
 }
コード例 #17
0
ファイル: WidgetNeedHelp.php プロジェクト: Tjorriemorrie/app
function WidgetNeedHelp($id, $params)
{
    global $wgUser, $wgTitle, $wgParser;
    wfProfileIn(__METHOD__);
    if (isset($params['_widgetTag'])) {
        // work-around for WidgetTag
        $parser = new Parser();
    } else {
        $parser =& $wgParser;
    }
    $parser->mOptions = ParserOptions::newFromUser($wgUser);
    $ret = $parser->parse(wfMsg('Needhelp'), $wgTitle, $parser->mOptions)->getText();
    wfProfileOut(__METHOD__);
    return $ret;
}
コード例 #18
0
 /**
  * Constructor
  * Initialise private variables
  */
 function OutputPage()
 {
     $this->mHeaders = $this->mCookies = $this->mMetatags = $this->mKeywords = $this->mLinktags = array();
     $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext = $this->mRedirect = $this->mLastModified = $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy = $this->mOnloadHandler = '';
     $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
     $this->mSuppressQuickbar = $this->mPrintable = false;
     $this->mLanguageLinks = array();
     $this->mCategoryLinks = array();
     $this->mDoNothing = false;
     $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
     $this->mParserOptions = ParserOptions::newFromUser($temp = NULL);
     $this->mSquidMaxage = 0;
     $this->mScripts = '';
     $this->mETag = false;
 }
コード例 #19
0
ファイル: renderDump.php プロジェクト: eFFemeer/seizamcore
 /**
  * Callback function for each revision, turn into HTML and save
  * @param $rev Revision
  */
 public function handleRevision($rev)
 {
     global $wgParserConf;
     $title = $rev->getTitle();
     if (!$title) {
         $this->error("Got bogus revision with null title!");
         return;
     }
     $display = $title->getPrefixedText();
     $this->count++;
     $sanitized = rawurlencode($display);
     $filename = sprintf("%s/%s-%07d-%s.html", $this->outputDirectory, $this->prefix, $this->count, $sanitized);
     $this->output(sprintf("%s\n", $filename, $display));
     $user = new User();
     $parser = new $wgParserConf['class']();
     $options = ParserOptions::newFromUser($user);
     $output = $parser->parse($rev->getText(), $title, $options);
     file_put_contents($filename, "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " . "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" . "<head>\n" . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" . "<title>" . htmlspecialchars($display) . "</title>\n" . "</head>\n" . "<body>\n" . $output->getText() . "</body>\n" . "</html>");
 }
コード例 #20
0
ファイル: ParserCache.php プロジェクト: ruizrube/spdef
 function getKey(&$article, $popts)
 {
     global $wgRequest;
     if ($popts instanceof User) {
         // It used to be getKey( &$article, &$user )
         $popts = ParserOptions::newFromUser($popts);
     }
     $user = $popts->mUser;
     $printable = $popts->getIsPrintable() ? '!printable=1' : '';
     $hash = $user->getPageRenderingHash();
     if (!$article->mTitle->quickUserCan('edit')) {
         // section edit links are suppressed even if the user has them on
         $edit = '!edit=0';
     } else {
         $edit = '';
     }
     $pageid = $article->getID();
     $renderkey = (int) ($wgRequest->getVal('action') == 'render');
     $key = wfMemcKey('pcache', 'idhash', "{$pageid}-{$renderkey}!{$hash}{$edit}{$printable}");
     return $key;
 }
コード例 #21
0
 function execute($params)
 {
     global $wgRequest, $wgOut, $wgUser;
     global $wgContLang, $wgProxyKey, $wgParser;
     $article = $wgRequest->getText('article', $params);
     $map = $wgRequest->getText('map', $params);
     $wgOut->disable();
     header("Cache-Control: no-cache, must-revalidate");
     header("Content-type: application/vnd.google-earth.kml+xml");
     header('Content-Disposition: attachment; filename="' . $article . '.kml"');
     $title = Title::newFromText($article);
     if ($title) {
         $revision = Revision::newFromTitle($title);
         $mapOptions = GoogleMaps::getMapSettings($title, array('icons' => 'http://maps.google.com/mapfiles/kml/pal4/{label}.png', 'icon' => 'icon57'));
         $exporter = new GoogleMapsKmlExporter($wgContLang, str_replace('{label}', $mapOptions['icon'], $mapOptions['icons']));
         $popts = ParserOptions::newFromUser($wgUser);
         $popts->setEditSection(false);
         $wgParser->startExternalParse($this->getTitle(), $popts, OT_WIKI, true);
         $localParser = new Parser();
         $localParser->startExternalParse($this->getTitle(), $popts, OT_WIKI, true);
         if (preg_match_all("/<googlemap( .*?|)>(.*?)<\\/googlemap>/s", $revision->getText(), $matches)) {
             $exporter->addFileHeader();
             for ($i = 0; $i < count($matches[2]); $i++) {
                 $attrs = Sanitizer::decodeTagAttributes($matches[1][$i]);
                 $mapOptions['version'] = isset($attrs['version']) ? $attrs['version'] : "0";
                 $exporter->addHeader(isset($attrs['title']) ? $attrs['title'] : "Map #" . ($i + 1));
                 GoogleMaps::renderContent($matches[2][$i], $wgParser, $localParser, $exporter, $mapOptions);
                 $exporter->addTrailer();
             }
             $exporter->addFileTrailer();
             echo $exporter->render();
         } else {
             echo "No maps in {$article}!";
         }
     } else {
         echo "No article found by the name of {$article}";
     }
 }
コード例 #22
0
ファイル: WikiPage.php プロジェクト: nahoj/mediawiki_ynh
	/**
	 * @deprecated since 1.18
	 * @param $oldid int
	 * @return bool
	 */
	public function useParserCache( $oldid ) {
		wfDeprecated( __METHOD__, '1.18' );
		global $wgUser;
		return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
	}
コード例 #23
0
 /**
  * @todo document
  */
 function getPreviewText($isConflict, $isCssJsSubpage)
 {
     global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
     $previewhead = '<h2>' . htmlspecialchars(wfMsg('preview')) . "</h2>\n" . "<p class='previewnote'>" . htmlspecialchars(wfMsg('previewnote')) . "</p>\n";
     if ($isConflict) {
         $previewhead .= '<h2>' . htmlspecialchars(wfMsg('previewconflict')) . "</h2>\n";
     }
     $parserOptions = ParserOptions::newFromUser($wgUser);
     $parserOptions->setEditSection(false);
     # don't parse user css/js, show message about preview
     # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
     if ($isCssJsSubpage) {
         if (preg_match("/\\.css\$/", $wgTitle->getText())) {
             $previewtext = wfMsg('usercsspreview');
         } else {
             if (preg_match("/\\.js\$/", $wgTitle->getText())) {
                 $previewtext = wfMsg('userjspreview');
             }
         }
         $parserOutput = $wgParser->parse($previewtext, $wgTitle, $parserOptions);
         $wgOut->addHTML($parserOutput->mText);
         return $previewhead;
     } else {
         # if user want to see preview when he edit an article
         if ($wgUser->getOption('previewonfirst') and $this->textbox1 == '') {
             $this->textbox1 = $this->mArticle->getContent(true);
         }
         $toparse = $this->textbox1;
         # If we're adding a comment, we need to show the
         # summary as the headline
         if ($this->section == "new" && $this->summary != "") {
             $toparse = "== {$this->summary} ==\n\n" . $toparse;
         }
         if ($this->mMetaData != "") {
             $toparse .= "\n" . $this->mMetaData;
         }
         $parserOutput = $wgParser->parse($this->mArticle->preSaveTransform($toparse) . "\n\n", $wgTitle, $parserOptions);
         $previewHTML = $parserOutput->mText;
         $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
         $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
         return $previewhead . $previewHTML;
     }
 }
コード例 #24
0
ファイル: parserBugTester.php プロジェクト: Tjorriemorrie/app
}
function efSampleRender($text, $args, $parser)
{
    $attrs = "";
    foreach ($args as $name => $value) {
        $attrs .= " {$name}=\"" . htmlspecialchars($value) . '"';
    }
    return "<stest{$attrs}>" . $parser->recursiveTagParse($text) . "</stest>";
}
///// TEST DATA /////
$inputOutputPairs = array('<stest facebook-logo="true" a:b="c" z_-.Z="val" A:B-c.1_2:3="val" _1="2">These attribs should be passed through</stest>' => '<stest facebook-logo="true" a:b="c" z_-.z="val" a:b-c.1_2:3="val" _1="2">These attribs should be passed through</stest>', '<stest -a="no" .b="no" 0c="no" 9d="no" don\'t="no" a=b="c" a%="no" hi"="no" a$="no" a@="no" ^a="no" a*="no" a(b)="no">Denied</stest>' => '<stest>Denied</stest>', '<stest profile-id="107399782623294"></stest>' => '<stest profile-id="107399782623294"></stest>', '<stest profile-id="107399782623294"/>' => '<stest profile-id="107399782623294"></stest>', '<stest name="Wikia"></stest>' => '<stest name="Wikia"></stest>');
///// TEST DATA /////
print "Testing parser tag examples...\n";
print count($inputOutputPairs) . " test cases.\n";
global $wgParser, $wgUser;
$parserOptions = ParserOptions::newFromUser($wgUser);
$title = Title::makeTitle(NS_MAIN, "Main_Page");
$numSuccesses = 0;
$numFailures = 0;
foreach ($inputOutputPairs as $input => $expectedOutput) {
    $actualOutput = $wgParser->parse($input, $title, $parserOptions)->getText();
    // The parser wraps the tags in paragraphs.
    $expectedOutput = "<p>{$expectedOutput}\n</p>";
    if ($actualOutput != $expectedOutput) {
        print "\n------------------------------------------\n";
        print "                 MISMATCH!\n";
        print "------------------------------------------\n";
        print "INPUT:    {$input}\n";
        print "EXPECTED: {$expectedOutput}\n";
        print "ACTUAL:   {$actualOutput}\n";
        print "------------------------------------------\n";
コード例 #25
0
 function parseText($text, $title)
 {
     #still need to make it actually parse the input.
     global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
     $parserOptions = ParserOptions::newFromUser($wgUser);
     $parserOptions->setEditSection(false);
     $rtitle = Title::newFromText($title);
     $pre_parsed = $wgParser->preSaveTransform($text, $rtitle, $wgUser, $parserOptions, true);
     $output = $wgParser->parse($pre_parsed, $rtitle, $parserOptions);
     $wgOut->setArticleBodyOnly(true);
     # Here we filter the output. If there's a section header in the beginning,
     # we'll have an empty wikiwyg_section_0 div, and we do not want it.
     # So we strip the empty span out.
     $goodHTML = str_replace("<span class=\"wikiwyg_section_0\">\n<p><!-- before block -->\n</p><p><br />\n</p><p><!-- After block -->\n</p>\n</span><iframe class=\"wikiwyg_iframe\" id=\"wikiwyg_iframe_0\" height='0' width='0' frameborder='0'></iframe>", "", $output->mText);
     /* manually strip away TOC */
     $goodHTML = preg_replace('/<table id="toc".*<\\/table>*.<script type="text\\/javascript"> if \\(window\\.showTocToggle\\).*<\\/script>/is', "", $goodHTML);
     $wgOut->addHTML($goodHTML);
 }
コード例 #26
0
 /**
  * Check if any of categories mentioned in $text gives $wgUser read access to $title
  */
 protected static function checkForReadableCategories($text, $title)
 {
     global $wgUser, $wgParser;
     $options = ParserOptions::newFromUser($wgUser);
     // clearState = true when not cleared yet
     $text = $wgParser->preSaveTransform($text, $title, $wgUser, $options, !$wgParser->mStripState);
     $parserOutput = $wgParser->parse($text, $title, $options);
     $catIds = array();
     foreach ($parserOutput->getCategoryLinks() as $cat) {
         // FIXME Resolve multiple title IDs at once
         $cat = Title::makeTitle(NS_CATEGORY, $cat);
         if ($id = $cat->getArticleId()) {
             $catIds[$id] = true;
         }
     }
     $catIds = array_keys($catIds + IACLStorage::get('Util')->getParentCategoryIDs(array_keys($catIds)));
     $r = IACLDefinition::userCan($wgUser->getId(), IACL::PE_CATEGORY, $catIds, IACL::ACTION_READ);
     return $r == 1;
 }
コード例 #27
0
 /**
  * @access private
  */
 function savePreferences()
 {
     global $wgUser, $wgOut, $wgParser;
     global $wgEnableUserEmail, $wgEnableEmail;
     global $wgEmailAuthentication, $wgMinimalPasswordLength;
     global $wgAuth;
     if ('' != $this->mNewpass && $wgAuth->allowPasswordChange()) {
         if ($this->mNewpass != $this->mRetypePass) {
             $this->mainPrefsForm('error', wfMsg('badretype'));
             return;
         }
         if (strlen($this->mNewpass) < $wgMinimalPasswordLength) {
             $this->mainPrefsForm('error', wfMsg('passwordtooshort', $wgMinimalPasswordLength));
             return;
         }
         if (!$wgUser->checkPassword($this->mOldpass)) {
             $this->mainPrefsForm('error', wfMsg('wrongpassword'));
             return;
         }
         if (!$wgAuth->setPassword($wgUser, $this->mNewpass)) {
             $this->mainPrefsForm('error', wfMsg('externaldberror'));
             return;
         }
         $wgUser->setPassword($this->mNewpass);
         $this->mNewpass = $this->mOldpass = $this->mRetypePass = '';
     }
     $wgUser->setRealName($this->mRealName);
     if ($wgUser->getOption('language') !== $this->mUserLanguage) {
         $needRedirect = true;
     } else {
         $needRedirect = false;
     }
     # Validate the signature and clean it up as needed
     if ($this->mToggles['fancysig']) {
         if (Parser::validateSig($this->mNick) !== false) {
             $this->mNick = $wgParser->cleanSig($this->mNick);
         } else {
             $this->mainPrefsForm('error', wfMsg('badsig'));
         }
     } else {
         // When no fancy sig used, make sure ~{3,5} get removed.
         $this->mNick = $wgParser->cleanSigInSig($this->mNick);
     }
     $wgUser->setOption('language', $this->mUserLanguage);
     $wgUser->setOption('variant', $this->mUserVariant);
     $wgUser->setOption('nickname', $this->mNick);
     $wgUser->setOption('quickbar', $this->mQuickbar);
     $wgUser->setOption('skin', $this->mSkin);
     global $wgUseTeX;
     if ($wgUseTeX) {
         $wgUser->setOption('math', $this->mMath);
     }
     $wgUser->setOption('date', $this->validateDate($this->mDate, 0, 20));
     // WERELATE removed
     //		$wgUser->setOption( 'searchlimit', $this->validateIntOrNull( $this->mSearch ) );
     //		$wgUser->setOption( 'contextlines', $this->validateIntOrNull( $this->mSearchLines ) );
     //		$wgUser->setOption( 'contextchars', $this->validateIntOrNull( $this->mSearchChars ) );
     $wgUser->setOption('rclimit', $this->validateIntOrNull($this->mRecent));
     $wgUser->setOption('wllimit', $this->validateIntOrNull($this->mWatchlistEdits, 0, 1000));
     $wgUser->setOption('rows', $this->validateInt($this->mRows, 4, 1000));
     $wgUser->setOption('cols', $this->validateInt($this->mCols, 4, 1000));
     $wgUser->setOption('stubthreshold', $this->validateIntOrNull($this->mStubs));
     $wgUser->setOption('timecorrection', $this->validateTimeZone($this->mHourDiff, -12, 14));
     $wgUser->setOption('imagesize', $this->mImageSize);
     $wgUser->setOption('thumbsize', $this->mThumbSize);
     $wgUser->setOption('underline', $this->validateInt($this->mUnderline, 0, 2));
     $wgUser->setOption('watchlistdays', $this->validateFloat($this->mWatchlistDays, 0, 7));
     # Set search namespace options
     // WERELATE removed
     //		foreach( $this->mSearchNs as $i => $value ) {
     //			$wgUser->setOption( "searchNs{$i}", $value );
     //		}
     if ($wgEnableEmail && $wgEnableUserEmail) {
         $wgUser->setOption('disablemail', $this->mEmailFlag);
     }
     # Set user toggles
     foreach ($this->mToggles as $tname => $tvalue) {
         $wgUser->setOption($tname, $tvalue);
     }
     if (!$wgAuth->updateExternalDB($wgUser)) {
         $this->mainPrefsForm(wfMsg('externaldberror'));
         return;
     }
     $wgUser->setCookies();
     $wgUser->saveSettings();
     $error = false;
     if ($wgEnableEmail) {
         $newadr = $this->mUserEmail;
         $oldadr = $wgUser->getEmail();
         if ($newadr != '' && $newadr != $oldadr) {
             # the user has supplied a new email address on the login page
             if ($wgUser->isValidEmailAddr($newadr)) {
                 $wgUser->mEmail = $newadr;
                 # new behaviour: set this new emailaddr from login-page into user database record
                 $wgUser->mEmailAuthenticated = null;
                 # but flag as "dirty" = unauthenticated
                 $wgUser->saveSettings();
                 if ($wgEmailAuthentication) {
                     # Mail a temporary password to the dirty address.
                     # User can come back through the confirmation URL to re-enable email.
                     $result = $wgUser->sendConfirmationMail();
                     if (WikiError::isError($result)) {
                         $error = wfMsg('mailerror', htmlspecialchars($result->getMessage()));
                     } else {
                         $error = wfMsg('eauthentsent', $wgUser->getName());
                     }
                 }
             } else {
                 $error = wfMsg('invalidemailaddress');
             }
         } else {
             $wgUser->setEmail($this->mUserEmail);
             $wgUser->setCookies();
             $wgUser->saveSettings();
         }
     }
     if ($needRedirect && $error === false) {
         $title =& Title::makeTitle(NS_SPECIAL, "Preferences");
         $wgOut->redirect($title->getFullURL('success'));
         return;
     }
     $wgOut->setParserOptions(ParserOptions::newFromUser($wgUser));
     $po = ParserOptions::newFromUser($wgUser);
     $this->mainPrefsForm($error === false ? 'success' : 'error', $error);
 }
コード例 #28
0
ファイル: Article.php プロジェクト: GodelDesign/Godel
 /**
  * This function is called right before saving the wikitext,
  * so we can do things like signatures and links-in-context.
  *
  * @param $text String article contents
  * @return string article contents with altered wikitext markup (signatures
  * 	converted, {{subst:}}, templates, etc.)
  */
 public function preSaveTransform($text)
 {
     global $wgParser, $wgUser;
     return $wgParser->preSaveTransform($text, $this->mTitle, $wgUser, ParserOptions::newFromUser($wgUser));
 }
コード例 #29
0
 /**
  * Get parser options suitable for rendering and caching the article
  *
  * @param IContextSource|User|string $context One of the following:
  *        - IContextSource: Use the User and the Language of the provided
  *                                            context
  *        - User: Use the provided User object and $wgLang for the language,
  *                                            so use an IContextSource object if possible.
  *        - 'canonical': Canonical options (anonymous user with default
  *                                            preferences and content language).
  *
  * @throws MWException
  * @return ParserOptions
  */
 public function makeParserOptions($context)
 {
     global $wgContLang, $wgEnableParserLimitReporting;
     if ($context instanceof IContextSource) {
         $options = ParserOptions::newFromContext($context);
     } elseif ($context instanceof User) {
         // settings per user (even anons)
         $options = ParserOptions::newFromUser($context);
     } elseif ($context === 'canonical') {
         // canonical settings
         $options = ParserOptions::newFromUserAndLang(new User(), $wgContLang);
     } else {
         throw new MWException("Bad context for parser options: {$context}");
     }
     $options->enableLimitReport($wgEnableParserLimitReporting);
     // show inclusion/loop reports
     $options->setTidy(true);
     // fix bad HTML
     return $options;
 }
コード例 #30
0
ファイル: ParserCache.php プロジェクト: D66Ha/mediawiki
 /**
  * Generates a key for caching the given article considering
  * the given parser options.
  *
  * @note Which parser options influence the cache key
  * is controlled via ParserOutput::recordOption() or
  * ParserOptions::addExtraKey().
  *
  * @note Used by Article to provide a unique id for the PoolCounter.
  * It would be preferable to have this code in get()
  * instead of having Article looking in our internals.
  *
  * @todo Document parameter $useOutdated
  *
  * @param WikiPage $article
  * @param ParserOptions $popts
  * @param bool $useOutdated (default true)
  * @return bool|mixed|string
  */
 public function getKey($article, $popts, $useOutdated = true)
 {
     global $wgCacheEpoch;
     if ($popts instanceof User) {
         wfWarn("Use of outdated prototype ParserCache::getKey( &\$article, &\$user )\n");
         $popts = ParserOptions::newFromUser($popts);
     }
     // Determine the options which affect this article
     $optionsKey = $this->mMemc->get($this->getOptionsKey($article));
     if ($optionsKey instanceof CacheTime) {
         if (!$useOutdated && $optionsKey->expired($article->getTouched())) {
             wfIncrStats("pcache.miss.expired");
             $cacheTime = $optionsKey->getCacheTime();
             wfDebug("Parser options key expired, touched " . $article->getTouched() . ", epoch {$wgCacheEpoch}, cached {$cacheTime}\n");
             return false;
         } elseif ($optionsKey->isDifferentRevision($article->getLatest())) {
             wfIncrStats("pcache.miss.revid");
             $revId = $article->getLatest();
             $cachedRevId = $optionsKey->getCacheRevisionId();
             wfDebug("ParserOutput key is for an old revision, latest {$revId}, cached {$cachedRevId}\n");
             return false;
         }
         // $optionsKey->mUsedOptions is set by save() by calling ParserOutput::getUsedOptions()
         $usedOptions = $optionsKey->mUsedOptions;
         wfDebug("Parser cache options found.\n");
     } else {
         if (!$useOutdated) {
             return false;
         }
         $usedOptions = ParserOptions::legacyOptions();
     }
     return $this->getParserOutputKey($article, $popts->optionsHash($usedOptions, $article->getTitle()));
 }