Inheritance: extends CI_Controller
function sbParserInit(Parser $parser)
{
    // Register <scratchblocks> tag
    $parser->setHook('scratchblocks', 'sbRenderTag');
    $parser->setHook('sb', 'sbRenderInlineTag');
    return true;
}
 /**
  * @dataProvider mwParserWrapperDataProvider
  *
  * @param $wikitext
  * @param $params
  */
 public function testWrapper($wikitext, $params, $newline)
 {
     $frame = $this->parser->getPreprocessor()->newCustomFrame($params);
     $wrapper = new \Wikia\PortableInfobox\Parser\MediaWikiParserService($this->parser, $frame);
     $output = $wrapper->parseRecursive($wikitext);
     $this->assertEquals($this->parse($wikitext, $params, $newline), $output);
 }
Exemple #3
0
 /**
  * Sets node attributes based on the parser's current position.
  */
 public function set_from_parser(Parser $parser)
 {
     $this->parser = $parser;
     $this->line_number = $parser->line_number();
     $this->indent_level = $parser->indent_level();
     $this->content = $parser->content();
 }
 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;
 }
Exemple #5
0
 public function testFile()
 {
     $content = file_get_contents(dirname(__FILE__) . '/data/Markdown.md');
     $contentHtml = file_get_contents(dirname(__FILE__) . '/data/Markdown.html');
     $parsedActual = $this->object->transform($content);
     $this->assertSame($contentHtml, $parsedActual);
 }
 /**
  * Parser hook handler for {{#articletype}}
  *
  * @param Parser $parser : Parser instance available to render
  *  wikitext into html, or parser methods.
  *
  * @return string: HTML to insert in the page.
  */
 public static function renderGallery($input, array $args, Parser $parser, PPFrame $frame)
 {
     $parser->getOutput()->addModules('ext.promoter.gallery');
     $pageName = $parser->getTitle()->getText();
     try {
         $renderedAds = array();
         $adChooser = new AdChooser($pageName, !$parser->getUser()->isLoggedIn());
         $ads = $adChooser->getAds();
         foreach ($ads as $ad) {
             $renderedAds[] = Ad::fromName($ad['name'])->renderHtml();
         }
     } catch (AdCampaignExistenceException $e) {
         wfDebugLog('Promoter', $e->getMessage());
         //@todo i18n
         return '<span class="error">No campaign for this page</span>';
     } catch (MWException $e) {
         wfDebugLog('Promoter', $e->getMessage());
         return '<span class="error text-danger">An error occurred [' . $e->getMessage() . ']</span>';
     }
     $html = '<div class="promotion-gallery hidden hidden-print">' . '<h5 class="sr-only">זוהי גלריה המקדמת ערכים שונים באתר.</h5>' . '<div class="gallery-controls">' . '<span class="sr-only">בכל רגע מוצגות 3 ידיעות בגלריה. ניתן להציג ידיעה נוספת או לחזור לאחור באמצעות הכפתורים הבאים, או באמצעות מקשי החיצים כאשר הפוקוס הוא על הגלריה</span>' . '<a href="#" class="owl-prev"><span class="fa fa-chevron-right fa-lg" title="הקודם"></span><span class="sr-only">הצגת הידיעה הקודמת</span></a>' . '<a href="#" class="owl-next"><span class="fa fa-chevron-left fa-lg" title="הבא"></span><span class="sr-only">הצגת הידיעה הבאה</span></a>' . '</div>';
     if ($args['title']) {
         $html .= '<div class="header">' . $args['title'] . '</div>';
     }
     $html .= '<div class="owl-carousel clearfix" tabindex="0">' . implode('', $renderedAds) . '</div>' . '</div>';
     return $html;
 }
 function setUp()
 {
     parent::setUp();
     $parser = new Parser();
     $options = new ParserOptions();
     $options->setTemplateCallback(array($this, 'templateCallback'));
     $parser->startExternalParse(Title::newMainPage(), $options, Parser::OT_HTML, true);
     try {
         $engine = new Scribunto_LuaSandboxEngine(array('parser' => $parser) + $this->sandboxOpts);
         $engine->setTitle($parser->getTitle());
         $engine->getInterpreter();
         $this->engines['LuaSandbox'] = $engine;
     } catch (Scribunto_LuaInterpreterNotFoundError $e) {
         $this->markTestSkipped("LuaSandbox interpreter not available");
         return;
     }
     try {
         $engine = new Scribunto_LuaStandaloneEngine(array('parser' => $parser) + $this->standaloneOpts);
         $engine->setTitle($parser->getTitle());
         $engine->getInterpreter();
         $this->engines['LuaStandalone'] = $engine;
     } catch (Scribunto_LuaInterpreterNotFoundError $e) {
         $this->markTestSkipped("LuaStandalone interpreter not available");
         return;
     }
 }
