示例#1
0
 /**
  * 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));
 }
 private function blockStats($blockId)
 {
     $this->wg->Out->setPageTitle(sprintf("%s #%s", wfMsg('phalanx-stats-title'), $blockId));
     $data = Phalanx::newFromId($blockId);
     if (!isset($data["id"])) {
         $this->wg->Out->addWikiMsg('phalanx-stats-block-notfound', $blockId);
         return;
     }
     $data['author_id'] = User::newFromId($data['author_id'])->getName();
     $data['timestamp'] = $this->wg->Lang->timeanddate($data['timestamp']);
     if ($data['expire'] == null) {
         $data['expire'] = 'infinite';
     } else {
         $data['expire'] = $this->wg->Lang->timeanddate($data['expire']);
     }
     $data['regex'] = $data['regex'] ? 'Yes' : 'No';
     $data['case'] = $data['case'] ? 'Yes' : 'No';
     $data['exact'] = $data['exact'] ? 'Yes' : 'No';
     $data['lang'] = empty($data['lang']) ? 'All' : $data['lang'];
     if ($data['type'] & Phalanx::TYPE_EMAIL && !$this->wg->User->isAllowed('phalanxemailblock')) {
         /* hide email from non-privildged users */
         $data['text'] = wfMsg('phalanx-email-filter-hidden');
     }
     $data['type'] = implode(', ', Phalanx::getTypeNames($data['type']));
     /* stats table */
     $headers = array(wfMsg('phalanx-stats-table-id'), wfMsg('phalanx-stats-table-user'), wfMsg('phalanx-stats-table-type'), wfMsg('phalanx-stats-table-create'), wfMsg('phalanx-stats-table-expire'), wfMsg('phalanx-stats-table-exact'), wfMsg('phalanx-stats-table-regex'), wfMsg('phalanx-stats-table-case'), wfMsg('phalanx-stats-table-language'));
     $tableAttribs = array('class' => 'wikitable', 'width' => '100%');
     /* pull these out of the array, so they dont get used in the top rows */
     $row = $data->toArray();
     unset($row['text']);
     unset($row['reason']);
     unset($row['comment']);
     unset($row['ip_hex']);
     // parse block comment
     if ($data['comment'] != '') {
         $comment = ParserPool::parse($data['comment'], $this->wg->Title, new ParserOptions())->getText();
     } else {
         $comment = '';
     }
     $table = Xml::buildTable(array($row), $tableAttribs, $headers);
     $table = str_replace("</table>", "", $table);
     $table .= "<tr><th>" . wfMsg('phalanx-stats-table-text') . "</th><td colspan='8'>" . htmlspecialchars($data['text']) . "</td></tr>";
     $table .= "<tr><th>" . wfMsg('phalanx-stats-table-reason') . "</th><td colspan='8'>{$data['reason']}</td></tr>";
     $table .= "<tr><th>" . wfMsg('phalanx-stats-table-comment') . "</th><td colspan='8'>{$comment}</td></tr>";
     $table .= "</table>";
     $this->setVal('table', $table);
     $this->setVal('editUrl', $this->phalanxTitle->getLocalUrl(array('id' => $data['id'])));
     /* match statistics */
     $pager = new PhalanxStatsPager($blockId);
     $this->setVal('statsPager', $pager->getNavigationBar() . $pager->getBody() . $pager->getNavigationBar());
 }
