public function getActiveFilterText() { $this->getActiveValues(); $aI18NValues = array(); foreach ($this->aActiveValues as $sValue) { $aI18NValues[] = BsNamespaceHelper::getNamespaceName($sValue); } return implode(", ", $aI18NValues); }
/** * Sets parameters for more complex options in preferences * @param string $sAdapterName Name of the adapter, e.g. MW * @param BsConfig $oVariable Instance of variable * @return array Preferences options */ public function runPreferencePlugin($sAdapterName, $oVariable) { $aPrefs = array(); if ($oVariable->getName() === 'DefScopeUser') { $aPrefs = array('options' => array(wfMessage('bs-extendedsearch-pref-scope-text')->plain() => 'text', wfMessage('bs-extendedsearch-pref-scope-title')->plain() => 'title')); } elseif ($oVariable->getName() === 'MltNS') { $aPrefs = array('type' => 'multiselectex', 'options' => BsNamespaceHelper::getNamespacesForSelectOptions(array(NS_SPECIAL, NS_MEDIA))); } return $aPrefs; }
public function buildLinksNs() { $oUser = $this->getUser(); $set = new ViewFormElementFieldset(); $set->setLabel(wfMessage('bs-blog-blog')->plain()); $select = new ViewFormElementSelectbox(); $select->setId('selFeedNsBlog'); $select->setName('selFeedNsBlog'); $select->setLabel(wfMessage('bs-ns')->plain()); $aNamespacesTemp = BsNamespaceHelper::getNamespacesForSelectOptions(array(NS_SPECIAL, NS_MEDIA, NS_BLOG, NS_BLOG_TALK, NS_FILE)); $aNamespaces = array(); foreach ($aNamespacesTemp as $index => $name) { if ($index % 2 == 0) { $aNamespaces[$index] = $name; } } $oSpecialRSS = SpecialPage::getTitleFor('RSSFeeder'); $sUserName = $oUser->getName(); $sUserToken = $oUser->getToken(); foreach ($aNamespaces as $key => $name) { $select->addData(array('value' => $oSpecialRSS->getLinkUrl(array('Page' => 'blog', 'ns' => $key, 'u' => $sUserName, 'h' => $sUserToken)), 'label' => $name)); } $btn = new ViewFormElementButton(); $btn->setId('btnFeedNsBlog'); $btn->setName('btnFeedNsBlog'); $btn->setType('button'); $btn->setLabel(wfMessage('bs-rssfeeder-submit')->plain()); $set->addItem($select); $set->addItem($btn); return $set; }
public static function ajaxGetActivatedNamespacesForCombobox() { if (BsCore::checkAccessAdmission('edit') === false) { return true; } $aNamespaces = array(); $aNamespaces[] = array('namespace_id' => -99, 'namespace_text' => BsNamespaceHelper::getNamespaceName(-99, true)); $aActivatedNamespaces = BsConfig::get('MW::ResponsibleEditors::ActivatedNamespaces'); foreach ($aActivatedNamespaces as $iNamespaceId) { $aNamespaces[] = array('namespace_id' => $iNamespaceId, 'namespace_text' => BsNamespaceHelper::getNamespaceName($iNamespaceId, true)); } return '{ namespaces: ' . json_encode($aNamespaces) . ' }'; }
public static function ajaxGetNamespaceFilter() { $aResult = array("success" => false, "errors" => array(), "message" => '', "data" => array()); global $wgUser; if (!$wgUser->isAllowed('read')) { $aResult["message"] = wfMessage('bs-statistics-not-allowed')->plain(); return json_encode($aResult); } foreach (BsNamespaceHelper::getNamespacesForSelectOptions(array(-2, -1)) as $key => $name) { $aResult['data'][] = array('key' => $key, 'displaytitle' => $name); } $aResult['success'] = true; return json_encode($aResult); }
public static function addCategoriesToArticle($iArticleId) { if (BsCore::checkAccessAdmission('read') === false) { return FormatJson::encode(array('success' => false)); } if (wfReadOnly()) { global $wgReadOnly; return FormatJson::encode(array('success' => false, 'msg' => wfMessage('bs-readonly', $wgReadOnly)->plain())); } $sTags = RequestContext::getMain()->getRequest()->getVal('categories'); $aTags = empty($sTags) ? array() : explode(',', $sTags); $oTitle = Title::newFromID($iArticleId); if (is_null($oTitle) || !$oTitle->exists()) { $oRequest = RequestContext::getMain()->getRequest(); $sPageName = $oRequest->getVal("page_name", ""); $oTitle = Title::newFromText($sPageName); } $sCat = BsNamespaceHelper::getNamespaceName(NS_CATEGORY); $sText = BsPageContentProvider::getInstance()->getContentFromTitle($oTitle, Revision::RAW); // Remove all before adding $sPattern = '#^\\[\\[' . $sCat . ':.*?\\]\\]#im'; $sText = preg_replace($sPattern, '', $sText); if (!empty($aTags)) { foreach ($aTags as $sTag) { $sText .= "\n[[" . $sCat . ":{$sTag}]]"; } } $oWikiPage = new WikiPage($oTitle); $oUser = RequestContext::getMain()->getUser(); $oContent = new WikitextContent($sText); $oStatus = $oWikiPage->doEditContent($oContent, "", 0, false, $oUser); if (!$oStatus->isGood()) { return FormatJson::encode(array('success' => false, 'msg' => $oStatus->getMessage())); } return FormatJson::encode(array('success' => true)); }
/** * Returns a json encoded list of available templates * @return bool allow other hooked methods to be executed. Always true. */ public static function getTemplates() { if (BsCore::checkAccessAdmission('wikiadmin') === false) { return true; } global $wgRequest; $iLimit = $wgRequest->getInt('limit', 25); $iStart = $wgRequest->getInt('start', 0); $sSort = $wgRequest->getVal('sort', 'user_name'); $sDirection = $wgRequest->getVal('dir', 'ASC'); switch ($sSort) { case 'label': $sSortField = 'pt_label'; break; case 'desc': $sSortField = 'pt_desc'; break; case 'targetns': $sSortField = 'pt_target_namespace'; break; case 'template': $sSortField = 'pt_template_title'; break; default: $sSortField = 'pt_label'; break; } $dbr = wfGetDB(DB_SLAVE); $res = $dbr->select(array('bs_pagetemplate'), array('pt_id', 'pt_label', 'pt_desc', 'pt_target_namespace', 'pt_template_title', 'pt_template_namespace'), array(), __METHOD__, array('ORDER BY' => $sSortField . ' ' . $sDirection, 'LIMIT' => $iLimit, 'OFFSET' => $iStart)); $aData = array(); $aData['templates'] = array(); while ($row = $res->fetchObject()) { $tmp = array(); $tmp['id'] = $row->pt_id; $tmp['label'] = $row->pt_label; $tmp['desc'] = $row->pt_desc; $tmp['targetns'] = BsNamespaceHelper::getNamespaceName($row->pt_target_namespace, true); $tmp['targetnsid'] = $row->pt_target_namespace; $oTitle = Title::newFromText($row->pt_template_title, $row->pt_template_namespace); $tmp['template'] = '<a href="' . $oTitle->getFullURL() . '" target="_blank" ' . ($oTitle->exists() ? '' : 'class="new"') . '>' . $oTitle->getFullText() . '</a>'; $tmp['templatename'] = $row->pt_template_title; $tmp['templatens'] = $row->pt_template_namespace; $aData['templates'][] = $tmp; } $rescount = $dbr->selectRow('bs_pagetemplate', 'COUNT( pt_id ) AS cnt', array()); $aData['totalCount'] = $rescount->cnt; return json_encode($aData); }
/** * Adds Notifications preferences to the echo section * @param User $user * @param array $preferences * @return boolean */ public function onGetPreferences($user, array &$preferences) { $preferences['MW::Notifications::NotifyNoMinor'] = array('type' => 'toggle', 'label-message' => 'bs-notifications-pref-notifynominor', 'section' => 'echo/echo-extended'); $preferences['MW::Notifications::Active'] = array('type' => 'toggle', 'label-message' => 'bs-notifications-pref-active', 'section' => 'echo/echo-extended'); // ugly workaraound for mw's handling of get default options from multivaluefields $sNotifyDefault = $user->getOption('MW::Notifications::NotifyNS', false) ? $user->getOption('MW::Notifications::NotifyNS') : array(0); $preferences['MW::Notifications::NotifyNS'] = array('type' => 'multiselectex', 'label-message' => 'bs-notifications-pref-notifyns', 'section' => 'echo/echo-extended', 'options' => BsNamespaceHelper::getNamespacesForSelectOptions(array(NS_SPECIAL, NS_MEDIA)), 'default' => $sNotifyDefault); return true; }
public function buildLinksNs() { global $wgUser; $set = new ViewFormElementFieldset(); $set->setLabel(wfMessage('bs-ns')->plain()); $select = new ViewFormElementSelectbox(); $select->setId('selFeedNs'); $select->setName('selFeedNs'); $select->setLabel(wfMessage('bs-ns')->plain()); $aNamespaces = BsNamespaceHelper::getNamespacesForSelectOptions(array(NS_SPECIAL, NS_MEDIA)); $oSpecialRSS = SpecialPage::getTitleFor('RSSFeeder'); $sUserName = $wgUser->getName(); $sUserToken = $wgUser->getToken(); foreach ($aNamespaces as $key => $name) { $select->addData(array('value' => $oSpecialRSS->getLinkUrl(array('Page' => 'namespace', 'ns' => $key, 'u' => $sUserName, 'h' => $sUserToken)), 'label' => $name)); } $btn = new ViewFormElementButton(); $btn->setId('btnFeedNs'); $btn->setName('btnFeedNs'); $btn->setType('button'); $btn->setLabel(wfMessage('bs-rssfeeder-submit')->plain()); $set->addItem($select); $set->addItem($btn); return $set; }
public static function setupLockmodePermissions() { global $wgAdditionalGroups, $wgGroupPermissions, $wgNamespacePermissionLockdown; // return directly if the settings got already checked in this session and the state of Lockmode didn't change. $oRequest = RequestContext::getMain()->getRequest(); $bLockmodeActive = BsConfig::get('MW::PermissionManager::Lockmode'); if ($oRequest->getSessionData('bsLockmodeIsSetup') === $bLockmodeActive) { return true; } $oRequest->setSessionData('bsLockmodeIsSetup', $bLockmodeActive); $bSave = false; if (!$bLockmodeActive) { if (isset($wgGroupPermissions[self::$sPmLockModeGroup]) && !empty($wgGroupPermissions[self::$sPmLockModeGroup])) { unset($wgGroupPermissions[self::$sPmLockModeGroup]); $bSave = true; } if (is_array($wgNamespacePermissionLockdown)) { foreach ($wgNamespacePermissionLockdown as $iNsIndex => $aNsRights) { foreach ($aNsRights as $sRight => $aGroups) { if (!in_array(self::$sPmLockModeGroup, $aGroups)) { continue; } $key = array_search(self::$sPmLockModeGroup, $aGroups); if ($key !== false) { unset($wgNamespacePermissionLockdown[$iNsIndex][$sRight][$key]); if (empty($wgNamespacePermissionLockdown[$iNsIndex][$sRight])) { unset($wgNamespacePermissionLockdown[$iNsIndex][$sRight]); } $bSave = true; } } if (empty($wgNamespacePermissionLockdown[$iNsIndex])) { unset($wgNamespacePermissionLockdown[$iNsIndex]); } } } if ($bSave) { self::writeGroupSettings($wgGroupPermissions, $wgNamespacePermissionLockdown); } return true; } $wgAdditionalGroups[self::$sPmLockModeGroup] = array(); foreach (BsNamespaceHelper::getNamespacesForSelectOptions(array(NS_MEDIA, NS_SPECIAL)) as $nsKey => $nsName) { // skip mediawiki namespaces if (BsConfig::get('MW::PermissionManager::SkipSystemNS') && $nsKey <= 15) { continue; } if (!isset($wgGroupPermissions[self::$sPmLockModeGroup])) { $wgGroupPermissions[self::$sPmLockModeGroup] = array(); } $aAvailablePermissions = User::getAllRights(); foreach ($aAvailablePermissions as $permissionName) { if (!isset($wgGroupPermissions[self::$sPmLockModeGroup][$permissionName])) { $wgGroupPermissions[self::$sPmLockModeGroup][$permissionName] = true; $bSave = true; } if (isset($wgNamespacePermissionLockdown[$nsKey][$permissionName])) { if (!in_array(self::$sPmLockModeGroup, $wgNamespacePermissionLockdown[$nsKey][$permissionName])) { $wgNamespacePermissionLockdown[$nsKey][$permissionName] = array_unique(array_merge($wgNamespacePermissionLockdown[$nsKey][$permissionName], array(self::$sPmLockModeGroup))); $bSave = true; } } else { $wgNamespacePermissionLockdown[$nsKey][$permissionName] = array(self::$sPmLockModeGroup); $bSave = true; } } } if ($bSave) { self::writeGroupSettings($wgGroupPermissions, $wgNamespacePermissionLockdown); } return true; }
/** * Calculate the data for the NamespaceManager store and put them to the ajax output. * @param string $output the ajax output (have to be JSON) */ public static function getData() { if (BsCore::checkAccessAdmission('wikiadmin') === false) { return true; } global $wgContLang; $aResults = array(); $aNamespaces = $wgContLang->getNamespaces(); foreach ($aNamespaces as $iNs => $sNamespace) { if ($sNamespace === '') { $sNamespace = BsNamespaceHelper::getNamespaceName($iNs); } if ($iNs === -2 || $iNs === -1) { continue; } $aResults[] = array('id' => $iNs, 'name' => $sNamespace); } wfRunHooks('NamespaceManager::getNamespaceData', array(&$aResults)); $oRequest = RequestContext::getMain()->getRequest(); $iLimit = $oRequest->getInt('limit', 25); $iStart = $oRequest->getInt('start', 0); $sSort = $oRequest->getVal('sort', '[{"property":"id","direction":"DESC"}]'); self::$aSortConditions = FormatJson::decode($sSort); self::$aSortConditions = self::$aSortConditions[0]; usort($aResults, 'NamespaceManager::namespaceManagerRemoteSort'); $aLimitedResults = array(); $iResultCount = count($aResults); $iMax = $iStart + $iLimit > $iResultCount ? $iResultCount : $iStart + $iLimit; for ($i = $iStart; $i < $iMax; $i++) { $aLimitedResults[] = $aResults[$i]; } $aReturn = array('totalCount' => $iResultCount, 'success' => true, 'results' => $aLimitedResults); return FormatJson::encode($aReturn); }
/** * Generates result entires for autocomplete * @param array $aDocuments Array of Apache_solr_Documents * @param string $sSearchString Given search string * @param integer $iNum Number of Results * @param mixed $vNsSearch false or integer namespace id * @param array $aResults Reference to results array */ private static function generateAutocompleteResults($aDocuments, $sSearchString, $iNum, $vNsSearch, &$aResults) { $sLabelText = ''; foreach ($aDocuments as $oDoc) { if ($oDoc->namespace != '999') { $iNamespace = $oDoc->namespace == '1000' ? NS_SPECIAL : $oDoc->namespace; $oTitle = Title::makeTitle($iNamespace, $oDoc->title); } else { continue; } if (!$oTitle->userCan('read')) { continue; } $sLabelText = self::highlightTitle($oTitle, $sSearchString); // Adding namespace if ($oTitle->getNamespace() !== NS_MAIN) { $sLabelText = BsNamespaceHelper::getNamespaceName($oTitle->getNamespace()) . ':' . $sLabelText; } //If namespace is in searchstring remove it from display if ($vNsSearch !== false) { $sNamespace = BsNamespaceHelper::getNamespaceName($vNsSearch); $sLabelText = str_replace($sNamespace . ':', '', $sLabelText); } $oItem = new stdClass(); $oItem->id = ++$iNum; $oItem->value = $oTitle->getPrefixedText(); $oItem->label = $sLabelText; $oItem->type = $oDoc->type; $oItem->link = $oTitle->getFullURL(); $oItem->attr = ''; $aResults[] = $oItem; } }
/** * Gets the recently visited pages of the current user. * @param int $iCount The number of pages to display * @param string $sNamespaces Comma separated list of requested namespaces, i.e. "1,5,Category,101" * @param int $iCurrentNamespaceId To determin wether the current namespace is in the list of requested namespaces * @param string $sSortOrder Defines the sorting of the list. 'time|pagename', default is 'time' * @return ViewBaseElement Contains the list in its _data member. The predefined template is '*[[{LINK}|{TITLE}]]\n' */ private function makePagesVisitedWikiList($iCount = 5, $sNamespaces = 'all', $iCurrentNamespaceId = 0, $iMaxTitleLength = 20, $sSortOrder = 'time') { $oCurrentUser = $this->getUser(); if (is_null($oCurrentUser)) { return null; } // in CLI //$sCacheKey = md5( $oCurrentUser->getName().$iCount.$sNamespaces.$iCurrentNamespaceId.$iMaxTitleLength ); //if( isset( self::$prResultListViewCache[$sCacheKey] ) ) return self::$prResultListViewCache[$sCacheKey]; $oErrorListView = new ViewTagErrorList($this); $oErrorView = null; $aConditions = array(); $aNamespaceIndexes = array(0); try { $aNamespaceIndexes = BsNamespaceHelper::getNamespaceIdsFromAmbiguousCSVString($sNamespaces); //Returns array of integer indexes } catch (BsInvalidNamespaceException $oException) { $aInvalidNamespaces = $oException->getListOfInvalidNamespaces(); $oVisitedPagesListView = new ViewBaseElement(); $oVisitedPagesListView->setTemplate('<ul><li><em>{TEXT}</em></li></ul>' . "\n"); $iCount = count($aInvalidNamespaces); $sNs = implode(', ', $aInvalidNamespaces); $sErrorMsg = wfMessage('bs-pagesvisited-error-nsnotvalid', $iCount, $sNs)->text(); $oVisitedPagesListView->addData(array('TEXT' => $sErrorMsg)); //self::$prResultListViewCache[$sCacheKey] = $oVisitedPagesListView; return $oVisitedPagesListView; } $aConditions = array('wo_user_id' => $oCurrentUser->getId(), 'wo_action' => 'view'); $aConditions[] = 'wo_page_namespace IN (' . implode(',', $aNamespaceIndexes) . ')'; //Add IN clause to conditions-array $aConditions[] = 'wo_page_namespace != -1'; // TODO RBV (24.02.11 13:54): Filter SpecialPages because there are difficulties to list them $aOptions = array('GROUP BY' => 'wo_page_id, wo_page_namespace, wo_page_title', 'ORDER BY' => 'MAX(wo_timestamp) DESC'); if ($sSortOrder == 'pagename') { $aOptions['ORDER BY'] = 'wo_page_title ASC'; } //If the page the extension is used on appears in the result set we have to fetch one row more than neccessary. if (in_array($iCurrentNamespaceId, $aNamespaceIndexes)) { $aOptions['OFFSET'] = 1; } $aFields = array('wo_page_id', 'wo_page_namespace', 'wo_page_title'); $sTable = 'bs_whoisonline'; $dbr = wfGetDB(DB_SLAVE); global $wgDBtype; if ($wgDBtype == 'oracle') { $sRowNumField = 'rnk'; $sTable = mb_strtoupper($dbr->tablePrefix() . $sTable); $sFields = implode(',', $aFields); $sConditions = $dbr->makeList($aConditions, LIST_AND); $aOptions['ORDER BY'] = $sSortOrder == 'pagename' ? $aOptions['ORDER BY'] : 'wo_timestamp DESC'; $res = $dbr->query("SELECT " . $sFields . " FROM (\n\t\t\t\t\t\t\t\t\t\t\tSELECT " . $sFields . ", row_number() over (order by " . $aOptions['ORDER BY'] . ") " . $sRowNumField . "\n\t\t\t\t\t\t\t\t\t\t\tFROM " . $sTable . "\n\t\t\t\t\t\t\t\t\t\t\tWHERE " . $sConditions . "\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\tWHERE " . $sRowNumField . " BETWEEN (0) AND (" . $iCount . ") GROUP BY " . $aOptions["GROUP BY"] . ""); } else { $res = $dbr->select($sTable, $aFields, $aConditions, __METHOD__, $aOptions); } $oVisitedPagesListView = new ViewBaseElement(); $oVisitedPagesListView->setTemplate('*{WIKILINK}' . "\n"); $iItems = 1; foreach ($res as $row) { if ($iItems > $iCount) { break; } $oVisitedPageTitle = Title::newFromID($row->wo_page_id); /* // TODO RBV (24.02.11 13:52): Make SpecialPages work... $oVisitedPageTitle = ( $row->wo_page_namespace != NS_SPECIAL ) ? Title::newFromID( $row->wo_page_id ) //: SpecialPage::getTitleFor( $row->wo_page_title ); : Title::makeTitle( NS_SPECIAL, $row->wo_page_title ); */ if ($oVisitedPageTitle == null || $oVisitedPageTitle->exists() === false || $oVisitedPageTitle->quickUserCan('read') === false) { continue; } $sDisplayTitle = BsStringHelper::shorten($oVisitedPageTitle->getPrefixedText(), array('max-length' => $iMaxTitleLength, 'position' => 'middle')); $oVisitedPagesListView->addData(array('WIKILINK' => BsLinkProvider::makeEscapedWikiLinkForTitle($oVisitedPageTitle, $sDisplayTitle))); $iItems++; } //$dbr->freeResult( $res ); //self::$prResultListViewCache[$sCacheKey] = $oVisitedPagesListView; return $oVisitedPagesListView; }
/** * Generate a link to a wiki page for a given result * @param object $oDocument Apache_Solr_Document * @param object $oTitle Title of wiki page * @param object $oParser Parser * @return string Anchor link to the wiki page */ private function getWikiLink($oDocument, $oTitle, $oParser) { $sHtml = null; if (isset($this->oResponse->highlighting->{$oDocument->uid}->titleWord)) { $sHtml = $this->oResponse->highlighting->{$oDocument->uid}->titleWord[0]; } elseif (isset($this->oResponse->highlighting->{$oDocument->uid}->titleReverse)) { $sHtml = $this->oResponse->highlighting->{$oDocument->uid}->titleReverse[0]; } if (!is_null($sHtml)) { if ($oDocument->namespace != '0' && $oDocument->namespace != '998' && $oDocument->namespace != '999') { $sHtml = BsNamespaceHelper::getNamespaceName($oDocument->namespace) . ':' . $sHtml; } $sHtml = str_replace('_', ' ', $sHtml); } $sSearchLink = Linker::link($oTitle, $sHtml, $aCustomAttribs = array('class' => 'bs-extendedsearch-result-headline'), array(), array('known')); if (isset($this->oResponse->highlighting->{$oDocument->uid}->sections)) { $sSection = strip_tags($this->oResponse->highlighting->{$oDocument->uid}->sections[0], '<em>'); $sSectionAnchor = $oParser->guessSectionNameFromWikiText($sSection); $sSectionLink = BsLinkProvider::makeLink($oTitle, $sSection, array(), array(), array('known')); $aMatches = array(); preg_match('#.*?href="(.*?)".*?#', $sSectionLink, $aMatches); if (isset($aMatches[1])) { $sAnchor = $aMatches[1] . $sSectionAnchor; $sSectionLink = str_replace($aMatches[1], $sAnchor, $sSectionLink); } $sSearchLink .= ' <span class="bs-extendedsearch-sectionresult">(' . wfMessage('bs-extendedsearch-section')->plain() . ' ' . $sSectionLink . ')</span>'; } return $sSearchLink; }
/** * Sets parameters for more complex options in preferences * @param string $sAdapterName Name of the adapter, e.g. MW * @param BsConfig $oVariable Instance of variable * @return array Preferences options */ public function runPreferencePlugin($sAdapterName, $oVariable) { wfProfileIn('BS::' . __METHOD__); $aPrefs = array(); switch ($oVariable->getName()) { case 'disableNS': global $wgContLang; $aExcludeNmsps = BsConfig::get('MW::VisualEditor::defaultNoContextNS'); foreach ($wgContLang->getNamespaces() as $sNamespace) { $iNsIndex = $wgContLang->getNsIndex($sNamespace); if (!MWNamespace::isTalk($iNsIndex)) { continue; } $aExcludeNmsps[] = $iNsIndex; } $aPrefs['type'] = 'multiselectex'; $aPrefs['options'] = BsNamespaceHelper::getNamespacesForSelectOptions($aExcludeNmsps); break; default: } wfProfileOut('BS::' . __METHOD__); return $aPrefs; }
/** * Renders the pagetemplates form which is displayed when creating a new article * @param bool $bReturnHTML If set, the form is returned as HTML, otherwise as wiki code. * @return string The rendered output */ protected function renderPageTemplates() { global $wgDBtype; $oTitle = $this->getTitle(); // if we are not on a wiki page, return. This is important when calling import scripts that try to create nonexistent pages, e.g. importImages if (!is_object($oTitle)) { return true; } $aRes = array(); $aOutNs = array(); $dbr = wfGetDB(DB_SLAVE); $aConds = array(); if (BsConfig::get('MW::PageTemplates::HideIfNotInTargetNs')) { if ($wgDBtype == 'postgres') { $aConds[] = "pt_target_namespace IN ('" . $oTitle->getNamespace() . "', '-99')"; } else { $aConds[] = 'pt_target_namespace IN (' . $oTitle->getNamespace() . ', -99)'; } } if ($wgDBtype == 'postgres') { $aFields = array("pt_template_title, pt_template_namespace, pt_label, pt_desc, pt_target_namespace"); } else { $aFields = array('pt_template_title', 'pt_template_namespace', 'pt_label', 'pt_desc', 'pt_target_namespace'); } $res = $dbr->select(array('bs_pagetemplate'), $aFields, $aConds, __METHOD__, array('ORDER BY' => 'pt_label')); // There is always one template for empty page it is added some lines beneath that $iCount = $dbr->numRows($res) + 1; $sOut = wfMessage('bs-pagetemplates-choose-template', $iCount)->parse(); $sOutAll = ''; $oTargetNsTitle = null; $sOut .= '<br /><br /><ul><li>'; $sOut .= BsLinkProvider::makeLink($oTitle, wfMessage('bs-pagetemplates-empty-page')->plain(), array(), array('preload' => '')); $sOut .= '<br />' . wfMessage('bs-pagetemplates-empty-page-desc')->plain(); $sOut .= '</li></ul>'; $oSortingTitle = Title::makeTitle(NS_MEDIAWIKI, 'PageTemplatesSorting'); $vOrder = BsPageContentProvider::getInstance()->getContentFromTitle($oSortingTitle); $vOrder = explode('*', $vOrder); $vOrder = array_map('trim', $vOrder); if ($res && $dbr->numRows($res) > 0) { while ($row = $dbr->fetchObject($res)) { $aRes[] = $row; } } $dbr->freeResult($res); foreach ($aRes as $row) { $oNsTitle = Title::makeTitle($row->pt_template_namespace, $row->pt_template_title); // TODO MRG (06.09.11 12:53): -99 is "all namespaces". Pls use a more telling constant if (BsConfig::get('MW::PageTemplates::ForceNamespace') && $row->pt_target_namespace != "-99" || $row->pt_target_namespace == $oTitle->getNamespace() || BsConfig::get('MW::PageTemplates::HideIfNotInTargetNs') == false) { $sNamespaceName = BsNamespaceHelper::getNamespaceName($row->pt_target_namespace); if (!isset($aOutNs[$sNamespaceName])) { $aOutNs[$sNamespaceName] = array(); } if (BsConfig::get('MW::PageTemplates::ForceNamespace')) { $oTargetNsTitle = Title::makeTitle($row->pt_target_namespace, $oTitle->getText()); } else { $oTargetNsTitle = $oTitle; } $sLink = BsLinkProvider::makeLink($oTargetNsTitle, $row->pt_label, array(), array('preload' => $oNsTitle->getPrefixedText())); $sLink = '<li>' . $sLink; if ($row->pt_desc) { $sLink .= '<br/>' . $row->pt_desc; } $sLink .= '</li>'; $aOutNs[$sNamespaceName][] = array('link' => $sLink, 'id' => $row->pt_target_namespace); } elseif ($row->pt_target_namespace == "-99") { $sLink = BsLinkProvider::makeLink($oTitle, $row->pt_label, array(), array('preload' => $oNsTitle->getPrefixedText())); $sOutAll .= '<li>' . $sLink; if ($row->pt_desc) { $sOutAll .= '<br />' . $row->pt_desc; } $sOutAll .= '</li>'; } } if (!empty($vOrder)) { $aTmp = array(); foreach ($vOrder as $key => $value) { if (empty($value)) { continue; } if (array_key_exists($value, $aOutNs)) { $aTmp[$value] = $aOutNs[$value]; } } $aOutNs = $aTmp + array_diff_key($aOutNs, $aTmp); } $aLeftCol = array(); $aRightCol = array(); foreach ($aOutNs as $sNs => $aTmpOut) { foreach ($aTmpOut as $key => $aAttribs) { $sNamespaceName = BsNamespaceHelper::getNamespaceName($aAttribs['id']); if ($aAttribs['id'] == $oTitle->getNamespace() || $aAttribs['id'] == -99) { $aLeftCol[$sNamespaceName][] = '<ul>' . $aAttribs['link'] . '</ul>'; } else { $aRightCol[$sNamespaceName][] = '<ul>' . $aAttribs['link'] . '</ul>'; } } } if ($sOutAll !== '') { $sSectionGeneral = wfMessage('bs-pagetemplates-general-section')->plain(); $aLeftCol[$sSectionGeneral][] = '<ul>' . $sOutAll . '</ul>'; } $sOut .= '<br />'; if (!empty($aLeftCol) || !empty($aRightCol) && BsConfig::get('MW::PageTemplates::HideIfNotInTargetNs') == false) { $sOut .= '<table><tr>'; if (!empty($aLeftCol)) { $sOut .= '<td style="vertical-align:top;">'; foreach ($aLeftCol as $sNamespace => $aHtml) { if ($sNamespace == wfMessage('bs-ns_all')->plain()) { $sNamespace = wfMessage('bs-pagetemplates-general-section')->plain(); } $sOut .= '<br />'; $sOut .= '<h3>' . $sNamespace . '</h3>'; $sOut .= implode('', $aHtml); } $sOut .= '</td>'; } if (BsConfig::get('MW::PageTemplates::HideIfNotInTargetNs') == false) { if (!empty($aRightCol)) { $sOut .= '<td style="vertical-align:top;">'; foreach ($aRightCol as $sNamespace => $aHtml) { $sOut .= '<br />'; $sOut .= '<h3>' . $sNamespace . '</h3>'; $sOut .= implode('', $aHtml); } $sOut .= '</td>'; } } $sOut .= '</tr></table>'; } return $sOut; }
/** * Generates a list of the most visisted pages * @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 getToplist($sInput, $aArgs, $oParser) { $sCat = BsCore::sanitizeArrayEntry($aArgs, 'cat', '', BsPARAMTYPE::STRING); $sNs = BsCore::sanitizeArrayEntry($aArgs, 'ns', '', BsPARAMTYPE::STRING); $iCount = BsCore::sanitizeArrayEntry($aArgs, 'count', 10, BsPARAMTYPE::INT); $sPeriod = BsCore::sanitizeArrayEntry($aArgs, 'period', 'alltime', BsPARAMTYPE::STRING); $iPortletPeriod = BsCore::sanitizeArrayEntry($aArgs, 'portletperiod', 0, BsPARAMTYPE::INT); $bAlltime = true; $oDbr = wfGetDB(DB_SLAVE); if (in_array($sPeriod, array('week', 'month')) || in_array($iPortletPeriod, array(7, 30))) { $aTables = array('bs_whoisonline'); $aColumns = array('COUNT( wo_page_title ) AS page_counter', 'wo_page_title', 'wo_page_namespace'); $aConditions = array('wo_action' => 'view'); $aOptions = array('GROUP BY' => 'wo_page_title', 'ORDER BY' => 'page_counter DESC'); $aJoinConditions = array(); if ($sPeriod === 'week' || $iPortletPeriod === 7) { $iTimestamp = wfTimestamp(TS_UNIX) - 7 * 24 * 60 * 60; $aConditions[] = 'wo_timestamp >= ' . $iTimestamp; } $bAlltime = false; } else { $aTables = array('page'); $aColumns = array('page_title', 'page_counter', 'page_namespace'); $aConditions = array(); $aOptions = array('ORDER BY' => 'page_counter DESC'); $aJoinConditions = array(); } if (!empty($sCat)) { $aCategories = explode(',', $sCat); $aCategories = array_map('trim', $aCategories); $aCategories = str_replace(' ', '_', $aCategories); if ($bAlltime === false) { $aColumns[] = 'wo_page_id'; $aJoinConditions = array('categorylinks' => array('INNER JOIN ', 'wo_page_id = cl_from')); $aTables[] = 'categorylinks'; $aConditions['cl_to'] = $aCategories; } else { $aTables[] = 'categorylinks'; $aConditions[] = 'page_id = cl_from'; $aConditions['cl_to'] = $aCategories; } } if (!empty($sNs) || $sNs === '0') { // string 0 is empty $aNamespaces = BsNamespaceHelper::getNamespaceIdsFromAmbiguousCSVString($sNs); if (!empty($aNamespaces)) { $sField = $bAlltime ? 'page_namespace' : 'wo_page_namespace'; $aConditions[$sField] = $aNamespaces; } } $res = $oDbr->select($aTables, $aColumns, $aConditions, __METHOD__, $aOptions, $aJoinConditions); if ($oDbr->numRows($res) > 0) { $bCategories = false; if (!empty($aCategories)) { $bCategories = true; $aPrefixedCategories = array(); foreach ($aCategories as $sCategory) { $sCategory = str_replace(' ', '_', $sCategory); $sCat = Title::makeTitle(NS_CATEGORY, $sCategory); $aPrefixedCategories[] = $sCat->getPrefixedDBKey(); } } $aList = array(); $aInList = array(); $iCurrCount = 0; if ($bAlltime === false) { foreach ($res as $row) { if ($iCurrCount === $iCount) { break; } if (empty($row->wo_page_title)) { continue; } $oTitle = Title::makeTitle($row->wo_page_namespace, $row->wo_page_title); if (!$oTitle->quickUserCan('read')) { continue; } if ($bCategories === true) { $aParents = array_keys($oTitle->getParentCategories()); $aResult = array_diff($aPrefixedCategories, $aParents); if (!empty($aResult)) { continue; } } if (in_array($oTitle->getPrefixedText(), $aInList)) { continue; } $aInList[] = $oTitle->getPrefixedText(); $sLink = BsLinkProvider::makeLink($oTitle); $aList['<li>' . $sLink . ' (' . $row->page_counter . ')</li>'] = (int) $row->page_counter; $iCurrCount++; } arsort($aList); $aList = array_keys($aList); array_unshift($aList, '<ol>'); } else { $aList[] = '<ol>'; foreach ($res as $row) { if ($iCurrCount == $iCount) { break; } if ($row->page_counter == '0') { continue; } $oTitle = Title::makeTitle($row->page_namespace, $row->page_title); if (!$oTitle->quickUserCan('read')) { continue; } if ($bCategories === true) { $aParents = array_keys($oTitle->getParentCategories()); $aResult = array_diff($aPrefixedCategories, $aParents); if (!empty($aResult)) { continue; } } if (in_array($oTitle->getPrefixedText(), $aInList)) { continue; } $aInList[] = $oTitle->getPrefixedText(); $sLink = BsLinkProvider::makeLink($oTitle); $aList[] = '<li>' . $sLink . ' (' . $row->page_counter . ')</li>'; $iCurrCount++; } } $aList[] = '</ol>'; $oDbr->freeResult($res); return "\n" . implode("\n", $aList); } $oDbr->freeResult($res); return wfMessage('bs-smartlist-no-entries')->plain(); }
/** * Reads in searchstring and checks if a namespace is in it * @param string $sSearchString given searchstring * @param string $sSolrSearchString the solr searchstring * @param array $aQueryFq solr filter query * @param boolean $bWtihTag flag for tagging * @return int|boolean id of namespace or false */ public function checkSearchstringForNamespace($sSearchString, &$sSolrSearchString, &$aQueryFq, $bWtihTag = false) { if (empty($sSearchString)) { return false; } if (substr_count($sSearchString, ':') === 0) { return false; } $aParts = explode(':', $sSearchString); if (count($aParts) !== 2) { return false; } if (empty($aParts[0]) || empty($aParts[1])) { return false; } $iNamespace = BsNamespaceHelper::getNamespaceIndex($aParts[0]); if (empty($iNamespace) || !is_int($iNamespace)) { return false; } // Check for special namespace if ($iNamespace === NS_SPECIAL) { $iNamespace = 1000; } $sSolrSearchString = $aParts[1]; $aQueryFq[] = $bWtihTag ? '{!tag=na}namespace:(' . $iNamespace . ')' : 'namespace:(' . $iNamespace . ')'; return $iNamespace; }
/** * Send file via HTTP. */ public static function getFile() { global $wgUploadDirectory; $sRawFilePath = RequestContext::getMain()->getRequest()->getVal('f'); // Some extensions (e.g. Social Profile) add params with ? to filename $aRawFilePathPcs = preg_split("/\\?.*=/", $sRawFilePath); $sRawFilePath = $aRawFilePathPcs[0]; $sUploadDirectory = realpath($wgUploadDirectory); if (empty($sUploadDirectory)) { throw new MWException('$wgUploadDirectory is empty. This should never happen!'); } // Switch between f=File:Foo.png and f=/3/33/Foo.png style requests $aFileNamespaceNames = BsNamespaceHelper::getNamespaceNamesAndAliases(NS_FILE); if (preg_match('#^(.*?):(.*)$#', $sRawFilePath, $aMatch) && in_array($aMatch[1], $aFileNamespaceNames)) { $oTitle = Title::newFromText($aMatch[2], NS_FILE); $oImg = wfLocalFile($oTitle); if (!is_null($oImg)) { $oImgRepoLocalRef = $oImg->getRepo()->getLocalReference($oImg->getPath()); if (!is_null($oImgRepoLocalRef)) { $sFilePath = realpath($oImgRepoLocalRef->getPath()); } } } else { $sFilePath = realpath($sUploadDirectory . $sRawFilePath); } $aPathParts = pathinfo($sFilePath); $sFileName = $aPathParts['basename']; $sFileExt = isset($aPathParts['extension']) ? strtolower($aPathParts['extension']) : ''; if (strpos($sFilePath, $sUploadDirectory) !== 0 || preg_match('/^\\.ht/', $sFileName) || empty($sFilePath) || !is_file($sFilePath) || !is_readable($sFilePath)) { header('HTTP/1.0 404 Not Found'); exit; } // At this point we have a valid and readable file path in $sFilePath. // Now create a File object to get some properties if (strstr($sFilePath, 'thumb')) { $sFindFileName = preg_replace("#(\\d*px-)#", '', $sFileName); } else { $sFindFileName = $sFileName; } $aOptions = array('time' => false); //TODO: maybe check for "/archive" in $sFilePath, too. But this migth be a config setting, so do not hardcode $isArchive = preg_match('#^\\d{14}!#si', $sFindFileName); //i.e. "20120724112914!Adobe-reader-x-tco-de.pdf" if ($isArchive) { $aFilenameParts = explode('!', $sFindFileName, 2); $sFindFileName = $aFilenameParts[1]; $aOptions['time'] = $aFilenameParts[0]; } $oFile = RepoGroup::singleton()->findFile($sFindFileName, $aOptions); // We need to do some additional checks if file extension is not on whitelist if (!in_array($sFileExt, BsConfig::get('MW::SecureFileStore::FileExtensionWhitelist'))) { // Check for MediaWiki right 'viewfiles' global $wgUser; if (!$wgUser->isAllowed('viewfiles')) { header('HTTP/1.0 403 Forbidden'); exit; } // Check if user has access to file's meta page if ($oFile) { if (!$oFile->getTitle()->userCan('read')) { header('HTTP/1.0 403 Forbidden'); exit; } } } // User is allowed to retrieve file. Get things going. # If file is not in MW's repo try to guess MIME type $sFileMime = $oFile ? $oFile->getMimeType() : MimeMagic::singleton()->guessMimeType($sFilePath, false); $sFileDispo = BsConfig::get('MW::SecureFileStore::DefaultDisposition'); if (in_array($sFileExt, BsConfig::get('MW::SecureFileStore::DispositionAttachment'))) { $sFileDispo = 'attachment'; } if (in_array($sFileExt, BsConfig::get('MW::SecureFileStore::DispositionInline'))) { $sFileDispo = 'inline'; } $aFileStat = stat($sFilePath); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $aFileStat['mtime']) . ' GMT'); header("Content-Type: {$sFileMime}"); header("Content-Disposition: {$sFileDispo}; filename=\"{$sFileName}\""); header("Cache-Control: no-cache,must-revalidate", true); //Otherwise IE might deliver old version if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $sModSince = preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']); $sSinceTime = strtotime($sModSince); if ($aFileStat['mtime'] <= $sSinceTime) { ini_set('zlib.output_compression', 0); header("HTTP/1.0 304 Not Modified"); exit; } } // IE6/IE7 cannot handle download of zip-files that are aditionally gzipped by the Apache // just put it in the header and tell apache to immediately flush => and gzip is disabled if ($sFileMime == 'application/zip') { header('Content-Length: ' . $aFileStat['size']); flush(); } // Send the file already ;-) readfile($sFilePath); exit; }