Exemple #8
0
 /**
  * Get the package information
  *
  * @return Info
  */
 public function getInfo()
 {
     exec("rpm -qi {$this->packageName}", $rawInfo);
     $rawInfo = implode("\n", $rawInfo);
     $parser = new Parser();
     return $parser->parse($rawInfo);
 }
Exemple #9
0
 private function run($name, $options, $contents)
 {
     require_once CORE_DIR . 'parser.php';
     $parser = new Parser();
     $data = html_entity_decode($parser->parse($contents, $options));
     return file_put_contents(strtolower($name) . '.php', $data) ? true : false;
 }
 protected function doTestPrettyPrintMethod($method, $name, $code, $dump)
 {
     $parser = new Parser(new Lexer\Emulative());
     $prettyPrinter = new PrettyPrinter\Standard();
     $stmts = $parser->parse($code);
     $this->assertEquals($this->canonicalize($dump), $this->canonicalize($prettyPrinter->{$method}($stmts)), $name);
 }
Exemple #11
0
 /**
  * Validate a domain with a Tld.
  *
  * @access public
  * @static
  * @param string $domain
  * @return boolean
  */
 public static function domainWithTld($domain)
 {
     $domainParser = new Parser($domain);
     $tld = $domainParser->getTld();
     $domainWithoutTld = $domainParser->getDomainWithoutTld();
     return self::domainWithoutTld($domainWithoutTld) && $tld && filter_var('http://' . $domain, FILTER_VALIDATE_URL);
 }
Exemple #12
0
 public static function renderCollection($input, array $args, Parser $parser, PPFrame $frame)
 {
     $string_array = array();
     $parsed_input = $parser->recursiveTagParse($input, $frame);
     if (Collection::startsWith($parsed_input, "Coll") === true) {
         $results = Collection::getResults($parsed_input);
         $string_array[] = '{| class="wikitable"';
         $string_array[] = "! ";
         foreach ($results['langs'] as $lang) {
             $string_array[] = "!" . $lang;
         }
         $string_array[] = "|-";
         foreach (array_keys($results['data']) as $pagename) {
             $string_array[] = "|[[" . $pagename . " |Edit]]";
             foreach ($results['langs'] as $lang) {
                 if (isset($results['data'][$pagename][$lang])) {
                     $string_array[] = "|" . implode("<br/>", $results['data'][$pagename][$lang]);
                 } else {
                     $string_array[] = "|";
                 }
             }
             $string_array[] = "|-";
         }
         $string_array[] = "|}";
         return $parser->recursiveTagParse(implode("\n\n", $string_array), $frame);
     } else {
         return $parser->recursiveTagParse("No results", $frame);
     }
 }
 /**
  * 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;
 }
Exemple #14
0
 /**
  * @covers Geissler\Converter\Standard\RIS\Creator::create
  * @covers Geissler\Converter\Standard\RIS\Creator::getPerson
  * @covers Geissler\Converter\Standard\RIS\Creator::getDate
  * @covers Geissler\Converter\Standard\RIS\Creator::getType
  * @covers Geissler\Converter\Standard\RIS\Creator::retrieve
  * @dataProvider dataProviderCreate
  */
 public function testCreate($input, $output)
 {
     $parser = new Parser();
     $this->assertTrue($parser->parse($input));
     $this->assertTrue($this->object->create($parser->retrieve()));
     $this->assertEquals($output, $this->object->retrieve());
 }
