コード例 #1
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));
 }
コード例 #2
0
 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;
 }
コード例 #4
0
 /**
  * Create a new Parser object
  *
  * @return Parser
  */
 public static function create()
 {
     global $wgParserConf;
     # Create base instance for cloning
     if (self::$origin === null) {
         $class = $wgParserConf['class'];
         if ($class == 'Parser_DiffTest') {
             self::$origin = false;
         } else {
             self::$origin = new Parser($wgParserConf);
         }
     }
     # Clone it (or create a new one if not possible)
     if (self::$origin !== false) {
         $parser = clone self::$origin;
     } else {
         $parser = new Parser($wgParserConf);
     }
     return $parser;
 }
コード例 #5
0
 /**
  * Prepares content in special format.
  * It doesn't parse template variables to extract them later.
  *
  * @param $content
  * @return string
  */
 private function prepareContent($content)
 {
     global $wgUser;
     $parser = \ParserPool::get();
     $parser->startExternalParse($this->title, \ParserOptions::newFromUser($wgUser), \Parser::OT_PLAIN);
     $frame = $parser->getPreprocessor()->newFrame();
     $dom = $parser->preprocessToDom($content);
     $content = $frame->expand($dom, PPFrame::NO_ARGS);
     $content = $parser->doTableStuff($content);
     return $content;
 }
コード例 #6
0
 public static function parseText($text = "")
 {
     global $wgTitle;
     return ParserPool::parse($text, $wgTitle, new ParserOptions())->getText();
 }
コード例 #7
0
ファイル: Citation.php プロジェクト: yusufchang/app
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;
}
コード例 #8
0
 public function parseText($rawText)
 {
     global $wgEnableParserCache;
     $this->mRawtext = self::removeMetadataTag($rawText);
     $wgEnableParserCache = false;
     $parser = ParserPool::get();
     $parser->ac_metadata = [];
     // VOLDEV-68: Remove broken section edit links
     $opts = ParserOptions::newFromContext(RequestContext::getMain());
     $opts->setEditSection(false);
     $head = $parser->parse($rawText, $this->mTitle, $opts);
     $this->mText = wfFixMalformedHTML($head->getText());
     $this->mHeadItems = $head->getHeadItems();
     if (isset($parser->ac_metadata)) {
         $this->mMetadata = $parser->ac_metadata;
     } else {
         $this->mMetadata = [];
     }
     ParserPool::release($parser);
     return $this->mText;
 }
コード例 #9
0
 public static function onGalleryBeforeProduceHTML($data, &$out)
 {
     global $wgArticleAsJson;
     wfProfileIn(__METHOD__);
     if ($wgArticleAsJson) {
         $parser = ParserPool::get();
         $parserOptions = new ParserOptions();
         $title = F::app()->wg->Title;
         $media = [];
         foreach ($data['images'] as $image) {
             $details = WikiaFileHelper::getMediaDetail(Title::newFromText($image['name'], NS_FILE), self::$mediaDetailConfig);
             $details['context'] = self::MEDIA_CONTEXT_GALLERY_IMAGE;
             $caption = $image['caption'];
             if (!empty($caption)) {
                 $caption = $parser->parse($caption, $title, $parserOptions, false)->getText();
             }
             $linkHref = isset($image['linkhref']) ? $image['linkhref'] : null;
             $media[] = self::createMediaObject($details, $image['name'], $caption, $linkHref);
             self::addUserObj($details);
         }
         self::$media[] = $media;
         if (!empty($media)) {
             $out = self::createMarker($media[0]['width'], $media[0]['height'], true);
         } else {
             $out = '';
         }
         ParserPool::release($parser);
         wfProfileOut(__METHOD__);
         return false;
     }
     wfProfileOut(__METHOD__);
     return true;
 }