示例#3
0
 /**
  * parser hook for <wikitweets> tag
  * @return string tag body
  */
 public static function wikiTweetsParserHook($input, $args, $parser)
 {
     global $wgOut, $wgExtensionsPath, $wgTitle;
     $limit = isset($args['size']) && intval($args['size']) ? $args['size'] : 5;
     $phrase = isset($args['keywords']) ? $args['keywords'] : '';
     if (empty($phrase)) {
         return '';
     }
     // parse all "magic words" in the phrase
     $phrase = trim(strip_tags(ParserPool::parse($phrase, $wgTitle, $parser->mOptions)->getText()));
     $phrase = urlencode($phrase);
     self::$wikiTweetsTagCount++;
     $tagId = 'cfWikiTweetsTag' . self::$wikiTweetsTagCount;
     $tagBody = '<ul class="cfWikiTweetsTag" id="' . $tagId . '">';
     $tagBody .= '<a href="http://search.twitter.com/search?q=' . urlencode($phrase) . '" target="_blank">Loading ...</a>';
     $tagBody .= '</ul>';
     $tagBody .= JSSnippets::addToStack(array('/extensions/wikia/ContentFeeds/js/ContentFeeds.js'), array(), 'ContentFeeds.getTweets', array('tagId' => $tagId, 'phrase' => $phrase, 'limit' => $limit));
     return $tagBody;
 }
 public static function parseText($text = "")
 {
     global $wgTitle;
     return ParserPool::parse($text, $wgTitle, new ParserOptions())->getText();
 }
示例#5
0
function parse_citation($text, $params, $parser)
{
    global $wgCitationRunning;
    if ($wgCitationRunning) {
        return;
    }
    $ret = "";
    $attheend = false;
    $res = array();
    $res2 = array();
    $href = "";
    $a = explode("||", $text);
    foreach ($a as $line) {
        $data = explode("=", $line, 2);
        while (count($data) < 2) {
            $data[] = "";
        }
        $key = urlencode(trim(strtolower(array_shift($data))));
        $value = array_shift($data);
        // Parsed now : "$key" = "$value"
        if (substr($value, 0, 3) == "{{{") {
        } elseif ($key == "attheend") {
            $attheend = true;
        } elseif ($key == "href") {
            $href = $value;
        } elseif ($value != "") {
            $x = array("key" => $key, "value" => $value);
            $res[] = $x;
            $res2[$key] = $value;
        }
    }
    // Creating output string
    foreach ($res as $item) {
        $key = $item["key"];
        $value = $item["value"];
        $key2 = urldecode($key);
        if (strtolower(substr($key2, 0, 3)) == "if:") {
            $key2 = trim(substr($key2, 3));
            $key = urlencode($key2);
        }
        if (isset($res2[$key])) {
            $ret .= $value;
        }
    }
    if ($href != "") {
        $ret .= " [{$href}]";
    }
    // Adding to footer list or showing inline
    $wgCitationRunning = true;
    $ret = ParserPool::parse($ret, $parser->getTitle(), $parser->getOptions(), false);
    $wgCitationRunning = false;
    $ret = $ret->getText();
    if ($attheend) {
        global $wgCitationCache, $wgCitationCounter;
        $ret = "<a name='citation{$wgCitationCounter}'></a>{$ret}";
        $wgCitationCache[$wgCitationCounter] = $ret;
        $ret = "<a href='#citation{$wgCitationCounter}' name='citeback{$wgCitationCounter}'>{" . $wgCitationCounter . "}</a>";
        $wgCitationCounter++;
    } else {
        $ret = "<span style='font-size:8pt'>[{$ret}]</span>";
    }
    return $ret;
}
 /**
  * Return contribution/copyright notice
  */
 public function getCopyrightNotice()
 {
     global $wgMemc, $wgLang;
     wfProfileIn(__METHOD__);
     $wikitext = parent::getCopywarn();
     $key = wfMemcKey(__METHOD__, $wgLang->getCode(), md5($wikitext));
     $text = $wgMemc->get($key);
     if (empty($text)) {
         wfProfileIn(__METHOD__ . '-parse');
         $text = ParserPool::parse($wikitext, $this->app->wg->Title, new ParserOptions())->getText();
         wfProfileOut(__METHOD__ . '-parse');
         $wgMemc->set($key, $text, self::COPYRIGHT_CACHE_TTL);
     }
     wfProfileOut(__METHOD__);
     return $text;
 }
