/** * Hook: ParserBeforeStrip * @param $parser Parser * @param $text * @param $state * @return bool */ public static function renderTagPage($parser, &$text, $state) { $title = $parser->getTitle(); if (strpos($text, '<translate>') !== false) { try { $parse = TranslatablePage::newFromText($parser->getTitle(), $text)->getParse(); $text = $parse->getTranslationPageText(null); } catch (TPException $e) { // Show ugly preview without processed <translate> tags } } // Set display title $page = TranslatablePage::isTranslationPage($title); if (!$page) { return true; } list(, $code) = TranslateUtils::figureMessage($title->getText()); $name = $page->getPageDisplayTitle($code); if ($name) { // BC for MW < 1.19 if (is_callable(array($parser, 'recursivePreprocess'))) { $name = $parser->recursivePreprocess($name); } else { $newParser = new Parser(); $name = $newParser->preprocess($name, $parser->getTitle(), $parser->getOptions()); } $name = $parser->recursivePreprocess($name); $parser->getOutput()->setDisplayTitle($name); } return true; }
/** * Helper method for processing a template transclusion by simulating template * expensions using a callback to avoid having to integrate DB read/write * process in order to access a Template * * @note Part of the routine has been taken from MW's ExtraParserTest * * @return text */ private function runTemplateTransclusion(Title $title, $text, $return) { $parser = new \Parser(); $options = new \ParserOptions(); $options->setTemplateCallback(function ($title, $parser = false) use($return) { $text = $return; $deps = array(); return array('text' => $text, 'finalTitle' => $title, 'deps' => $deps); }); return $parser->preprocess($text, $title, $options); }
function VideoGalleryPopulate($input, $args, $parser) { $parser->disableCache(); $category = isset($args['category']) ? $args['category'] : ''; $limit = isset($args['limit']) ? intval($args['limit']) : 10; if (empty($category)) { return ''; } // Use Parser::recursivePreprocess() if available instead of creating another Parser instance if (is_callable(array($parser, 'recursivePreprocess'))) { $category = $parser->recursivePreprocess($category); } else { $newParser = new Parser(); $category = $newParser->preprocess($category, $parser->getTitle(), $parser->getOptions()); } $category_title = Title::newFromText($category); if (!$category_title instanceof Title) { return ''; } // @todo FIXME: not overly i18n-friendly here... $category_title_secondary = Title::newFromText($category . ' Videos'); if (!$category_title_secondary instanceof Title) { return ''; } $params['ORDER BY'] = 'page_id'; if ($limit) { $params['LIMIT'] = $limit; } $dbr = wfGetDB(DB_SLAVE); $res = $dbr->select(array('page', 'categorylinks'), 'page_title', array('cl_to' => array($category_title->getDBkey(), $category_title_secondary->getDBkey()), 'page_namespace' => NS_VIDEO), __METHOD__, $params, array('categorylinks' => array('INNER JOIN', 'cl_from = page_id'))); $gallery = new VideoGallery(); $gallery->setParsing(true); $gallery->setShowFilename(true); foreach ($res as $row) { $video = Video::newFromName($row->page_title, RequestContext::getMain()); $gallery->add($video); } return $gallery->toHtml(); }
public function hookNcl($category, $argv, $parser) { # get any user-specified parameters, and save them in $this->settings $this->settings = array_merge($this->settings, $argv); # replace variables in $category by calling the parser on it $localParser = new Parser(); $category = $localParser->preprocess($category, $parser->mTitle, $parser->mOptions, false); # make a title object for the requested category $title = Title::newFromText($category); if (!$title) { return '<p>Failed to create title!</p>'; } # get the database handle, and get all the subcategory links for the given category # modif serge 01/08 =& to = line 188 $dbr = wfGetDB(DB_SLAVE); $catData = $this->searchCategory($dbr, $title, 0); # generate the category listing $output = "<div class='ncl-nicecategorylist'>" . $this->outputCategory($catData) . "</div>"; # suppress TOC $output .= "__NOTOC__\n"; # add stylesheet and do not cache global $wgOut, $wgScriptPath, $egNiceCategoryListInstallDir; $wgOut->addExtensionStyle("{$wgScriptPath}/extensions/{$egNiceCategoryListInstallDir}/NiceCategoryList.css"); # code taken from [[mw:Extension_talk:NiceCategoryList2#Stale_Content_.2F_Extension_Doesn.27t_refresh]] global $egNiceCategoryListDisableCache; if ($egNiceCategoryListDisableCache) { global $wgVersion; # modif serge 01/08 =& to = line 205 $dbr = wfGetDB(DB_SLAVE); # Do not cache this wiki page. # for details see http://public.kitware.com/Wiki/User:Barre/MediaWiki/Extensions global $wgTitle, $wgDBprefix; $ts = mktime(); $now = gmdate("YmdHis", $ts + 120); $ns = $wgTitle->getNamespace(); $ti = $dbr->addQuotes($wgTitle->getDBkey()); $version = preg_replace("/^([1-9]).([1-9]).*/", "\\1\\2", $wgVersion); $sql = "UPDATE {$wgDBprefix}" . "page SET page_touched='{$now}' WHERE page_namespace={$ns} AND page_title={$ti}"; $dbr->query($sql, __METHOD__); } # convert the listing wikitext into HTML and return it $localParser = new Parser(); $output = $localParser->parse($output, $parser->mTitle, $parser->mOptions); return $output->getText(); }
function MwRdfInterwiki($article) { global $DCTERM, $DCMES, $DCMITYPE, $RDFS_seeAlso, $wgContLang; $model = ModelFactory::getDefaultModel(); $nt = $article->getTitle(); $tr = MwRdfTitleResource($nt); $text = $article->getContent(true); $parser = new Parser(); $text = $parser->preprocess($text, $article->mTitle, new ParserOptions()); # XXX: this sucks # Ignore <nowiki> blocks $text = preg_replace("|(<nowiki>.*</nowiki>)|", "", $text); # Find prefixed links preg_match_all("/\\[\\[([^|\\]]+:[^|\\]]+)(\\|.*)?\\]\\]/", $text, $matches); # XXX: this fails for Category: namespace; why? if (isset($matches)) { foreach ($matches[1] as $linktext) { $iwlink = Title::newFromText($linktext); if (isset($iwlink)) { $pfx = $iwlink->getInterwiki(); if (strlen($pfx) > 0) { $iwr = MwRdfTitleResource($iwlink); # XXX: Wikitravel uses some 4+ prefixes for sister site links if ($wgContLang->getLanguageName($pfx) && strlen($pfx) < 4) { $model->add(new Statement($tr, $DCTERM['hasVersion'], $iwr)); $model->add(new Statement($iwr, $DCMES['language'], MwRdfLanguage($pfx))); } else { # XXX: Express the "sister site" relationship better $model->add(new Statement($tr, $RDFS_seeAlso, $iwr)); } } } } } return $model; }
/** * @covers Parser::preprocess */ public function testPreprocess() { $title = Title::newFromText(__FUNCTION__); $outputText = $this->parser->preprocess("Test\n{{Foo}}\n{{Bar}}", $title, $this->options); $this->assertEquals("Test\nContent of ''Template:Foo''\nContent of ''Template:Bar''", $outputText); }
/** * This function was originally in the UserStats directory, in the file * CreatedOpinionsCount.php. * This function here updates the stats_opinions_created column in the * user_stats table every time the user creates a new blog post. * * This is hooked into two separate hooks (todo: find out why), ArticleSave * and ArticleSaveComplete. Their arguments are mostly the same and both * have $article as the first argument. * * @param $article Object: Article object representing the page that was/is * (being) saved * @return Boolean: true */ public static function updateCreatedOpinionsCount(&$article) { global $wgOut, $wgUser; $aid = $article->getTitle()->getArticleID(); // Shortcut, in order not to perform stupid queries (cl_from = 0...) if ($aid == 0) { return true; } $dbr = wfGetDB(DB_SLAVE); $res = $dbr->select('categorylinks', 'cl_to', array('cl_from' => $aid), __METHOD__); foreach ($res as $row) { $ctg = Title::makeTitle(NS_CATEGORY, $row->cl_to); $ctgname = $ctg->getText(); $blogCat = wfMsgForContent('blog-category'); $userBlogCat = wfMsgForContent('blog-by-user-category', $blogCat); if (strpos($ctgname, $userBlogCat) !== false) { $user_name = trim(str_replace($userBlogCat, '', $ctgname)); $u = User::idFromName($user_name); if ($u) { $stats = new UserStatsTrack($u, $user_name); // Copied from UserStatsTrack::updateCreatedOpinionsCount() // Throughout this code, we could use $u and $user_name // instead of $stats->user_id and $stats->user_name but // there's no point in doing that because we have to call // clearCache() in any case if (!$wgUser->isAnon() && $stats->user_id) { $ctg = $userBlogCat . ' ' . $stats->user_name; $parser = new Parser(); $ctgTitle = Title::newFromText($parser->preprocess(trim($ctg), $wgOut->getTitle(), $wgOut->parserOptions())); $ctgTitle = $ctgTitle->getDBkey(); $dbw = wfGetDB(DB_MASTER); $opinions = $dbw->select(array('page', 'categorylinks'), array('COUNT(*) AS CreatedOpinions'), array('cl_to' => $ctgTitle, 'page_namespace' => NS_BLOG), __METHOD__, array(), array('categorylinks' => array('INNER JOIN', 'page_id = cl_from'))); // Please die in a fire, PHP. // selectField() would be ideal above but it returns // insane results (over 300 when the real count is // barely 10) so we have to f**k around with a // foreach() loop that we don't even need in theory // just because PHP is...PHP. $opinionsCreated = 0; foreach ($opinions as $opinion) { $opinionsCreated = $opinion->CreatedOpinions; } $res = $dbw->update('user_stats', array('stats_opinions_created' => $opinionsCreated), array('stats_user_id' => $stats->user_id), __METHOD__); $stats->clearCache(); } } } } return true; }
/** * Ugly home made probably awfully slow looping parser * that parses {{PLURAL}} instances from message and * returns array of invokations having array of forms. * @since 2012-09-19 * @param string $translation * @return array[array] */ public static function getPluralForms($translation) { // Stores the forms from plural invocations $plurals = array(); $cb = function ($parser, $frame, $args) use(&$plurals) { $forms = array(); foreach ($args as $index => $form) { // The first arg is the number, we skip it if ($index !== 0) { // Collect the raw text $forms[] = $frame->expand($form, PPFrame::RECOVER_ORIG); // Expand the text to process embedded plurals $frame->expand($form); } } $plurals[] = $forms; return ''; }; // Setup parser $parser = new Parser(); // Load the default magic words etc now. $parser->firstCallInit(); // So that they don't overrider our own callback $parser->setFunctionHook('plural', $cb, Parser::SFH_NO_HASH | Parser::SFH_OBJECT_ARGS); // Setup things needed for preprocess $title = null; $options = new ParserOptions(new User(), Language::factory('en')); $parser->preprocess($translation, $title, $options); return $plurals; }