コード例 #10
0
 /**
  * Save categories sent via AJAX into article
  */
 public function save()
 {
     wfProfileIn(__METHOD__);
     $articleId = $this->request->getVal('articleId', 0);
     $categories = $this->request->getVal('categories', array());
     $response = array();
     $title = Title::newFromID($articleId);
     if (wfReadOnly()) {
         $response['error'] = wfMessage('categoryselect-error-db-locked')->text();
     } else {
         if (is_null($title)) {
             $response['error'] = wfMessage('categoryselect-error-article-doesnt-exist', $articleId)->text();
         } else {
             if (!$title->userCan('edit') || $this->wg->User->isBlocked()) {
                 $response['error'] = wfMessage('categoryselect-error-user-rights')->text();
             } else {
                 if (!empty($categories) && is_array($categories)) {
                     Wikia::setVar('EditFromViewMode', 'CategorySelect');
                     $article = new Article($title);
                     $wikitext = $article->fetchContent();
                     // Pull in categories from templates inside of the article (BugId:100980)
                     $options = new ParserOptions();
                     $preprocessedWikitext = ParserPool::preprocess($wikitext, $title, $options);
                     $preprocessedData = CategoryHelper::extractCategoriesFromWikitext($preprocessedWikitext, true);
                     // Compare the new categories with those already in the article to weed out duplicates
                     $newCategories = CategoryHelper::getDiffCategories($preprocessedData['categories'], $categories);
                     // Append the new categories to the end of the article wikitext
                     $wikitext .= CategoryHelper::changeFormat($newCategories, 'array', 'wikitext');
                     // Update the array of categories for the front-end
                     $categories = array_merge($preprocessedData['categories'], $newCategories);
                     $dbw = wfGetDB(DB_MASTER);
                     $dbw->begin();
                     $editPage = new EditPage($article);
                     $editPage->edittime = $article->getTimestamp();
                     $editPage->recreate = true;
                     $editPage->textbox1 = $wikitext;
                     $editPage->summary = wfMessage('categoryselect-edit-summary')->inContentLanguage()->text();
                     $editPage->watchthis = $editPage->mTitle->userIsWatching();
                     $bot = $this->wg->User->isAllowed('bot');
                     $status = $editPage->internalAttemptSave($result, $bot)->value;
                     $response['status'] = $status;
                     switch ($status) {
                         case EditPage::AS_SUCCESS_UPDATE:
                         case EditPage::AS_SUCCESS_NEW_ARTICLE:
                             $dbw->commit();
                             $title->invalidateCache();
                             Article::onArticleEdit($title);
                             $response['html'] = $this->app->renderView('CategorySelectController', 'categories', array('categories' => $categories));
                             wfRunHooks('CategorySelectSave', array($title, $newCategories));
                             break;
                         case EditPage::AS_SPAM_ERROR:
                             $dbw->rollback();
                             $response['error'] = wfMessage('spamprotectiontext')->text() . '<p>( Case #8 )</p>';
                             break;
                         default:
                             $dbw->rollback();
                             $response['error'] = wfMessage('categoryselect-error-edit-abort')->text();
                     }
                 }
             }
         }
     }
     $this->response->setData($response);
     wfProfileOut(__METHOD__);
 }
コード例 #11
0
 /**
  * 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;
 }
コード例 #12
0
ファイル: MessageCache.php プロジェクト: Tjorriemorrie/app
 /**
  * Get Parser instance that's suitable for passing it to CoreParserFunctions
  * in MessageCache::transform()
  *
  * @author Władysław Bodzek <*****@*****.**>
  *
  * @param ParserOptions $popts
  * @return Parser
  */
 function getParserFor(ParserOptions $popts)
 {
     $interfaceMessage = $popts->getInterfaceMessage();
     $userLanguage = $popts->getUserLang();
     $hash = array();
     foreach (array($interfaceMessage, $userLanguage) as $obj) {
         if (is_object($obj)) {
             $hash[] = get_class($obj);
         } else {
             $hash[] = serialize($obj);
         }
     }
     $hash = implode('|', $hash);
     if (!isset(self::$parsersCache[$hash])) {
         if (count(self::$parsersCache) > 25) {
             foreach (self::$parsersCache as $parser) {
                 ParserPool::release($parser);
             }
         }
         $parser = ParserPool::get();
         $parser->startExternalParse(new Title('DoesntExistXYZ'), $popts, Parser::OT_PREPROCESS, true);
         self::$parsersCache[$hash] = $parser;
     }
     return self::$parsersCache[$hash];
 }
コード例 #13
0
 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;
 }
コード例 #14
0
 /**
  * Returns message in the requested format after parsing wikitext to html
  * This is meant to be equivalent to wfMsgExt() with parse, parsemag and escape as available options but using the DPL2 local parser instead of the global one (bugfix).
  */
 function msgExt($key, $options)
 {
     $args = func_get_args();
     array_shift($args);
     array_shift($args);
     if (!is_array($options)) {
         $options = array($options);
     }
     $string = wfMsgGetKey($key, true, false, false);
     $string = wfMsgReplaceArgs($string, $args);
     if (in_array('parse', $options)) {
         $this->mParserOptions->setInterfaceMessage(true);
         $string = $this->mParser->recursiveTagParse($string);
         $this->mParserOptions->setInterfaceMessage(false);
         //$string = $parserOutput->getText();
     } elseif (in_array('parsemag', $options)) {
         $parser = ParserPool::create();
         # Wikia
         $parserOptions = new ParserOptions();
         $parserOptions->setInterfaceMessage(true);
         $parser->startExternalParse($this->mParserTitle, $parserOptions, OT_MSG);
         $string = $parser->transformMsg($string, $parserOptions);
     }
     if (in_array('escape', $options)) {
         $string = htmlspecialchars($string);
     }
     return $string;
 }
コード例 #15
0
 /**
  * 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;
 }
コード例 #16
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;
 }
コード例 #17
0
ファイル: BlogTemplate.php プロジェクト: Tjorriemorrie/app
 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;
 }
コード例 #18
0
 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__);
 }