Exemple #15
0
 public function build()
 {
     $article = $this->Agent->getArticle();
     $text = $article->getContent(true);
     # Strip comments and <nowiki>
     $text = preg_replace("/<!--.*?-->/s", "", $text);
     $text = preg_replace("@<nowiki>.*?</nowiki>@s", "", $text);
     # change template usage to substitution; note that this is WRONG
     #$tchars = Title::legalChars();
     #$text = preg_replace("/(?<!{){{([$tchars]+)(\|.*?)?}}(?!})/", "{{subst:$1$2}}", $text);
     $parser = new Parser();
     # so the magic variables work out right
     $parser->mOptions = new ParserOptions();
     $parser->mTitle = $this->Agent->getTitle();
     $parser->mOutputType = OT_WIKI;
     $parser->initialiseVariables();
     $parser->clearState();
     $text = $parser->replaceVariables($text);
     preg_match_all("@<rdf>(.*?)</rdf>@s", $text, $matches, PREG_PATTERN_ORDER);
     $content = $matches[1];
     $rdf = implode(' ', array_values($content));
     $model = MwRdf::Model();
     if (strlen($rdf) > 0) {
         $parser->mOutputType = OT_HTML;
         $rdf = $parser->replaceVariables($rdf);
         $turtle_parser = MwRdf::Parser('turtle');
         $base_uri = $this->Agent->getTitle()->getFullUrl();
         $prelude = MwRdf::getNamespacePrelude();
         $model->loadStatementsFromString($turtle_parser, $prelude . $rdf);
     }
     return $model;
 }
 /**
  * Outputs the internal image wrapped in a link
  * @param Parser $parser Instance of running Parser.
  * @param String $image Name of image to display.
  * @param String $url External URL to which to link
  * @param String $alt Alternate text for image and link (optional)
  * @return String A parser strip flag which will be later replaced with raw html.
  */
 function imageLink($parser, $image = null, $url = null, $alt = '')
 {
     # Short-circuit if requried params are missing
     if ($image === null || $url === null) {
         return $this->error('missing-params');
     }
     # Prepare incomming params
     $image = trim($image);
     $url = trim($url);
     $alt = trim($alt);
     # Check for bad URLs
     if (!preg_match('/^(' . wfUrlProtocols() . ')/', $url) || preg_match('/\'"/', $url)) {
         $t = Title::newFromText($url);
         if (!$t) {
             return $this->error('bad-url', $url);
         }
         $url = $t->getFullURL();
     }
     # Check to see that the selected image exists
     $imageObj = Image::newFromName($image);
     if (!$imageObj->exists()) {
         return $this->error('no-such-image', $image);
     }
     # Finally, since all checks passed, display it!
     return $parser->insertStripItem($this->msg('embed-clause', htmlentities($url, ENT_COMPAT), $imageObj->getURL(), htmlentities($alt, ENT_COMPAT)), $parser->mStripState);
 }
Exemple #17
0
 /**
  * Loads the mapping table.
  */
 private function loadTable()
 {
     // no need to load multiple times.
     if ($this->loaded) {
         return;
     }
     $this->loaded = true;
     $title = Title::newFromText(self::$tablePageName);
     if (!$title->exists()) {
         return;
     }
     $tablePageRev = Revision::newFromTitle($title);
     if (is_object($tablePageRev)) {
         $tablePage = $tablePageRev->getText();
         global $wgUser;
         $parser = new Parser();
         $parser->setFunctionHook('tag_to_template', array($this, 'mg_tag_to_template'));
         // this will populate the 'map' variable
         // assuming of course that the page was edited with
         // {{#tag_to_template| ... }} instructions.
         $this->initPhase = true;
         $parser->parse($tablePage, $title, new ParserOptions($wgUser));
         $this->initPhase = false;
     }
 }
Exemple #18
0
 /**
  * @return DOMDocument
  */
 private function createAst()
 {
     $input = file_get_contents($this->fixtureDir . DIRECTORY_SEPARATOR . "test_grammar.ebnf");
     $scanner = new Scanner($input);
     $parser = new Parser($scanner);
     return $parser->parse();
 }
 /**
  * @param Parser $parser
  * @return array
  */
 public static function render($parser)
 {
     $html = '';
     $html .= $parser->insertStripItem('<a href="#" class="custom-watchlist-wrapper" id="add-to-watchlist"></a>');
     $parser->getOutput()->addModules('ext.customwatchlist.foo');
     return array($html, 'markerType' => 'nowiki');
 }
 /**
  * Load a RiveScript document from a file.
  *
  * @param array|string  $file
  */
 public function load($files)
 {
     $files = !is_array($files) ? (array) $files : $files;
     foreach ($files as $file) {
         $this->tree = $this->parser->process($file, $this->tree);
     }
 }
