static function AJAXPollRender($input, $args = array(), Parser $parser)
 {
     global $wgUser, $wgOut, $wgTitle, $wgScriptPath, $wgUseAjax;
     $parser->disableCache();
     $parser->addTrackingCategory('ajaxpoll-tracking-category');
     if ($wgUser->getName() == '') {
         $userName = wfGetIP();
     } else {
         $userName = $wgUser->getName();
     }
     // ID of the poll
     $id = strtoupper(md5($input));
     $par = new Parser();
     $input = $par->parse($input, $wgTitle, $wgOut->parserOptions());
     $input = trim(strip_tags($input->getText()));
     $lines = explode("\n", trim($input));
     // compatibility for non-ajax requests - just in case
     if (!$wgUseAjax) {
         $responseId = "ajaxpoll-post-id";
         $responseAnswer = "ajaxpoll-post-answer-{$id}";
         $responseToken = "ajaxPollToken";
         if (isset($_POST[$responseId]) && isset($_POST[$responseAnswer]) && $_POST[$responseId] == $id && isset($_POST[$responseToken])) {
             self::submitVote($id, intval($_POST[$responseAnswer]), $_POST[$responseToken]);
         }
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->begin(__METHOD__);
     /**
      * Register poll in the database
      */
     $row = $dbw->selectRow(array('ajaxpoll_info'), array('COUNT(poll_id) AS count'), array('poll_id' => $id), __METHOD__);
     $showResultsBeforeVoting = null;
     if (array_key_exists('show-results-before-voting', $args)) {
         if (strval($args['show-results-before-voting']) !== '0') {
             $showResultsBeforeVoting = '1';
         } else {
             $showResultsBeforeVoting = '0';
         }
     }
     if (empty($row->count)) {
         $dbw->insert('ajaxpoll_info', array('poll_id' => $id, 'poll_show_results_before_voting' => $showResultsBeforeVoting, 'poll_txt' => $input, 'poll_date' => wfTimestampNow()), __METHOD__);
     } else {
         $dbw->update('ajaxpoll_info', array('poll_show_results_before_voting' => $showResultsBeforeVoting), array('poll_id' => $id), __METHOD__);
     }
     $dbw->commit(__METHOD__);
     switch ($lines[0]) {
         case 'STATS':
             $ret = self::buildStats($id, $userName);
             break;
         default:
             $ret = Html::rawElement('div', array('id' => 'ajaxpoll-container-' . $id), self::buildHTML($id, $userName, $lines));
             break;
     }
     return $ret;
 }
Exemple #2
0
 /**
  * Set elements that should be hidden
  *
  * @param $parser Parser current parser
  * @return string
  */
 static function setHiddenElements(Parser $parser)
 {
     global $wgTweekiSkinHideAll, $wgTweekiSkinHideable;
     $parser->disableCache();
     // Argument 0 is $parser, so begin iterating at 1
     for ($i = 1; $i < func_num_args(); $i++) {
         if (in_array(func_get_arg($i), $wgTweekiSkinHideable)) {
             $wgTweekiSkinHideAll[] = func_get_arg($i);
         }
     }
     return '';
 }
 /**
  * Embeds video of the chosen service
  * @param Parser $parser Instance of running Parser.
  * @param String $service Which online service has the video.
  * @param String $id Identifier of the chosen service
  * @param String $width Width of video (optional)
  * @param String $desc description to show (optional, unused)
  * @param String $align alignment of the video (optional, unused)
  * @return String Encoded representation of input params (to be processed later)
  */
 public static function parserFunction_ev($parser, $service = null, $id = null, $width = null, $align = null, $desc = null)
 {
     global $wgScriptPath;
     # Initialize things once
     if (!EmbedVideo::$initialized) {
         EmbedVideo::VerifyWidthMinAndMax();
         # Add system messages
         wfLoadExtensionMessages('embedvideo');
         $parser->disableCache();
         EmbedVideo::$initialized = true;
     }
     # Get the name of the host
     if ($service === null || $id === null) {
         return EmbedVideo::errMissingParams($service, $id);
     }
     $service = trim($service);
     $id = trim($id);
     $desc = $parser->recursiveTagParse($desc);
     $entry = EmbedVideo::getServiceEntry($service);
     if (!$entry) {
         return EmbedVideo::errBadService($service);
     }
     if (!EmbedVideo::sanitizeWidth($entry, $width)) {
         return EmbedVideo::errBadWidth($width);
     }
     $height = EmbedVideo::getHeight($entry, $width);
     $hasalign = $align !== null;
     if ($hasalign) {
         $desc = EmbedVideo::getDescriptionMarkup($desc);
     }
     # If the service has an ID pattern specified, verify the id number
     if (!EmbedVideo::verifyID($entry, $id)) {
         return EmbedVideo::errBadID($service, $id);
     }
     # if the service has it's own custom extern declaration, use that instead
     if (array_key_exists('extern', $entry) && ($clause = $entry['extern']) != null) {
         $clause = wfMsgReplaceArgs($clause, array($wgScriptPath, $id, $width, $height));
         if ($hasalign) {
             $clause = EmbedVideo::generateAlignExternClause($clause, $align, $desc, $width, $height);
         }
         return array($clause, 'noparse' => true, 'isHTML' => true);
     }
     # Build URL and output embedded flash object
     $url = wfMsgReplaceArgs($entry['url'], array($id, $width, $height));
     $clause = "";
     if ($hasalign) {
         $clause = EmbedVideo::generateAlignClause($url, $width, $height, $align, $desc);
     } else {
         $clause = EmbedVideo::generateNormalClause($url, $width, $height);
     }
     return array($clause, 'noparse' => true, 'isHTML' => true);
 }
Exemple #4
0
/**
 * Renders a table of all the individual month tables
 *
 * @param Parser $parser
 * @return string
 */
function wfRenderCalendar(&$parser)
{
    $parser->disableCache();
    $argv = array();
    foreach (func_get_args() as $arg) {
        if (!is_object($arg)) {
            if (preg_match('/^(.+?)\\s*=\\s*(.+)$/', $arg, $match)) {
                $argv[$match[1]] = $match[2];
            }
        }
    }
    if (isset($argv['format'])) {
        $f = $argv['format'];
    } else {
        $f = '%e %B %Y';
    }
    if (isset($argv['dayformat'])) {
        $df = $argv['dayformat'];
    } else {
        $df = false;
    }
    if (isset($argv['title'])) {
        $p = $argv['title'] . '/';
    } else {
        $p = '';
    }
    if (isset($argv['query'])) {
        $q = $argv['query'] . '&action=edit';
    } else {
        $q = 'action=edit';
    }
    if (isset($argv['year'])) {
        $y = $argv['year'];
    } else {
        $y = date('Y');
    }
    if (isset($argv['month'])) {
        $m = $argv['month'];
        return wfRenderMonth(strftime('%m', strtotime("{$y}-{$m}-01")), $y, $p, $q, $f, $df);
    } else {
        $m = 1;
    }
    $table = "{| class=\"calendar\"\n";
    for ($rows = 3; $rows--; $table .= "|-\n") {
        for ($cols = 0; $cols < 4; $cols++) {
            $table .= '|' . wfRenderMonth($m++, $y, $p, $q, $f, $df) . "\n";
        }
    }
    return "{$table}\n|}\n";
}
Exemple #5
0
 /**
  * Callback function for registerParserHook.
  *
  * @param string $input User-supplied input, unused
  * @param array $args User-supplied arguments
  * @param Parser $parser Instance of Parser, unused
  * @return string HTML
  */
 public static function renderVote($input, $args, $parser)
 {
     global $wgOut, $wgUser;
     wfProfileIn(__METHOD__);
     // Disable parser cache (sadly we have to do this, because the caching is
     // messing stuff up; we want to show an up-to-date rating instead of old
     // or totally wrong rating, i.e. another page's rating...)
     $parser->disableCache();
     // Add CSS & JS
     // In order for us to do this *here* instead of having to do this in
     // registerParserHook(), we must've disabled parser cache
     $parser->getOutput()->addModuleStyles('ext.voteNY.styles');
     if ($wgUser->isAllowed('voteny')) {
         $parser->getOutput()->addModules('ext.voteNY.scripts');
     }
     // Define variable - 0 means that we'll get that green voting box by default
     $type = 0;
     // Determine what kind of a voting gadget the user wants: a box or pretty stars?
     if (preg_match("/^\\s*type\\s*=\\s*(.*)/mi", $input, $matches)) {
         $type = htmlspecialchars($matches[1]);
     } elseif (!empty($args['type'])) {
         $type = intval($args['type']);
     }
     $output = null;
     $title = $wgOut->getTitle();
     if ($title) {
         $articleID = $title->getArticleID();
         switch ($type) {
             case 0:
                 $vote = new Vote($articleID);
                 break;
             case 1:
                 $vote = new VoteStars($articleID);
                 break;
             default:
                 $vote = new Vote($articleID);
         }
         $output = $vote->display();
     }
     wfProfileOut(__METHOD__);
     return $output;
 }
 static function renderToolProperty($input, array $args, Parser $parser, PPFrame $frame)
 {
     $parser->disableCache();
     $id = $args['id'];
     $property = $args['property'];
     $format = array_key_exists('format', $args) ? $args['format'] : null;
     $function = array_key_exists('function', $args) ? $args['function'] : null;
     $parsedId = $parser->recursiveTagParse($id, $frame);
     if (is_numeric($parsedId) && !array_key_exists($parsedId, self::$resources)) {
         $lnf = new LNF();
         self::$resources[$parsedId] = $lnf->getResource($parsedId);
     }
     if (array_key_exists($parsedId, self::$resources)) {
         $res = self::$resources[$parsedId];
     }
     if ($res == null) {
         return $property;
     }
     if ($property == "ToolEngineers") {
         if (is_array($res->ToolEngineers)) {
             $html = "<ul>";
             foreach ($res->ToolEngineers as $item) {
                 $html .= '<li><a href="mailto:' . $item->Email[0] . '">' . $item->DisplayName . '</li>';
             }
             $html .= "</ul>";
             return $html;
         } else {
             $result = self::getPropertyValue($res, "ToolEngineers");
         }
     } else {
         $result = self::getPropertyValue($res, $property);
     }
     if ($function != null) {
         $result = self::$function($result);
     }
     if ($format == null) {
         return $result;
     } else {
         return sprintf($format, $result);
     }
 }
Exemple #7
0
 /**
  * fixTemplate
  *
  * This code ensures that the version of the Template that was in existence
  * at the same time as the Memento gets loaded and displayed with the
  * Memento.
  *
  * @fixme make this compatible with parser cache
  * @param Title $title
  * @param Parser $parser
  * @param integer $id
  *
  * @return array containing the text, finalTitle, and deps
  */
 public function fixTemplate(Title $title, Parser $parser, &$id)
 {
     // stopgap measure until we can find a better way
     // to work with parser cache
     $parser->disableCache();
     $request = $parser->getUser()->getRequest();
     if ($request->getHeader('ACCEPT-DATETIME')) {
         $requestDatetime = $request->getHeader('ACCEPT-DATETIME');
         $mwMementoTimestamp = $this->parseRequestDateTime($requestDatetime);
         $firstRev = $title->getFirstRevision();
         // if the template no longer exists, return gracefully
         if ($firstRev != null) {
             if ($firstRev->getTimestamp() < $mwMementoTimestamp) {
                 $pgID = $title->getArticleID();
                 $this->db->begin();
                 $res = $this->db->selectRow('revision', array('rev_id'), array('rev_page' => $pgID, 'rev_timestamp <=' . $this->db->addQuotes($mwMementoTimestamp)), __METHOD__, array('ORDER BY' => 'rev_id DESC', 'LIMIT' => '1'));
                 $id = $res->rev_id;
             } else {
                 // if we get something prior to the first memento, just
                 // go with the first one
                 $id = $firstRev->getId();
             }
         }
     }
 }
 /**
  * @param Parser $parser
  * @return bool
  */
 function skin(&$parser)
 {
     global $wgUser, $wgRequest;
     $parser->disableCache();
     return $wgRequest->getVal('useskin', $wgUser->getGlobalPreference('skin'));
 }
 /**
  * Renders the blog. Called by parser function for bs:blog tag and also from Blog::onUnknownAction.
  * @param string $input Inner HTML of bs:blog tag. Not used.
  * @param array $args List of tag attributes.
  * @param Parser $parser MediaWiki parser object
  * @return string HTML output that is to be displayed.
  */
 public function onBlog($input, $args, $parser)
 {
     $oTitle = null;
     if ($parser instanceof Parser) {
         $oTitle = $parser->getTitle();
         $parser->disableCache();
     } else {
         $oTitle = $this->getTitle();
     }
     $sKey = BsCacheHelper::getCacheKey('BlueSpice', 'Blog', $oTitle->getArticleID());
     $aData = BsCacheHelper::get($sKey);
     if ($aData !== false) {
         return $aData;
     }
     // initialize local variables
     $oErrorListView = new ViewTagErrorList($this);
     BsExtensionManager::setContext('MW::Blog::ShowBlog');
     // get all config options
     $iShowLimit = BsConfig::get('MW::Blog::ShowLimit');
     //$blogShowTrackback    = BsConfig::get('MW::Blog::ShowTrackback');  // see comment below
     $bShowPermalink = BsConfig::get('MW::Blog::ShowPermalink');
     $bShowInfo = BsConfig::get('MW::Blog::ShowInfo');
     $sSortBy = BsConfig::get('MW::Blog::SortBy');
     $bMoreInNewWindow = BsConfig::get('MW::Blog::MoreInNewWindow');
     $bShowAll = BsConfig::get('MW::Blog::ShowAll');
     $bMoreAtEndOfEntry = BsConfig::get('MW::Blog::MoreAtEndOfEntry');
     $bShowNewEntryField = BsConfig::get('MW::Blog::ShowNewEntryField');
     $bNewEntryFieldPosition = BsConfig::get('MW::Blog::NewEntryFieldPosition');
     $sImageRenderMode = BsConfig::get('MW::Blog::ImageRenderMode');
     $sImageFloatDirection = BsConfig::get('MW::Blog::ThumbFloatDirection');
     $iMaxEntryCharacters = BsConfig::get('MW::Blog::MaxEntryCharacters');
     // Trackbacks are not supported the way we intend it to be. From http://www.mediawiki.org/wiki/Manual:$wgUseTrackbacks
     // When MediaWiki receives a trackback ping, a box will show up at the bottom of the article containing a link to the originating page
     //if (!$wgUseTrackbacks)
     $bShowTrackback = false;
     // get tag attributes
     $argsIShowLimit = BsCore::sanitizeArrayEntry($args, 'count', $iShowLimit, BsPARAMTYPE::NUMERIC | BsPARAMOPTION::DEFAULT_ON_ERROR);
     $argsSCategory = BsCore::sanitizeArrayEntry($args, 'cat', false, BsPARAMTYPE::STRING);
     $argsINamespace = BsNamespaceHelper::getNamespaceIndex(BsCore::sanitizeArrayEntry($args, 'ns', NS_BLOG, BsPARAMTYPE::STRING));
     $argsBNewEntryField = BsCore::sanitizeArrayEntry($args, 'newentryfield', $bShowNewEntryField, BsPARAMTYPE::BOOL);
     $argsSNewEntryFieldPosition = BsCore::sanitizeArrayEntry($args, 'newentryfieldposition', $bNewEntryFieldPosition, BsPARAMTYPE::STRING);
     $argsSImageRenderMode = BsCore::sanitizeArrayEntry($args, 'imagerendermode', $sImageRenderMode, BsPARAMTYPE::STRING);
     $argsSImageFloatDirection = BsCore::sanitizeArrayEntry($args, 'imagefloatdirection', $sImageFloatDirection, BsPARAMTYPE::STRING);
     $argsIMaxEntryCharacters = BsCore::sanitizeArrayEntry($args, 'maxchars', $iMaxEntryCharacters, BsPARAMTYPE::INT);
     $argsSSortBy = BsCore::sanitizeArrayEntry($args, 'sort', $sSortBy, BsPARAMTYPE::STRING);
     $argsBShowInfo = BsCore::sanitizeArrayEntry($args, 'showinfo', $bShowInfo, BsPARAMTYPE::BOOL);
     $argsBMoreInNewWindow = BsCore::sanitizeArrayEntry($args, 'moreinnewwindow', $bMoreInNewWindow, BsPARAMTYPE::BOOL);
     $argsBShowPermalink = BsCore::sanitizeArrayEntry($args, 'showpermalink', $bShowPermalink, BsPARAMTYPE::BOOL);
     $argsModeNamespace = BsCore::sanitizeArrayEntry($args, 'mode', null, BsPARAMTYPE::STRING);
     if ($argsModeNamespace === 'ns' && is_object($oTitle)) {
         $argsINamespace = $oTitle->getNamespace();
     }
     // validate tag attributes
     $validateIShowLimit = BsValidator::isValid('ArgCount', $argsIShowLimit, array('fullResponse' => true));
     if ($validateIShowLimit->getErrorCode()) {
         $oErrorListView->addItem(new ViewTagError($validateIShowLimit->getI18N()));
     }
     if ($argsSCategory) {
         $validateSCategory = BsValidator::isValid('Category', $argsSCategory, array('fullResponse' => true));
         if ($validateSCategory->getErrorCode()) {
             $oErrorListView->addItem(new ViewTagError($validateSCategory->getI18N()));
         }
     }
     $oValidationResult = BsValidator::isValid('SetItem', $argsSImageRenderMode, array('fullResponse' => true, 'setname' => 'imagerendermode', 'set' => array('full', 'thumb', 'none')));
     if ($oValidationResult->getErrorCode()) {
         $oErrorListView->addItem(new ViewTagError($oValidationResult->getI18N()));
     }
     $oValidationResult = BsValidator::isValid('SetItem', $argsSImageFloatDirection, array('fullResponse' => true, 'setname' => 'imagefloatdirection', 'set' => array('left', 'right', 'none')));
     if ($oValidationResult->getErrorCode()) {
         $oErrorListView->addItem(new ViewTagError($oValidationResult->getI18N()));
     }
     $oValidationResult = BsValidator::isValid('SetItem', $argsSSortBy, array('fullResponse' => true, 'setname' => 'sort', 'set' => array('title', 'creation')));
     if ($oValidationResult->getErrorCode()) {
         $oErrorListView->addItem(new ViewTagError($oValidationResult->getI18N()));
     }
     // if there are errors, abort with a message
     if ($oErrorListView->hasEntries()) {
         return $oErrorListView->execute();
     }
     if (BsConfig::get('MW::Blog::ShowTagFormWhenNotLoggedIn') != true) {
         $oPermissionTest = Title::newFromText('PermissionTest', $argsINamespace);
         if (!$oPermissionTest->userCan('edit')) {
             $argsBNewEntryField = false;
         }
     }
     // get array of article ids from Blog/subpages
     $oBlogTitle = Title::makeTitleSafe($oTitle->getNamespace(), 'Blog');
     $aSubpages = $oBlogTitle->getSubpages();
     $iLimit = 0;
     // for later use
     $aArticleIds = array();
     foreach ($aSubpages as $oSubpage) {
         $aArticleIds[] = $oSubpage->getArticleID();
         $iLimit++;
         // for later use
     }
     if (count($aArticleIds) < 1) {
         $aArticleIds = 0;
     }
     $aTables = array('page');
     $aFields = array('entry_page_id' => 'page_id');
     $aConditions = array();
     $aOptions = array();
     $aJoins = array();
     $dbr = wfGetDB(DB_SLAVE);
     // get blog entries
     if ($argsSSortBy == 'title') {
         $aOptions['ORDER BY'] = 'page_title ASC';
     } else {
         //Creation: Also fetch possible custom timestamps from page_props table
         $aOptions['ORDER BY'] = 'entry_timestamp DESC';
         $aOptions['GROUP BY'] = 'page_id';
         global $wgDBtype;
         switch ($wgDBtype) {
             case 'oracle':
                 $aFields['entry_timestamp'] = "NVL( pp_value, rev_timestamp )";
                 $aConditions[] = "NVL( pp_value, rev_timestamp ) < " . wfTimestampNow();
                 break;
             case 'mssql':
                 $aFields['entry_timestamp'] = "ISNULL( pp_value, rev_timestamp )";
                 $aConditions[] = "ISNULL( pp_value, rev_timestamp ) < " . wfTimestampNow();
                 break;
             case 'postgres':
                 $aFields['entry_timestamp'] = "NULLIF( pp_value, rev_timestamp )";
                 $aConditions[] = "NULLIF( pp_value, rev_timestamp ) < " . wfTimestampNow();
                 break;
             default:
                 //MySQL, SQLite
                 //use pp_value if exists
                 $aFields['entry_timestamp'] = "IFNULL( pp_value, rev_timestamp )";
                 //also do not list future entries
                 $aConditions[] = "IFNULL( pp_value, rev_timestamp ) < " . wfTimestampNow();
         }
         $aTables[] = 'revision';
         $aTables[] = 'page_props';
         $aConditions[] = 'rev_page = page_id';
         $aJoins['page_props'] = array('LEFT JOIN', "pp_page = rev_page AND pp_propname = 'blogtime'");
     }
     if ($argsSCategory) {
         $aTables[] = 'categorylinks';
         $aConditions['cl_to'] = $argsSCategory;
         $aConditions[] = 'cl_from = page_id';
     } else {
         if ($argsModeNamespace === 'ns') {
             $aConditions['page_id'] = $aArticleIds;
         }
         $aConditions['page_namespace'] = $argsINamespace;
     }
     $res = $dbr->select($aTables, $aFields, $aConditions, __METHOD__, $aOptions, $aJoins);
     $iNumberOfEntries = $dbr->numRows($res);
     $iLimit = $iNumberOfEntries;
     //All
     // Sole importance is the existence of param 'showall'
     $paramBShowAll = $this->getRequest()->getFuzzyBool('showall', false);
     if ($paramBShowAll == false) {
         $iLimit = $argsIShowLimit;
     }
     // abort if there are no entries
     if ($iNumberOfEntries < 1) {
         $oBlogView = new ViewBlog();
         $oBlogView->setOption('shownewentryfield', $argsBNewEntryField);
         $oBlogView->setOption('newentryfieldposition', $argsSNewEntryFieldPosition);
         $oBlogView->setOption('namespace', BsNamespaceHelper::getNamespaceName($argsINamespace));
         if ($argsSCategory) {
             $oBlogView->setOption('blogcat', $argsSCategory);
         }
         // actually create blog output
         $sOut = $oBlogView->execute();
         $sOut .= wfMessage('bs-blog-no-entries')->plain();
         return $sOut;
     }
     $oBlogView = new ViewBlog();
     // prepare views per blog item
     $iLoop = 0;
     foreach ($res as $row) {
         // prepare data for view class
         $oEntryTitle = Title::newFromID($row->entry_page_id);
         if (!$oEntryTitle->userCan('read')) {
             $iNumberOfEntries--;
             continue;
         }
         $bMore = false;
         $aContent = preg_split('#<(bs:blog:)?more */>#', BsPageContentProvider::getInstance()->getContentFromTitle($oEntryTitle));
         if (sizeof($aContent) > 1) {
             $bMore = true;
         }
         $aContent = trim($aContent[0]);
         // Prevent recursive rendering of blog tag
         $aContent = preg_replace('/<(bs:)blog[^>]*?>/', '', $aContent);
         // Thumbnail images
         $sNamespaceRegEx = implode('|', BsNamespaceHelper::getNamespaceNamesAndAliases(NS_IMAGE));
         switch ($argsSImageRenderMode) {
             case 'none':
                 $aContent = preg_replace('/(\\[\\[(' . $sNamespaceRegEx . '):[^\\|\\]]*)(\\|)?(.*?)(\\]\\])/', '', $aContent);
                 break;
             case 'full':
                 // do nothing
                 break;
             case 'thumb':
             default:
                 $aContent = preg_replace('/(\\[\\[(' . $sNamespaceRegEx . '):[^\\|\\]]*)(\\|)?(.*?)(\\]\\])/', "\$1|thumb|{$argsSImageFloatDirection}\$3\$4|150px\$5", $aContent);
                 break;
         }
         if (strlen($aContent) > $argsIMaxEntryCharacters) {
             $bMore = true;
         }
         $aContent = BsStringHelper::shorten($aContent, array('max-length' => $argsIMaxEntryCharacters, 'ignore-word-borders' => false, 'position' => 'end'));
         $resComment = $dbr->selectRow('revision', 'COUNT( rev_id ) AS cnt', array('rev_page' => $oEntryTitle->getTalkPage()->getArticleID()));
         $iCount = $resComment->cnt;
         // set data for view class
         $oBlogItemView = new ViewBlogItem();
         // use magic set
         $oBlogItemView->setOption('showInfo', $argsBShowInfo);
         $oBlogItemView->setOption('showLimit', $argsIShowLimit);
         $oBlogItemView->setOption('showTrackback', $bShowTrackback);
         $oBlogItemView->setOption('showPermalink', $argsBShowPermalink);
         $oBlogItemView->setOption('moreInNewWindow', $argsBMoreInNewWindow);
         $oBlogItemView->setOption('showAll', $bShowAll);
         $oBlogItemView->setOption('moreAtEndOfEntry', $bMoreAtEndOfEntry);
         $oBlogItemView->setOption('more', $bMore);
         //TODO: magic_call?
         if ($argsModeNamespace === 'ns') {
             $sTitle = substr($oEntryTitle->getText(), 5);
         } else {
             $sTitle = $oEntryTitle->getText();
         }
         $aTalkParams = array();
         if (!$oEntryTitle->getTalkPage()->exists()) {
             $aTalkParams = array('action' => 'edit');
         }
         $oRevision = Revision::newFromTitle($oEntryTitle);
         $oBlogItemView->setTitle($sTitle);
         $oBlogItemView->setRevId($oRevision->getId());
         $oBlogItemView->setURL($oEntryTitle->getLocalURL());
         $oBlogItemView->setTalkURL($oEntryTitle->getTalkPage()->getLocalURL($aTalkParams));
         $oBlogItemView->setTalkCount($iCount);
         $oBlogItemView->setTrackbackUrl($oEntryTitle->getLocalURL());
         if ($bShowInfo) {
             $oFirstRevision = $oEntryTitle->getFirstRevision();
             $sTimestamp = $oFirstRevision->getTimestamp();
             $sLocalDateTimeString = BsFormatConverter::timestampToAgeString(wfTimestamp(TS_UNIX, $sTimestamp));
             $oBlogItemView->setEntryDate($sLocalDateTimeString);
             $iUserId = $oFirstRevision->getUser();
             if ($iUserId != 0) {
                 $oAuthorUser = User::newFromId($iUserId);
                 $oBlogItemView->setAuthorPage($oAuthorUser->getUserPage()->getPrefixedText());
                 $oBlogItemView->setAuthorName($this->mCore->getUserDisplayName($oAuthorUser));
             } else {
                 $oBlogItemView->setAuthorName($oFirstRevision->getUserText());
             }
         }
         $oBlogItemView->setContent($aContent);
         $oBlogView->addItem($oBlogItemView);
         $iLoop++;
         if ($iLoop >= $iLimit) {
             break;
         }
     }
     $dbr->freeResult($res);
     // prepare complete blog output
     if ($bShowAll && !$paramBShowAll && $iNumberOfEntries > $argsIShowLimit) {
         $oBlogView->setOption('showall', true);
     }
     $oBlogView->setOption('shownewentryfield', $argsBNewEntryField);
     $oBlogView->setOption('newentryfieldposition', $argsSNewEntryFieldPosition);
     $oBlogView->setOption('namespace', BsNamespaceHelper::getNamespaceName($argsINamespace, false));
     $oBlogView->setOption('blogcat', $argsSCategory);
     if ($argsModeNamespace === 'ns') {
         $oBlogView->setOption('parentpage', 'Blog/');
     }
     // actually create blog output
     $sOut = $oBlogView->execute();
     //Use cache only in NS_BLOG - there is curently no functionality to
     //figure out in what type of blog tag a entry is showen and why
     //(coditions). Possible blog by categories or subpages...
     //Needs rework.
     if (in_array($oTitle->getNamespace(), array(NS_BLOG, NS_BLOG_TALK))) {
         $aKey = array($sKey);
         $sTagsKey = BsCacheHelper::getCacheKey('BlueSpice', 'Blog', 'Tags');
         $aTagsData = BsCacheHelper::get($sTagsKey);
         if ($aTagsData !== false) {
             if (!in_array($sKey, $aTagsData)) {
                 $aTagsData = array_merge($aTagsData, $aKey);
             }
         } else {
             $aTagsData = $aKey;
         }
         BsCacheHelper::set($sTagsKey, $aTagsData, 60 * 1440);
         // one day
         BsCacheHelper::set($sKey, $sOut, 60 * 1440);
         // one day
     }
     return $sOut;
 }
 /**
  * Parser hook callback
  *
  * @param string $input Tag input
  * @param array $args Tag attributes
  * @param Parser $parser Parent parser
  * @return string
  */
 public static function renderHook($input, $args, $parser)
 {
     global $wgRandomImageNoCache;
     if ($wgRandomImageNoCache) {
         $parser->disableCache();
     }
     $random = new RandomImage($parser, $args, $input);
     return $random->render();
 }
Exemple #11
0
/**
 * This is called when {{#manual:short|long}} is found in an article content. It should produce an output
 * set of HTML which provides the name (long) as a link to the most recent (based on version tags) TOC
 * management page for that manual.
 *
 * @param Parser $parser
 * @param string $shortName Short name of the Manual used in links.
 * @param string $longName Long/display name of Manual.
 * @param string $categories The categories for the Manual, in a comma-separated list
 * @return array
 */
function efManualParserFunction_Render(&$parser, $shortName = '', $longName = '', $categories = '')
{
    global $wgArticlePath;
    $valid = TRUE;
    if (!preg_match(PONYDOCS_PRODUCTMANUAL_REGEX, $shortName) || !strlen($shortName) || !strlen($longName)) {
        return $parser->insertStripItem('', $parser->mStripState);
    }
    $manualName = preg_replace('/([^' . PONYDOCS_PRODUCTMANUAL_LEGALCHARS . ']+)/', '', $shortName);
    // TODO: It's silly to do this twice (the other is in LoadManualsForProduct().
    //       We should get the manual object from PonyDocsProductManual
    $static = FALSE;
    if (strpos($shortName, PONYDOCS_PRODUCT_STATIC_PREFIX) === 0) {
        $static = TRUE;
        $manualName = substr($manualName, strlen(PONYDOCS_PRODUCT_STATIC_PREFIX));
    }
    $productName = PonyDocsProduct::GetSelectedProduct();
    $version = PonyDocsProductVersion::GetSelectedVersion($productName);
    // Don't cache Documentation:[product]:Manuals pages because when we switch selected version the content will come from cache
    $parser->disableCache();
    // If static, link to Special:StaticDocImport
    if ($static) {
        $output = "<p><a href=\"" . str_replace('$1', "Special:StaticDocImport/{$productName}/{$manualName}", $wgArticlePath) . "\" style=\"font-size: 1.3em;\">{$longName}</a></p>\n" . "<span style=\"padding-left: 20px;\">Click manual to manage static documentation.</span>\n";
        // Otherwise, link to TOC for current Version OR add a link to create a new TOC if none exists
    } else {
        // TODO: We should call PonyDocsTOC.php or maybe PonyDocsProductManual to see if there's a TOC in this manual
        //       or maybe actually get the manual object and query it
        $dbr = wfGetDB(DB_SLAVE);
        $res = $dbr->select(array('categorylinks', 'page'), 'page_title', array('cl_from = page_id', 'page_namespace = "' . NS_PONYDOCS . '"', "cl_to = 'V:{$productName}:{$version}'", 'cl_type = "page"', "cl_sortkey LIKE '" . $dbr->strencode(strtoupper($productName)) . ':' . $dbr->strencode(strtoupper($manualName)) . "TOC%'"), __METHOD__);
        if (!$res->numRows()) {
            /**
             * Link to create new TOC page -- should link to current version TOC and then add message to explain.
             */
            $output = '<p><a href="' . str_replace('$1', PONYDOCS_DOCUMENTATION_NAMESPACE_NAME . ':' . $productName . ':' . $manualName . 'TOC' . $version, $wgArticlePath) . '" style="font-size: 1.3em;">' . $longName . "</a></p>\n <span style=\"padding-left: 20px;\">Click manual to create TOC for current version (" . $version . ").</span>\n";
        } else {
            $row = $dbr->fetchObject($res);
            $output = '<p><a href="' . str_replace('$1', PONYDOCS_DOCUMENTATION_NAMESPACE_NAME . ":{$row->page_title}", $wgArticlePath) . '" style="font-size: 1.3em;">' . $longName . "</a></p>\n";
        }
    }
    if ($categories != '') {
        $output .= "<br>Categories: {$categories}";
    }
    return $parser->insertStripItem($output, $parser->mStripState);
}
function BugzillaRender($input, array $args, Parser $parser, $frame = null)
{
    global $wgBugzillaRESTURL;
    // We don't want the page to be cached
    // TODO: Not sure if we need this
    $parser->disableCache();
    // TODO: Figure out to have the parser not do anything to our output
    // mediawiki docs are wrong :-(
    // error_log(print_r($parser->mStripState, true));
    // $parser->mStripState->addItem( 'nowiki', 'NOWIKI', true);
    // 'noparse' => true, 'isHTML' => true, 'markerType' => 'nowiki' );
    $input = $parser->recursiveTagParse($input, $frame);
    // Create a new bugzilla object
    $bz = Bugzilla::create($args, $input, $parser->getTitle());
    // Show the desired output (or an error if there was one)
    return $bz->render();
}
 /**
  * Renders bs:whoisonline:popup output.
  * @param Parser $oParser MediaWiki parser object.
  * @param string $sLinkTitle Label of the link that is the anchor of the flyout
  * @return array Rendered HTML and flags. Used by magic word function hook as well as by onUsersLinkTag.
  */
 public function onUsersLink($oParser, $sLinkTitle = '')
 {
     $oParser->disableCache();
     wfProfileIn('BS::' . __METHOD__);
     $sLinkTitle = BsCore::sanitize($sLinkTitle, '', BsPARAMTYPE::STRING);
     if (empty($sLinkTitle)) {
         $sLinkTitle = wfMessage('bs-whoisonline-widget-title')->plain();
     }
     $oWhoIsOnlineTagView = new ViewWhoIsOnlineTag();
     $oWhoIsOnlineTagView->setOption('title', $sLinkTitle);
     $oWhoIsOnlineTagView->setPortlet($this->getPortlet());
     $sOut = $oWhoIsOnlineTagView->execute();
     wfProfileOut('BS::' . __METHOD__);
     return $oParser->insertStripItem($sOut, $oParser->mStripState);
 }
 /**
  * Callback for MediaWiki Parser. Renders the list of wanted articles
  * @param string $sInput The content of the tag. Usually empty string.
  * @param array $aAttributes An Array of given attributes
  * @param Parser $oParser The MediaWiki parser object
  * @return string The rendered <bs:wantedarticles /> tag
  */
 public function onWantedArticlesTag($sInput, $aAttributes, $oParser)
 {
     $oParser->disableCache();
     $oErrorListView = new ViewTagErrorList($this);
     $sDefaultTitle = wfMessage('bs-wantedarticle-tag-default-title')->plain();
     $iCount = BsCore::sanitizeArrayEntry($aAttributes, 'count', 5, BsPARAMTYPE::INT);
     $sSort = BsCore::sanitizeArrayEntry($aAttributes, 'sort', 'time', BsPARAMTYPE::STRING);
     $sOrder = BsCore::sanitizeArrayEntry($aAttributes, 'order', 'DESC', BsPARAMTYPE::STRING);
     $sTitle = BsCore::sanitizeArrayEntry($aAttributes, 'title', $sDefaultTitle, BsPARAMTYPE::STRING);
     $sType = BsCore::sanitizeArrayEntry($aAttributes, 'type', 'list', BsPARAMTYPE::STRING);
     //Validation
     $oValidationICount = BsValidator::isValid('IntegerRange', $iCount, array('fullResponse' => true, 'lowerBoundary' => 1, 'upperBoundary' => 30));
     if ($oValidationICount->getErrorCode()) {
         $oErrorListView->addItem(new ViewTagError('count: ' . $oValidationICount->getI18N()));
     }
     if (!in_array($sSort, array('', 'time', 'title'))) {
         $oErrorListView->addItem(new ViewTagError('sort: ' . wfMessage('bs-wantedarticle-sort-value-unknown')->plain()));
     }
     if (!in_array($sOrder, array('', 'ASC', 'DESC'))) {
         $oErrorListView->addItem(new ViewTagError('order: ' . wfMessage('bs-wantedarticle-order-value-unknown')->plain()));
     }
     if ($oErrorListView->hasItems()) {
         return $oErrorListView->execute();
     }
     //Create list
     $aWishList = $this->getTitleListFromTitle($this->getDataSourceTemplateArticle()->getTitle());
     switch ($sSort) {
         case 'title':
             $aTitleList = $this->sortWishListByTitle($aWishList);
             break;
         case 'time':
         default:
             $aTitleList = $this->getDefaultTitleList($aWishList);
     }
     if ($sOrder == 'ASC') {
         $aTitleList = array_reverse($aTitleList);
     }
     $oWishListView = new ViewWantedArticleTag();
     $oWishListView->setTitle($sTitle)->setType($sType)->setOrder($sOrder)->setSort($sSort)->setCount($iCount)->setList($aTitleList);
     return $oWishListView->execute();
 }
 /**
  * Handles the Parser Hook for TagExtensions
  * @param string $sInput Content of $lt;pagesvisited /&gt; from MediaWiki Framework
  * @param array $aAttributes Attributes of &lt;pagesvisited /&gt; from MediaWiki Framework
  * @param Parser $oParser Parser object from MediaWiki Framework
  * @return string HTML list of recently visited pages
  */
 public function onPagesVisitedTag($sInput, $aAttributes, $oParser)
 {
     $oParser->disableCache();
     $oErrorListView = new ViewTagErrorList($this);
     $iCount = BsCore::sanitizeArrayEntry($aAttributes, 'count', 5, BsPARAMTYPE::INT);
     $iMaxTitleLength = BsCore::sanitizeArrayEntry($aAttributes, 'maxtitlelength', 20, BsPARAMTYPE::INT);
     $sNamespaces = BsCore::sanitizeArrayEntry($aAttributes, 'namespaces', 'all', BsPARAMTYPE::STRING | BsPARAMOPTION::CLEANUP_STRING);
     $sSortOrder = BsCore::sanitizeArrayEntry($aAttributes, 'order', 'time', BsPARAMTYPE::STRING | BsPARAMOPTION::CLEANUP_STRING);
     //Validation
     $oValidationICount = BsValidator::isValid('IntegerRange', $iCount, array('fullResponse' => true, 'lowerBoundary' => 1, 'upperBoundary' => 30));
     if ($oValidationICount->getErrorCode()) {
         $oErrorListView->addItem(new ViewTagError('count: ' . $oValidationICount->getI18N()));
     }
     $oValidationIMaxTitleLength = BsValidator::isValid('IntegerRange', $iMaxTitleLength, array('fullResponse' => true, 'lowerBoundary' => 5, 'upperBoundary' => 50));
     if ($oValidationIMaxTitleLength->getErrorCode()) {
         $oErrorListView->addItem(new ViewTagError('maxtitlelength: ' . $oValidationIMaxTitleLength->getI18N()));
     }
     if ($oErrorListView->hasItems()) {
         return $oErrorListView->execute();
     }
     $iCurrentNamespaceId = $oParser->getTitle()->getNamespace();
     $oListView = $this->makePagesVisitedWikiList($iCount, $sNamespaces, $iCurrentNamespaceId, $iMaxTitleLength, $sSortOrder);
     $sOut = $oListView->execute();
     if ($oListView instanceof ViewTagErrorList) {
         return $sOut;
     } else {
         return $this->mCore->parseWikiText($sOut, $this->getTitle());
     }
 }
 /**
  *
  * @param type $input
  * @param type $args
  * @param Parser $parser
  * @return type
  */
 public function onMagicWordBsCountCharacters($input, $args, $parser)
 {
     $parser->disableCache();
     if (empty($input)) {
         $oErrorView = new ViewTagError(wfMessage('bs-countthings-error-no-input')->plain());
         return $oErrorView->execute();
     }
     $sMode = isset($args['mode']) ? str_replace(' ', '', $args['mode']) : 'all';
     $aModes = explode(',', $sMode);
     $aAvailableModes = array('chars', 'words', 'pages', 'all');
     $sOut = '';
     $bValidModeProvided = false;
     foreach ($aModes as $sMode) {
         if (!in_array($sMode, $aAvailableModes)) {
             $oErrorView = new ViewTagError(wfMessage('bs-countthings-error-invalid-mode', $sMode)->plain());
             $sOut .= $oErrorView->execute();
             continue;
         }
         $bValidModeProvided = true;
     }
     if ($bValidModeProvided == false) {
         $aModes = array('all');
     }
     $aTitleTexts = explode(',', $input);
     foreach ($aTitleTexts as $sTitleText) {
         $oTitle = Title::newFromText(trim($sTitleText));
         if ($oTitle == null || $oTitle->exists() == false) {
             $oErrorView = new ViewTagError(wfMessage('bs-countthings-error-not-exist', $sTitleText)->plain());
             $sOut .= $oErrorView->execute();
             continue;
         }
         $sContent = BsPageContentProvider::getInstance()->getContentFromTitle($oTitle);
         //Old: last revision
         $oCountView = new ViewCountCharacters();
         $oCountView->setTitle($oTitle);
         if (in_array('all', $aModes)) {
             $iChars = strlen(preg_replace("/\\s+/", " ", $sContent));
             $iWords = sizeof(explode(' ', $sContent));
             $iPages = ceil($iChars / 2000);
             $oCountView->setChars($iChars);
             $oCountView->setWords($iWords);
             $oCountView->setPages($iPages);
             $sOut .= $oCountView->execute();
             continue;
         }
         // TODO RBV (17.02.12 15:34): Find better logic for this...
         if (in_array('chars', $aModes)) {
             $iChars = strlen(preg_replace("/\\s+/", " ", $sContent));
             $oCountView->setChars($iChars);
         }
         if (in_array('words', $aModes)) {
             $iChars = strlen(preg_replace("/\\s+/", " ", $sContent));
             $iWords = sizeof(explode(' ', $sContent));
             $oCountView->setWords($iWords);
         }
         if (in_array('pages', $aModes)) {
             $iChars = strlen(preg_replace("/\\s+/", " ", $sContent));
             $iWords = sizeof(explode(' ', $sContent));
             $iPages = ceil($iChars / 2000);
             $oCountView->setPages($iPages);
         }
         $sOut .= $oCountView->execute();
     }
     return $sOut;
 }
 /**
  *
  * @param type $input
  * @param string $args
  * @param Parser $parser
  * @return string
  */
 public function onTagBsPageAccess($input, $args, $parser)
 {
     //ignore access tag on mainpage or it will break all ajax calls without title param
     if ($parser->getTitle()->equals(Title::newMainPage()) === true) {
         return '';
     }
     $parser->disableCache();
     if (!isset($args['groups'])) {
         $oErrorView = new ViewTagError(wfMessage('bs-pageaccess-error-no-groups-given')->escaped());
         return $oErrorView->execute();
     }
     $sOldAccessGroups = $parser->getOutput()->getProperty('bs-page-access');
     if ($sOldAccessGroups) {
         $args['groups'] = $sOldAccessGroups . "," . $args['groups'];
     }
     $parser->getOutput()->setProperty('bs-page-access', $args['groups']);
     return '';
 }
Exemple #18
0
 /**
  * Renrder the spark div.
  *
  * @since 0.1
  *
  * @param Parser $parser
  *
  * @return string
  */
 public function render(Parser $parser, $frame)
 {
     global $wgVersion;
     global $wgOut;
     global $egSparkScriptPath;
     global $wgResourceModules;
     // What is loaded already?
     static $loadedJsses = array();
     wfDebugLog('myextension', 'Parameters alright? ' . print_r($this->parameters, true));
     if (array_key_exists(egSparkQuery, $this->parameters)) {
         $query = htmlspecialchars($this->parameters[egSparkQuery]);
         // Before that, shall we allow internal parse, at least for the query?
         // We replace variables, templates etc.
         $query = $parser->replaceVariables($query, $frame);
         //$query = $parser->recursiveTagParse( $query );
         // Replace special characters
         $query = str_replace(array('&lt;', '&gt;'), array('<', '>'), $query);
         unset($this->parameters[egSparkQuery]);
         // Depending on the format, we possibly need to add modules
         if (array_key_exists(egSparkFormat, $this->parameters)) {
             $format = htmlspecialchars($this->parameters[egSparkFormat]);
             // Remove everything before "spark.XXX"
             $format = substr($format, strpos($format, "spark."));
             // Remove .js at the end
             $format = str_replace(array('.js'), array(''), $format);
             $module = 'ext.' . $format;
             // for older versions of MW, different
             if (version_compare($wgVersion, '1.17', '<')) {
                 if (isset($wgResourceModules) && array_key_exists($module, $wgResourceModules)) {
                     // only if not already loaded
                     if (!isset($loadedJsses[$module])) {
                         // scripts
                         foreach ($wgResourceModules[$module]['scripts'] as $script) {
                             $wgOut->addScript('<script src="' . $egSparkScriptPath . "/" . $script . '" type="text/javascript"></script>');
                             wfDebugLog('spark', "AddScript:" . ' <script src="' . $egSparkScriptPath . "/" . $script . '" type="text/javascript"></script>');
                         }
                         // css
                         foreach ($wgResourceModules[$module]['styles'] as $style) {
                             $wgOut->addScript('<link rel="stylesheet" href="' . $egSparkScriptPath . "/" . $style . '" type="text/css" />');
                             wfDebugLog('spark', "AddLink:" . ' <link rel="stylesheet" href="' . $egSparkScriptPath . "/" . $style . '" type="text/css" />');
                         }
                         $loadedJsses[$module] = true;
                     }
                 }
             } else {
                 // $wgResourceModules might not exist
                 if (isset($wgResourceModules) && array_key_exists($module, $wgResourceModules)) {
                     // TODO: Do we need to check, whether module has been added already?
                     $parser->getOutput()->addModules($module);
                 }
             }
         }
         $html = '<div class="spark" data-spark-query="' . $query . '" ' . Html::expandAttributes($this->parameters) . ' >' . (is_null($this->contents) ? '' : htmlspecialchars($this->contents)) . '</div>';
         // In MW 1.17 there seems to be the problem that ? after an empty space is replaced by a non-breaking space (&#160;) Therefore we remove all spaces before ? which should still make the SPARQL query work
         $html = preg_replace('/[ \\t]+(\\?)/', '$1', $html);
         // for older versions of MW, different
         if (version_compare($wgVersion, '1.17', '<')) {
             $parser->disableCache();
             return $html;
         } else {
             return array($parser->insertStripItem($html, $parser->mStripState), 'noparse' => true, 'isHTML' => true);
         }
     } else {
         return Html::element('i', array(), wfMsg('spark-missing-query'));
     }
 }
 /**
  * Renders the BsTagToplist tag. Called by parser function.
  * @param string $sInput Inner HTML of BsTagMToplist tag. Not used.
  * @param array $aArgs List of tag attributes.
  * @param Parser $oParser MediaWiki parser object
  * @return string HTML output that is to be displayed.
  */
 public function onTagToplist($sInput, $aArgs, $oParser)
 {
     $oParser->disableCache();
     $oParser->getOutput()->setProperty('bs-toplist', FormatJson::encode($aArgs));
     return $this->getToplist($sInput, $aArgs, $oParser);
 }
function drawDiagram(Parser $parser, PPFrame $frame)
{
    global $wgTitle;
    $sumEditing = 0;
    $pagesList = CDParameters::getInstance()->getPagesList();
    $pageWithChanges = array();
    foreach ($pagesList as $thisPageTitle) {
        $names = getPageEditorsFromDb($thisPageTitle);
        $changesForUsersForPage = getCountsOfEditing($names);
        $thisPageTitleKey = $thisPageTitle->getText();
        if ($thisPageTitle->getNsText() != "") {
            $thisPageTitleKey = $thisPageTitle->getNsText() . ":" . $thisPageTitleKey;
            // we can't use Title object this is a key with an array so we generate the Ns:Name key
        }
        $pageWithChanges[$thisPageTitleKey] = $changesForUsersForPage;
        $sumEditing += evaluateCountOfAllEdits($changesForUsersForPage);
    }
    $text = drawPreamble();
    foreach ($pageWithChanges as $thisPageTitleKey => $changesForUsersForPage) {
        $drawer = CDDrawerFactory::getDrawer($changesForUsersForPage, $sumEditing, $thisPageTitleKey);
        $text .= $drawer->draw();
    }
    $text .= "}</graphviz>";
    // $text = getPie($changesForUsers, $sumEditing, $thisPageTitle);
    $parser->disableCache();
    $parser->setTitle(Title::newFromText("Main_page"));
    $frame->getTitle(Title::newFromText("Main_page"));
    $text = $parser->recursiveTagParse($text, $frame);
    //this stuff just render my page
    return $text;
}