示例#7
0
 public function strip_wikitext($text, Title $title = null)
 {
     $app = F::app();
     // use memcached on top of Parser
     $textHash = md5($text);
     $key = wfmemcKey(__METHOD__, $textHash);
     $cachedText = $app->wg->memc->get($key);
     if (!empty($cachedText)) {
         return $cachedText;
     }
     $text = str_replace('*', '&asterix;', $text);
     if (empty($title)) {
         $title = $app->wg->Title;
     }
     // local parser to fix the issue fb#17907
     $text = ParserPool::parse($text, $title, $app->wg->Out->parserOptions())->getText();
     // BugId:31034 - I had to give ENT_COMPAT and UTF-8 explicitly.
     // Prior PHP 5.4 the defaults are ENT_COMPAT and ISO-8859-1 (not UTF-8)
     // and cause HTML entities in an actual UTF-8 string to be decoded incorrectly
     // and displayed in... an ugly way.
     $text = trim(strip_tags(html_entity_decode($text, ENT_COMPAT, 'UTF-8')));
     $text = str_replace('&asterix;', '*', $text);
     $app->wg->memc->set($key, $text, self::PARSER_CACHE_TTL);
     return $text;
 }
示例#8
0
 private static function __getRevisionText($iPage, $oRev)
 {
     global $wgLang, $wgUser;
     wfProfileIn(__METHOD__);
     $sResult = "";
     $titleObj = Title::newFromId($iPage);
     /* parse summary */
     if (!empty($oRev) && !empty($titleObj) && !empty(self::$aOptions['summary'])) {
         $sBlogText = $oRev->getText(Revision::FOR_THIS_USER);
         /* parse or not parse - this is a good question */
         if (!in_array(self::$aOptions['type'], array('array', 'noparse'))) {
             /* macbre - remove parser hooks (RT #67074) */
             global $wgParser;
             $hooks = $wgParser->getTags();
             $hooksRegExp = implode('|', array_map('preg_quote', $hooks));
             $sBlogText = preg_replace('#<(' . $hooksRegExp . ')[^>]{0,}>(.*)<\\/[^>]+>#s', '', $sBlogText);
             /* skip HTML tags */
             if (!empty(self::$blogTAGS)) {
                 /* skip some special tags  */
                 foreach (self::$blogTAGS as $id => $tag) {
                     $sBlogText = preg_replace($tag, '', $sBlogText);
                 }
             }
             $sBlogText = strip_tags($sBlogText, self::$skipStrinBeforeParse);
             /* skip invalid Wiki-text  */
             $sBlogText = preg_replace('/\\{\\{\\/(.*?)\\}\\}/si', '', $sBlogText);
             $sBlogText = preg_replace('/\\{\\{(.*?)\\}\\}/si', '', $sBlogText);
             if (!empty(self::$blogWIKITEXT)) {
                 /* skip some wiki-text */
                 foreach (self::$blogWIKITEXT as $id => $tag) {
                     $sBlogText = preg_replace($tag, '', $sBlogText);
                 }
             }
             /* parse truncated text */
             $parserOutput = ParserPool::parse($sBlogText, $titleObj, ParserOptions::newFromUser($wgUser));
             /* replace unused HTML tags */
             $sBlogText = preg_replace(self::$search, self::$replace, $parserOutput->getText());
             /* skip HTML tags */
             $sBlogText = strip_tags($sBlogText, self::$skipStrinAfterParse);
             /* truncate text */
             $cutSign = wfMsg("blug-cut-sign");
             $sResult = self::__truncateText($sBlogText, null, $cutSign);
             /* RT #69661: make sure truncated HTML is valid */
             if (function_exists('tidy_repair_string')) {
                 $sResult = tidy_repair_string($sResult, array(), 'utf8');
                 $idxStart = strpos($sResult, '<body>') + 6;
                 $idxEnd = strrpos($sResult, '</body>');
                 $sResult = substr($sResult, $idxStart, $idxEnd - $idxStart);
             }
         } else {
             /* parse revision text */
             $parserOutput = ParserPool::parse($sBlogText, $titleObj, ParserOptions::newFromUser($wgUser));
             $sResult = $parserOutput->getText();
         }
     }
     wfProfileOut(__METHOD__);
     return $sResult;
 }
 public function renderMediaGroup()
 {
     wfProfileIn(__METHOD__);
     $items = $this->request->getVal('items', []);
     /**
      * This is a parser from ImageGallery
      * @var $parser Parser
      */
     $parser = $this->request->getVal('parser');
     //ImageGallery has parser as false by default
     //and getVal returns default value when there is no value for a parameter
     //false is not useful here but is a value nevertheless
     //that is why default value is set after getVal
     if (!$parser instanceof Parser) {
         $parser = $this->wg->Parser;
     }
     $first = null;
     $wikiText = '';
     $result = '';
     $params = [];
     //separate linked items from normal ones and select the first one
     //which will be rendered in the page
     foreach ($items as $item) {
         /**
          * @var $file File
          */
         $file = wfFindFile($item['title']);
         if ($file instanceof File) {
             if (!empty($item['link']) || self::isSmallImage($file->getWidth(), $file->getHeight())) {
                 $wikiText .= self::renderOutsideGallery($item);
             } else {
                 if (empty($first)) {
                     $first = ['data' => $item, 'file' => $file];
                 }
                 //prepare data for media collection
                 $info = ['name' => htmlspecialchars(urlencode($item['title']->getDBKey())), 'full' => wfReplaceImageServer($file->getFullUrl(), $file->getTimestamp())];
                 if (WikiaFileHelper::isFileTypeVideo($file)) {
                     $info['type'] = 'video';
                     $info['provider'] = $file->getProviderName();
                 }
                 if (!empty($item['caption'])) {
                     $capt = $parser->internalParse($item['caption']);
                     $parser->replaceLinkHolders($capt);
                     //Kill all markers from gallery caption as if at this time they are not converted to HTML
                     //We want have chance to Json encode it and this might really brake gallery HTML
                     //https://wikia-inc.atlassian.net/browse/MOB-346
                     $info['capt'] = $parser->killMarkers($capt);
                 }
                 $params[] = $info;
             }
         }
     }
     if (!empty($first) && !empty($params)) {
         $file = $first['file'];
         $origWidth = $file->getWidth();
         $origHeight = $file->getHeight();
         //only one non-linked media left
         if (count($params) == 1) {
             $item = $first['data'];
             //build wikitext for a normal thumb
             $groupWikiText = '[[' . $item['title']->getPrefixedDBkey() . '|thumb|' . min($origWidth, self::THUMB_WIDTH) . 'px';
             if ($item['caption']) {
                 $groupWikiText .= "|{$item['caption']}";
             }
             $groupWikiText .= "]]\n";
             $wikiText = "{$groupWikiText}{$wikiText}";
         } else {
             //many left, proceed preparing and rendering the media group
             $size = self::calculateMediaSize($origWidth, $origHeight);
             $thumb = $file->transform($size);
             $attribs = array('src' => wfReplaceImageServer($thumb->getUrl(), $file->getTimestamp()), 'width' => $size['width'], 'height' => $size['height']);
             $result = $this->render(self::GROUP, $attribs, $params, array(), false, Xml::element('img', $attribs, '', true), [], wfMessage('wikiamobile-media-group-footer', count($params))->inContentLanguage()->plain());
         }
     }
     //if there's any raw wikitext left to parse
     //then do it now
     if (!empty($wikiText)) {
         $origVal = $this->wg->WikiaMobileDisableMediaGrouping;
         //avoid wikitext recursion
         $this->wg->WikiaMobileDisableMediaGrouping = true;
         //This wikiText is created locally here so we are safe with links also being normally replaced
         $result .= ParserPool::parse($wikiText, $this->wg->Title, new ParserOptions())->getText();
         //restoring to previous value
         $this->wg->WikiaMobileDisableMediaGrouping = $origVal;
     }
     $this->response->setBody($result);
     wfProfileOut(__METHOD__);
 }
 /**
  * AJAX helper called from view mode to get gallery data
  * @author Marooned
  */
 public static function getGalleryDataByHash($hash, $articleId, $revisionId = 0, $type = WikiaPhotoGallery::WIKIA_PHOTO_GALLERY)
 {
     global $wgUser, $wgOut;
     wfProfileIn(__METHOD__);
     self::initParserHook();
     self::$mGalleryHash = $hash;
     $parserOptions = new ParserOptions();
     $title = Title::newFromId($articleId);
     if (!$title) {
         $result['error'] = wfMsg('wikiaPhotoGallery-error-wrong-title');
         $result['errorCaption'] = wfMsg('wikiaPhotoGallery-error-caption');
         wfProfileOut(__METHOD__);
         return $result;
     }
     // let's parse current version of wikitext and store data of gallery with provided hash in self::$mGalleryData
     $rev = Revision::newFromTitle($title, $revisionId);
     //should never happen
     if (!is_null($rev)) {
         $wikitext = $rev->getText();
         ParserPool::parse($wikitext, $title, $parserOptions)->getText();
     }
     // Marooned: check block state of user (RT #55274)
     $permissionErrors = $title->getUserPermissionsErrors('edit', $wgUser);
     if (count($permissionErrors) && $type == WikiaPhotoGallery::WIKIA_PHOTO_GALLERY) {
         $result['error'] = $wgOut->parse($wgOut->formatPermissionsErrorMessage($permissionErrors));
         $result['errorCaption'] = wfMsg('wikiaPhotoGallery-error-caption');
     } elseif (empty(self::$mGalleryData)) {
         $result['error'] = wfMsg('wikiaPhotoGallery-error-outdated');
         $result['errorCaption'] = wfMsg('wikiaPhotoGallery-error-caption');
     } else {
         $result['info'] = 'ok';
         $result['gallery'] = self::$mGalleryData;
         $result['gallery']['starttime'] = wfTimestampNow();
     }
     wfProfileOut(__METHOD__);
     return $result;
 }
 static function getAllAnonMessages($user)
 {
     global $wgCityId, $wgExternalSharedDB, $wgMemc, $wgTitle;
     wfProfileIn(__METHOD__);
     $localCityId = isset($wgCityId) ? $wgCityId : 0;
     $memcKey = "smw:anon:{$localCityId}";
     $result = $wgMemc->get($memcKey);
     if (!is_array($result)) {
         $dbr = wfGetDB(DB_SLAVE, array(), $wgExternalSharedDB);
         $result = array();
         $dbResult = $dbr->query('SELECT msg_wiki_id, msg_id AS id, msg_text AS text, msg_expire AS expire, msg_lang AS lang, msg_status AS status' . ' FROM ' . MSG_TEXT_DB . ' LEFT JOIN ' . MSG_STATUS_DB . ' USING (msg_id)' . ' WHERE msg_mode = ' . MSG_MODE_SELECTED . ' AND msg_recipient_id = 0' . ' AND msg_recipient_name = ' . $dbr->addQuotes(MSG_RECIPIENT_ANON) . ' AND msg_status IN (' . MSG_STATUS_UNSEEN . ', ' . MSG_STATUS_SEEN . ')' . ' AND (msg_expire IS NULL OR msg_expire > ' . $dbr->addQuotes(date('Y-m-d H:i:s')) . ')' . ' AND msg_removed = ' . MSG_REMOVED_NO . " AND (msg_wiki_id = 0 OR msg_wiki_id = {$localCityId} )" . ';', __METHOD__);
         while ($oMsg = $dbr->fetchObject($dbResult)) {
             if (self::getLanguageConstraintsForUser($user, $oMsg->lang)) {
                 $messageText = ParserPool::parse($oMsg->text, $wgTitle, new ParserOptions())->getText();
                 $result['msg_' . $oMsg->id] = array('msgId' => $oMsg->id, 'wiki_id' => $oMsg->msg_wiki_id, 'text' => $messageText, 'expire' => $oMsg->expire, 'status' => $oMsg->status);
             }
         }
         if ($dbResult !== false) {
             $dbr->freeResult($dbResult);
         }
         //sort from newer to older
         krsort($result);
         // Cache result for 15 minutes
         $wgMemc->set($memcKey, $result, 900);
     }
     wfProfileOut(__METHOD__);
     return $result;
 }