Exemple #21
0
 /**
  * @covers Geissler\Converter\Standard\CSL\Creator::create
  * @covers Geissler\Converter\Standard\CSL\Creator::getType
  * @covers Geissler\Converter\Standard\CSL\Creator::createPerson
  * @covers Geissler\Converter\Standard\CSL\Creator::createDate
  * @covers Geissler\Converter\Standard\CSL\Creator::retrieve
  * @dataProvider dataProviderForCreate
  */
 public function testCreate($input, $titles, $types, $authors = false, $issued = false, $issuedFull = false)
 {
     $parser = new Parser();
     $this->assertTrue($parser->parse($input));
     $this->assertTrue($this->object->create($parser->retrieve()));
     $csl = json_decode($this->object->retrieve(), true);
     $count = 0;
     foreach ($csl as $entry) {
         $this->assertEquals($titles[$count], $entry['title']);
         $this->assertEquals($types[$count], $entry['type']);
         if ($authors !== false) {
             $countAuthors = count($authors[$count]);
             for ($i = 0; $i < $countAuthors; $i++) {
                 $this->assertEquals($authors[$count][$i]['family'], $entry['author'][$i]['family']);
                 $this->assertEquals($authors[$count][$i]['given'], $entry['author'][$i]['given']);
             }
         }
         if ($issued !== false && isset($issued[$count]) == true) {
             $this->assertEquals($issued[$count]['year'], $entry['issued'][0]['year']);
             $this->assertArrayNotHasKey('day', $entry['issued'][0]);
             $this->assertArrayNotHasKey('month', $entry['issued'][0]);
         }
         if ($issuedFull !== false && isset($issuedFull[$count]) == true) {
             $this->assertEquals($issuedFull[$count]['year'], $entry['issued'][0]['year']);
             $this->assertEquals($issuedFull[$count]['day'], $entry['issued'][0]['day']);
             $this->assertEquals($issuedFull[$count]['month'], $entry['issued'][0]['month']);
         }
         $count++;
     }
 }
Exemple #22
0
/**
 * Setup parser hook
 *
 * @param Parser $parser
 * @return bool
 */
function efWidgetTagSetup(Parser $parser)
{
    global $wgHooks;
    $parser->setHook('widget', 'efWidgetTagRender');
    $wgHooks['ParserAfterTidy'][] = 'efWidgetTagReplaceMarkers';
    return true;
}
 /**
  * Compile some CoffeeScript.
  *
  * Available options:
  *
  *  'filename' => The source file, for debugging (formatted into error messages)
  *  'header'   => Add a header to the generated source (default: TRUE)
  *  'rewrite'  => Enable rewriting token stream (debugging)
  *  'tokens'   => Reference to token stream (debugging)
  *  'trace'    => File to write parser trace to (debugging)
  *
  * @param  string  The source CoffeeScript code
  * @param  array   Options (see above)
  *
  * @return string  The resulting JavaScript (if there were no errors)
  */
 static function compile($code, $options = array())
 {
     $lexer = new Lexer($code, $options);
     if (isset($options['filename'])) {
         Parser::$FILE = $options['filename'];
     }
     if (isset($options['tokens'])) {
         $tokens =& $options['tokens'];
     }
     if (isset($options['trace'])) {
         Parser::Trace(fopen($options['trace'], 'w', TRUE), '> ');
     }
     try {
         $parser = new Parser();
         foreach ($tokens = $lexer->tokenize() as $token) {
             $parser->parse($token);
         }
         $js = $parser->parse(NULL)->compile($options);
     } catch (\Exception $e) {
         throw new Error("In {$options['filename']}, " . $e->getMessage());
     }
     if (!isset($options['header']) || $options['header']) {
         $js = '// Generated by CoffeeScript PHP ' . VERSION . "\n" . $js;
     }
     return $js;
 }
Exemple #24
0
function renderpageTools($input)
{
    global $wgUser, $wgTitle, $wgOut, $IP;
    require_once "{$IP}/extensions/ListPages/ListPagesClass.php";
    $parser = new Parser();
    $list = new ListPages();
    $list->setBool("ShowCtg", "yes");
    $relatedctgArray = explode(",", strip_tags($list->getCategoryLinks($wgTitle->mArticleID, 7)));
    foreach ($relatedctgArray as $ctg) {
        if ($ctg != "") {
            $ctg = trim(strtoupper($ctg));
            if ($ctg != "NEWS" && $ctg != "OPINIONS") {
                if ($ctgstr != "") {
                    $ctgstr .= ",";
                }
                $CtgTitle = Title::newFromText($parser->transformMsg(trim($ctg), $wgOut->parserOptions()));
                $ctgstr .= $CtgTitle->getDbKey();
            }
        }
    }
    $output = "";
    $output .= '<a href="#pageToolsTop"></a><table cellpadding="0" cellspacing="0" border="0"><tr>';
    $output .= '<td width="100" id="commentsBtn" class="toptabsOn" onmousedown=\'javascript:$("commentsBtn").className="toptabsOn";$("historyBtn").className="toptabs";$("emailBtn").className="toptabs";$("relatedBtn").className="toptabs";getContent("index.php?title=Special:CommentAction&Action=2","pid=' . $wgTitle->mArticleID . '&shwform=1&ord=0","pageToolsContent")\'>Comments</td>';
    $output .= '<td width="5" class="topright">&nbsp;</td>';
    $output .= '<td width="100" id="emailBtn" class="toptabs" onmousedown=\'javascript:$("emailBtn").className="toptabsOn";$("historyBtn").className="toptabs";$("commentsBtn").className="toptabs";$("relatedBtn").className="toptabs";getContent("index.php?title=Special:EmailThis&pageid=' . $wgTitle->mArticleID . '","","pageToolsContent")\'>Email This</td>';
    $output .= '<td width="5" class="topright">&nbsp;</td>';
    $output .= '<td width="100" id="relatedBtn" class="toptabs" onmousedown=\'$("relatedBtn").className="toptabsOn";$("historyBtn").className="toptabs";$("commentsBtn").className="toptabs";$("emailBtn").className="toptabs";javascript:getContent("index.php?title=Special:ListPagesAction","shw=15&ctg=' . $ctgstr . '&ord=PUBLISHEDDATE&lv=1&shwctg=1&det=0&pub=1","pageToolsContent")\'>Related Articles</td>';
    $output .= '<td width="5" class="topright">&nbsp;</td>';
    $output .= '<td width="100" id="historyBtn" class="toptabs" onmousedown=\'$("historyBtn").className="toptabsOn";$("relatedBtn").className="toptabs";$("commentsBtn").className="toptabs";$("emailBtn").className="toptabs";javascript:getContent("index.php?title=Special:PageHistoryAJAX&pid=' . $wgTitle->mArticleID . '","","pageToolsContent")\'>Page History</td><td width="300" class="topright">&nbsp;</td>';
    $output .= '</tr></table><br/><div id="pageToolsContent">';
    return $output;
}
Exemple #25
0
 public function getAllData()
 {
     $url = $this->getWebsiteUrl();
     $parser = new Parser();
     $html = $parser->getHtml($url);
     phpQuery::newDocumentHTML($html);
     $data = array();
     $data['logo'] = $this->getLogo();
     $data['sitename'] = "Sulekha.com";
     foreach (pq(".box") as $item) {
         $class_Discount_bg = pq($item)->find(".dealimgst");
         $href = pq($class_Discount_bg)->find("a")->attr("href");
         $href = 'http://deals.sulekha.com' . $href;
         $actual_price = trim(pq($item)->find(".dlpristrk")->text());
         $actual_price = (int) preg_replace('~\\D~', '', $actual_price);
         $img_src = pq($class_Discount_bg)->find("img")->attr("src");
         $price = trim(pq($item)->find(".hgtlgtorg")->text());
         $price = (int) preg_replace('~\\D~', '', $price);
         $off_percent = $actual_price - $price;
         $off_percent = number_format($off_percent) . "/-";
         $price = number_format($price) . "/-";
         $name = trim(pq($item)->find(".deallstit>a")->text());
         //$time_left = pq($item)->find(".countdown_row")->text();
         $data[] = array('name' => $name, 'href' => $href, 'price' => 'Rs.' . $price, 'image' => $img_src, 'off' => 'Rs.' . $off_percent);
     }
     return $data;
 }
 /**
  * @brief This function set parseTag hook
  */
 public static function onParserFirstCallInit(Parser &$parser)
 {
     wfProfileIn(__METHOD__);
     $parser->setHook(CHAT_TAG, array(__CLASS__, "parseTag"));
     wfProfileOut(__METHOD__);
     return true;
 }
Exemple #27
0
 /**
  * Renders the view
  *
  * @param array $data additional view data
  *
  * @return string
  */
 public function render(array $data = [])
 {
     if (!empty($data)) {
         $this->set($data);
     }
     return $this->parser->parse($this->file, $this->getData());
 }
 /**
  * Constructor.
  * 
  * @param   object Document
  * @return  object Parser
  * @access  public
  * @static  method
  */
 function &create(&$parent)
 {
     $parser = new Parser();
     $parser->PEAR('Parser_Error');
     $parser->_prepare(&$parent);
     return $parser;
 }
 private function dumpAst($expression)
 {
     $parser = new Parser();
     $ast = $parser->parse($expression);
     fwrite($this->out, "AST\n========\n\n");
     fwrite($this->out, json_encode($ast, JSON_PRETTY_PRINT) . "\n");
 }
Exemple #30
-1
/**
 * Set hooks for each of the three parser tags
 * @param Parser $parser reference to MediaWiki Parser object
 */
function wfMainPageTag(&$parser)
{
    $parser->setHook('mainpage-rightcolumn-start', 'wfMainPageTag_rcs');
    $parser->setHook('mainpage-leftcolumn-start', 'wfMainPageTag_lcs');
    $parser->setHook('mainpage-endcolumn', 'wfMainPageTag_ec');
    return true;
}