/** * Renders a form field that allows to create a new blog entry. * @return string HTML of form. */ public function renderShowNewEntryField() { global $wgScriptPath, $wgUser; $sId = 'blog' . self::$iFormElementCount; self::$iFormElementCount++; $sParentpage = $this->getOption('parentpage') ? $this->getOption('parentpage') : ''; $aOut = array(); $aOut[] = '<script type="text/javascript">'; $aOut[] = 'hw_' . $sId . '_submit = function() {'; $aOut[] = ' pagename = "' . $sParentpage . '" + document.getElementById("' . $sId . 'Input").value;'; //$aOut[] = ' if(!check_pagename(pagename)) return false;'; $aOut[] = ' pagename = pagename.replace(" ", "_");'; if ($wgUser->isLoggedIn() || BsConfig::get('MW::Blog::ShowTagFormWhenNotLoggedIn') != true) { $aOut[] = ' url = unescape("' . $wgScriptPath . '/index.php?title=' . ($this->getOption('namespace') ? $this->getOption('namespace') . ':' : '') . '"+pagename+"%26action"+"=edit"+"%26blogcat=' . $this->getOption('blogcat') . '");'; } else { $aOut[] = ' url = unescape("' . $wgScriptPath . '/index.php%3Ftitle=special:userlogin%26returnto=' . $this->getOption('namespace') . ':"+pagename);'; } $aOut[] = ' window.location.href = url;'; $aOut[] = '}'; $aOut[] = '</script>'; $aOut[] = '<div class="bs-blog-wrapper clearfix">'; $aOut[] = ' <form action="#" id="' . $sId . 'form" action="get" onsubmit="hw_' . $sId . '_submit();return false;">'; $aOut[] = ' <div class="bs-blog-form-center">'; $aOut[] = ' <h2 class="bs-blog-header">' . wfMessage('bs-blog-form-title-text')->plain() . '</h2>'; $aOut[] = ' <input id="' . $sId . 'Input" class="bs-blog-newentry-input" name="newpage" type="text" value="' . wfMessage('bs-blog-form-inline-text')->plain() . '" onfocus="if (this.value==\'' . wfMessage('bs-blog-form-inline-text')->plain() . '\') this.value=\'\';" />'; $aOut[] = ' <input type="hidden" name="blogcat" value="' . $this->getOption('blogcat') . '" />'; $aOut[] = ' <input type="submit" name="go" class="bs-blog-newentry-submit" id="' . $sId . 'Button" value="' . wfMessage('bs-blog-form-button-text')->plain() . '" onclick="hw_' . $sId . '_submit(); return false;"/> '; $aOut[] = ' </div>'; $aOut[] = ' </form>'; $aOut[] = '</div>'; return implode("", $aOut); }
/** * Constructor of BsFilterCategory class * @param BsDiagram $oDiagram Instance of diagram the filter is used with. * @param array $aDefaultValues List of strings */ public function __construct($oDiagram, $aDefaultValues = null) { parent::__construct($oDiagram, $aDefaultValues); $this->sLabel = wfMsg('bs-statistics-filter-user'); $this->aAvailableValues = $this->loadAvailableValues(); $this->aDefaultValues = BsConfig::get('MW::Statistics::ExcludeUsers'); }
/** * This method actually generates the output * @param array $params List of parameters * @return string HTML output */ public function execute($params = false) { $sTargetId = $this->getTargetId() . '-target'; $sLink = Html::element('a', array('class' => 'bs-tooltip-link', 'id' => $this->getTargetId(), 'data-bs-tt-title' => wfMessage('bs-whoisonline-widget-title')->plain(), 'data-bs-tt-target' => $sTargetId, 'data-bs-tt-maxheight' => BsConfig::get('MW::WhoIsOnline::LimitCount') * 20), $this->getOption('title')); $sTarget = Html::rawElement('div', array('class' => 'bs-tooltip-body bs-whoisonline-portlet', 'id' => $sTargetId), $this->oPortlet ? $this->oPortlet->execute() : ''); $sOut = $sLink . '<div class="bs-tooltip">' . $sTarget . '</div>'; return $sOut; }
/** * The default contructor of the SpecialUniversalExport class */ function __construct() { parent::__construct('UniversalExport', 'universalexport-export', true); $this->oOutputPage = $this->getOutput(); //Set up default parameters and metadata $this->aParams = BsConfig::get('MW::UniversalExport::ParamsDefaults'); $this->aParams['webroot-filesystempath'] = BsCore::getMediaWikiWebrootPath(); $this->aMetadata = FormatJson::decode(BsConfig::get('MW::UniversalExport::MetadataDefaults'), true); //Set up Black- and Whitelists $this->aCategoryWhitelist = BsConfig::get('MW::UniversalExport::CategoryWhitelist'); $this->aCategoryBlacklist = BsConfig::get('MW::UniversalExport::CategoryBlacklist'); }
/** * Extracts the parameters from the querystring and merges it wir the * default and overrige settings of the UniversalExport Extension. * @param array $aParams */ public static function getParamsFromQueryString(&$aParams) { global $wgRequest; $aParamsOverrides = BsConfig::get('MW::UniversalExport::ParamsOverrides'); $aParams = array_merge($aParams, $wgRequest->getArray('ue', array())); $aParams = array_merge($aParams, $aParamsOverrides); $aParams['oldid'] = $wgRequest->getVal('oldid', 0); $sDirection = $wgRequest->getVal('direction', ''); if (!empty($sDirection)) { $aParams['direction'] = $sDirection; } }
/** * 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(); switch ($oVariable->getName()) { case 'DefaultTemplate': $aParams = array('template-path' => BsConfig::get('MW::UEModulePDF::TemplatePath')); $aPrefs = array('type' => 'select', 'options' => BsPDFTemplateProvider::getTemplatesForSelectOptions($aParams)); break; default: break; } return $aPrefs; }
/** * Renders the form that is used to enter new shouts * @return string HTML of the form */ protected function renderMessageForm() { global $wgScriptPath; $aOut = array(); $aOut[] = '<form id="bs-sb-form" class="clearfix">'; $aOut[] = '<textarea id="bs-sb-message" maxlength="' . BsConfig::get('MW::ShoutBox::MaxMessageLength') . '">' . wfMessage('bs-shoutbox-message')->plain() . '</textarea>'; $aOut[] = '<br />'; $aOut[] = '<img id="bs-sb-loading" src="' . $wgScriptPath . '/extensions/BlueSpiceFoundation/resources/bluespice/images/bs-ajax-loader-bar-blue.gif" alt="Loading..."/>'; $aOut[] = '<input id="bs-sb-send" type="submit" value="' . wfMessage('bs-shoutbox-shout')->plain() . '" />'; $aOut[] = '<p class="bs-sb-textarea-additionalinfo">'; $aOut[] = '<span id="bs-sb-charactercounter"></span>'; $aOut[] = '</p>'; $aOut[] = '</form>'; return implode("\n", $aOut); }
/** * Initiate URLs so they use the correct protocol. */ protected function _initUrls() { wfProfileIn('BS::' . __METHOD__); $this->_morelikethisUrl = $this->_constructUrl(BsConfig::get('MW::ExtendedSearch::SolrCore') . self::MORELIKETHIS_SERVLET); $this->_spellcheckUrl = $this->_constructUrl(BsConfig::get('MW::ExtendedSearch::SolrCore') . self::SPELLCHECK_SERVLET); parent::_initUrls(); if ($this->bUseDifferentProtocolThanHttp) { $this->_updateUrl = str_ireplace('http://', $this->sProtocol . '://', $this->_updateUrl); $this->_searchUrl = str_ireplace('http://', $this->sProtocol . '://', $this->_searchUrl); $this->_threadsUrl = str_ireplace('http://', $this->sProtocol . '://', $this->_threadsUrl); $this->_spellcheckUrl = str_ireplace('http://', $this->sProtocol . '://', $this->_spellcheckUrl); $this->_morelikethisUrl = str_ireplace('http://', $this->sProtocol . '://', $this->_morelikethisUrl); } wfProfileOut('BS::' . __METHOD__); }
/** * Prepares array of files to be indexed * @return true. */ public function crawl() { $sDirectories = BsConfig::get('MW::ExtendedSearch::ExternalRepo'); if ($sDirectories === '') { return $sDirectories; } $aDirectories = explode(',', $sDirectories); foreach ($aDirectories as $sDirectory) { $sDir = trim($sDirectory); if (!is_dir($sDir)) { continue; } $this->readInFiles($sDir); } return $this->aFiles; }
/** * @param SkinTemplate $sktemplate a collection of views. Add the view that needs to be displayed * @param BaseTemplate $tpl currently logged in user. Not used in this context. * @return bool always true */ public function onSkinTemplateOutputPageBeforeExec(&$sktemplate, &$tpl) { if (BsConfig::get('MW::BlueSpiceProjectFeedbackHelper::Active') == false) { return true; } if (!in_array('sysop', $sktemplate->getUser()->getGroups())) { return true; } $oView = new ViewBlueSpiceProjectFeedbackHelperPanel(); if (isset($tpl->data['dataAfterContent'])) { $tpl->data['dataAfterContent'] .= $oView->execute(); } else { $tpl->data['dataAfterContent'] = $oView->execute(); } return true; }
/** * Getter for $aNavigationSites array * @param boolean $bForceReload * @return array */ public static function getNavigationSites($bForceReload = false) { if (!$bForceReload && !is_null(self::$aNavigationSites)) { return self::$aNavigationSites; } self::$aNavigationSites = array(); $oTopBarMenuTitle = Title::makeTitle(NS_MEDIAWIKI, 'TopBarMenu'); if (is_null($oTopBarMenuTitle) || !$oTopBarMenuTitle->exists()) { return self::$aNavigationSites; } $sContent = BsPageContentProvider::getInstance()->getContentFromTitle($oTopBarMenuTitle); $aLines = explode("\n", trim($sContent)); $iMaxMainEntries = BsConfig::get('MW::TopMenuBarCustomizer::NumberOfMainEntries'); $iMaxSubEntries = BsConfig::get('MW::TopMenuBarCustomizer::NumberOfSubEntries'); $iAllowedLevels = BsConfig::get('MW::TopMenuBarCustomizer::NuberOfLevels'); self::$aNavigationSites = self::parseArticleContentLines($aLines, $iAllowedLevels, $iMaxMainEntries, $iMaxSubEntries); return self::$aNavigationSites; }
public function __construct($oMainControl) { parent::__construct($oMainControl); // Set file types to be indexed $vTempFileTypes = BsConfig::get('MW::ExtendedSearch::IndexFileTypes'); $vTempFileTypes = str_replace(array(' ', ';'), array('', ','), $vTempFileTypes); $vTempFileTypes = explode(',', $vTempFileTypes); foreach ($vTempFileTypes as $value) { $this->aFileTypes[$value] = true; } unset($vTempFileTypes); // Maximum file size in MB $iMaxFileSize = (int) ini_get('post_max_size'); if (empty($iMaxFileSize) || $iMaxFileSize <= 0) { $iMaxFileSize = 32; } $this->iMaxDocSize = $iMaxFileSize * 1024 * 1024; // Make bytes out of it }
/** * Gets a DOMDocument, searches it for files, uploads files and markus to webservice and generated PDF. * @param DOMDocument $oHtmlDOM The source markup * @return string The resulting PDF as bytes */ public function createPDF(&$oHtmlDOM) { $this->findFiles($oHtmlDOM); $this->uploadFiles(); //HINT: http://www.php.net/manual/en/class.domdocument.php#96055 //But: Formated Output is evil because is will destroy formatting in <pre> Tags! $sHtmlDOM = $oHtmlDOM->saveXML($oHtmlDOM->documentElement); //Save temporary $sTmpHtmlFile = BSDATADIR . DS . 'UEModulePDF' . DS . $this->aParams['document-token'] . '.html'; $sTmpPDFFile = BSDATADIR . DS . 'UEModulePDF' . DS . $this->aParams['document-token'] . '.pdf'; file_put_contents($sTmpHtmlFile, $sHtmlDOM); $aOptions = array('timeout' => 120, 'postData' => array('fileType' => '', 'documentToken' => $this->aParams['document-token'], 'sourceHtmlFile_name' => basename($sTmpHtmlFile), 'sourceHtmlFile' => '@' . $sTmpHtmlFile, 'wikiId' => wfWikiID())); if (BsConfig::get('MW::TestMode')) { $aOptions['postData']['debug'] = "true"; } global $bsgUEModulePDFCURLOptions; $aOptions = array_merge_recursive($aOptions, $bsgUEModulePDFCURLOptions); wfRunHooks('BSUEModulePDFCreatePDFBeforeSend', array($this, &$aOptions, $oHtmlDOM)); $vHttpEngine = Http::$httpEngine; Http::$httpEngine = 'curl'; //HINT: http://www.php.net/manual/en/function.curl-setopt.php#refsect1-function.curl-setopt-notes //Upload HTML source //TODO: Handle $sResponse $sResponse = Http::post($this->aParams['soap-service-url'] . '/UploadAsset', $aOptions); //Now do the rendering //We re-send the paramters but this time without the file. unset($aOptions['postData']['sourceHtmlFile']); unset($aOptions['postData']['fileType']); //We do not want the request to be multipart/formdata because that's more difficult to handle on Servlet-side $aOptions['postData'] = wfArrayToCgi($aOptions['postData']); $vPdfByteArray = Http::post($this->aParams['soap-service-url'] . '/RenderPDF', $aOptions); Http::$httpEngine = $vHttpEngine; if ($vPdfByteArray == false) { wfDebugLog('BS::UEModulePDF', 'BsPDFServlet::createPDF: Failed creating "' . $this->aParams['document-token'] . '"'); } file_put_contents($sTmpPDFFile, $vPdfByteArray); //Remove temporary file if (!BsConfig::get('MW::TestMode')) { unlink($sTmpHtmlFile); unlink($sTmpPDFFile); } return $vPdfByteArray; }
/** * Constructor of BsDiagramNumberOfUsers class */ public function __construct() { parent::__construct(); BsConfig::get('MW::Statistics::ExcludeUsers'); $this->sTitle = wfMessage('bs-statistics-diag-number-of-users')->plain(); $this->sDescription = wfMessage('bs-statistics-diag-number-of-users-desc')->plain(); $this->sTitlex = wfMessage('bs-statistics-label-time')->plain(); $this->sTitley = wfMessage('bs-statistics-label-count')->plain(); $this->sActualGrain = "m"; $this->sModLabel = "M y"; $this->iDataSource = BsDiagram::DATASOURCE_DATABASE; $this->bListable = true; $this->sSqlWhatForDiagram = "count(user_id)"; $this->sSqlWhatForList = "user_name, user_registration"; $this->sSqlFromWhere = "FROM #__user\n\t\t\t\t\t\t\t\tWHERE user_registration @period\n\t\t\t\t\t\t\t\tAND user_id NOT IN (\n\t\t\t\t\t\t\t\t\tSELECT ug_user\n\t\t\t\t\t\t\t\t\tFROM #__user_groups\n\t\t\t\t\t\t\t\t\tWHERE ug_group = 'bot'\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tAND NOT user_name IN (@BsFilterUsers)"; $this->sListLabel = array(wfMessage('bs-statistics-label-name')->plain(), wfMessage('bs-statistics-label-registration')->plain()); $this->sMode = BsDiagram::MODE_AGGREGATED; $this->addFilter(new BsFilterUsers($this)); }
/** * This method actually generates the output * @return string HTML output */ public function execute($params = false) { $aSearchBoxKeyValues = array(); $sInputFields[] = Xml::input('title', false, SpecialPage::getTitleFor('SpecialExtendedSearch')->getFullText(), array('type' => 'hidden')); if (BsConfig::get('MW::ExtendedSearch::SearchFiles')) { $sInputFields[] = Xml::input('search_files', false, 1, array('type' => 'hidden')); } $sValue = isset($this->oSearchRequest->sInput) ? $this->oSearchRequest->sInput : wfMessage('searchsuggest-search')->plain(); $sInputFields[] = Xml::input('q', false, $sValue, array('id' => 'bs-extendedsearch-inputfieldtext-specialpage', 'defaultvalue' => wfMessage('searchsuggest-search')->text())); $sScope = BsConfig::get('MW::ExtendedSearch::DefScopeUser'); $sInputFields[] = Xml::input('search_scope', false, $sScope, array('type' => 'hidden', 'id' => 'bs-search-button-hidden-specialpage')); $sImageTitleButton = Xml::element('div', array('id' => 'bs-extendedsearch-titlebuttonimage-specialpage', 'class' => 'bs-extendedsearch-buttonimage-specialpage'), '', false); $sInputFields[] = Xml::openElement('button', array('type' => 'button', 'title' => wfMessage('bs-extendedsearch-pref-scope-title')->plain(), 'id' => 'bs-search-button-specialpage', 'class' => 'bs-search-button-specialpage')); $sInputFields[] = $sImageTitleButton; $sInputFields[] = Xml::closeElement('button'); $sImageFulltextButton = Xml::element('div', array('id' => 'bs-extendedsearch-fulltextbuttonimage-specialpage', 'class' => 'bs-extendedsearch-buttonimage-specialpage'), '', false); $sInputFields[] = Xml::openElement('button', array('type' => 'button', 'title' => wfMessage('bs-extendedsearch-pref-scope-text')->plain(), 'id' => 'bs-search-fulltext-specialpage', 'class' => 'bs-search-button-specialpage')); $sInputFields[] = $sImageFulltextButton; $sInputFields[] = Xml::closeElement('button'); $sLinkToExtendedPage = Xml::element('a', array('href' => $this->getOption('linkToExtendedPageUri'), 'id' => 'bs-extendedsearch-linktoextendedpage'), wfMessage($this->getOption('linkToExtendedPageMessageKey'))->plain(), false); if ($this->hasItems() === 0) { $sDivSearchDomains = ''; } else { $itemsOut = ''; foreach ($this->_mItems as $item) { $itemsOut .= $item->execute(); } $sDivSearchDomains = Xml::openElement('div', array('class' => 'bs-extendedsearch-domaindiv')) . $itemsOut . Xml::closeElement('div'); } global $wgScript; $aFormAttributes = array('class' => 'bs-search-form', 'id' => 'bs-extendedsearch-form-specialpage', 'action' => $wgScript, 'method' => 'get'); $aForm = array(); $aForm[] = $sLinkToExtendedPage; $aForm[] = Html::openElement('form', $aFormAttributes); $aForm[] = implode("\n", $sInputFields) . $sDivSearchDomains; $aForm[] = Xml::closeElement('form'); return implode("\n", $aForm); }
/** * Checks wether to set Context or not. * @return bool */ private function checkContext() { if (BsConfig::get('MW::Authors::Show') === false) { return false; } $oTitle = $this->getTitle(); if (!is_object($oTitle)) { return false; } if (!$oTitle->exists()) { return false; } // Do only display when user is allowed to read if (!$oTitle->userCan('read')) { return false; } // Do only display in view mode if ($this->getRequest()->getVal('action', 'view') != 'view') { return false; } // Do not display on SpecialPages, CategoryPages or ImagePages if (in_array($oTitle->getNamespace(), array(NS_SPECIAL, NS_CATEGORY, NS_FILE))) { return false; } // Do not display if __NOAUTHORS__ keyword is found $vNoAuthors = BsArticleHelper::getInstance($oTitle)->getPageProp('bs_noauthors'); if ($vNoAuthors === '') { return false; } return true; }
/** * Processes incoming search request */ public function readInSearchRequest() { global $wgCanonicalNamespaceNames, $wgExtraNamespaces, $wgContentNamespaces; $this->aOptions['searchStringRaw'] = $this->oSearchRequest->sInput; $this->aOptions['searchStringOrig'] = ExtendedSearchBase::preprocessSearchInput($this->oSearchRequest->sInput); self::$searchStringRaw = $this->aOptions['searchStringRaw']; $sCustomerId = $this->getCustomerId(); $sLogOp = ' OR '; $aFq = array(); $aBq = array(); $oRequest = RequestContext::getMain()->getRequest(); $scope = $oRequest->getVal('search_scope', BsConfig::get('MW::ExtendedSearch::DefScopeUser')) == 'title' ? 'title' : 'text'; $this->aOptions['scope'] = $scope; $vNamespace = $this->checkSearchstringForNamespace($this->aOptions['searchStringRaw'], $this->aOptions['searchStringOrig'], $aFq, BsConfig::get('MW::ExtendedSearch::ShowFacets')); $this->aOptions['searchStringWildcarded'] = SearchService::wildcardSearchstring($this->aOptions['searchStringOrig']); $this->aOptions['searchStringForStatistics'] = $this->aOptions['searchStringWildcarded']; $aSearchTitle = array('title:(' . $this->aOptions['searchStringOrig'] . ')^5', 'titleWord:(' . $this->aOptions['searchStringOrig'] . ')^2', 'titleReverse:(' . $this->aOptions['searchStringWildcarded'] . ')', 'redirects:(' . $this->aOptions['searchStringOrig'] . ')'); $aSearchText = array('textWord:(' . $this->aOptions['searchStringOrig'] . ')^2', 'textReverse:(' . $this->aOptions['searchStringWildcarded'] . ')', 'sections:(' . $this->aOptions['searchStringOrig'] . ')'); $sSearchStringTitle = implode($sLogOp, $aSearchTitle); $sSearchStringText = implode($sLogOp, $aSearchText); $this->aOptions['searchStringFinal'] = $this->aOptions['scope'] === 'title' ? $sSearchStringTitle : $sSearchStringTitle . $sLogOp . $sSearchStringText; // filter query $aFq[] = 'redirect:0'; $aFq[] = 'special:0'; $aFq[] = 'wiki:(' . $sCustomerId . ')'; // $this->aOptions['namespaces'] HAS TO BE an array with numeric indices of type string! $this->aOptions['namespaces'] = $this->oSearchRequest->aNamespaces; $aNamespaces = array_slice($wgCanonicalNamespaceNames, 2); $aNamespaces = $aNamespaces + $wgExtraNamespaces; $bTagNamespace = false; if ($vNamespace === false) { $this->aOptions['files'] = $this->oSearchRequest->bSearchFiles === true ? true : false; $oUser = RequestContext::getMain()->getUser(); if (!$oUser->getOption('searcheverything')) { if (empty($this->aOptions['namespaces']) && $this->oSearchRequest->bNoSelect === false) { $this->aOptions['namespaces'] = array(); $aOptions = $oUser->getOptions(); foreach ($aOptions as $sOpt => $sValue) { if (strpos($sOpt, 'searchNs') !== false && $sValue == true) { $this->aOptions['namespaces'][] = '' . str_replace('searchNs', '', $sOpt); } } $aAllowedTypes = explode(',', BsConfig::get('MW::ExtendedSearch::IndexFileTypes')); $aAllowedTypes = array_map('trim', $aAllowedTypes); $aSearchFilesFacet = array_intersect($this->oSearchRequest->aType, $aAllowedTypes); if (($this->aOptions['files'] === true || !empty($aSearchFilesFacet)) && $oUser->isAllowed('searchfiles')) { $this->aOptions['namespaces'][] = '999'; $this->aOptions['namespaces'][] = '998'; } } else { $bTagNamespace = true; $aTmp = array(); foreach ($this->aOptions['namespaces'] as $iNs) { if (BsNamespaceHelper::checkNamespacePermission($iNs, 'read') === true) { $aTmp[] = $iNs; } } $this->aOptions['namespaces'] = $aTmp; } } else { if (empty($this->aOptions['namespaces'])) { $aTmp = array(); foreach ($aNamespaces as $iNs) { if (BsNamespaceHelper::checkNamespacePermission($iNs, 'read') === true) { $this->aOptions['namespaces'][] = $iNs; } } } else { $bTagNamespace = true; $aTmp = array(); foreach ($this->aOptions['namespaces'] as $iNs) { if (!BsNamespaceHelper::checkNamespacePermission($iNs, 'read')) { $aTmp[] = $iNs; } } if (!empty($aTmp)) { $this->aOptions['namespaces'] = array_diff($this->aOptions['namespaces'], $aTmp); } } } } else { $bTagNamespace = true; $this->aOptions['namespaces'][] = '' . $vNamespace; } $this->aOptions['namespaces'] = array_unique($this->aOptions['namespaces']); if (!empty($this->aOptions['namespaces'])) { $aFqNamespaces = array(); foreach ($this->aOptions['namespaces'] as $sNamespace) { $aFqNamespaces[] = $sNamespace; if ($sNamespace == '999') { $filesAlreadyAddedInLoopBefore = true; } } if (!isset($filesAlreadyAddedInLoopBefore) && $this->aOptions['files'] === true && $oUser->isAllowed('searchfiles')) { $aFqNamespaces[] = '999'; } $bTagNamespace = true; $aFq[] = BsConfig::get('MW::ExtendedSearch::ShowFacets') ? '{!tag=na}namespace:("' . implode('" "', $aFqNamespaces) . '")' : 'namespace:("' . implode('" "', $aFqNamespaces) . '")'; } // $this->aOptions['cats'] = $this->oSearchRequest->sCat; // string, defaults to '' if 'search_cat' not set in REQUEST $this->aOptions['cats'] = $this->oSearchRequest->sCategories; // array of strings or empty array if (!empty($this->aOptions['cats'])) { if (isset($this->oSearchRequest->sOperator)) { switch ($this->oSearchRequest->sOperator) { case 'AND': $sLogOp = ' AND '; break; default: } } $sFqCategories = BsConfig::get('MW::ExtendedSearch::ShowFacets') ? '{!tag=ca}' : ''; $sFqCategories .= 'cat:("' . implode('"' . $sLogOp . '"', $this->aOptions['cats']) . '")'; $aFq[] = $sFqCategories; } $this->aOptions['type'] = $this->oSearchRequest->aType; if (!empty($this->aOptions['type'])) { $sFqType = BsConfig::get('MW::ExtendedSearch::ShowFacets') ? '{!tag=ty}' : ''; $sFqType .= 'type:("' . implode('"' . $sLogOp . '"', $this->aOptions['type']) . '")'; $aFq[] = $sFqType; } $this->aOptions['editor'] = $this->oSearchRequest->sEditor; if (!empty($this->aOptions['editor'])) { // there may be spaces in name of editor. solr analyses those to two // terms (editor's names) thus we wrap the name into quotation marks // todo: better: in schema.xml define field editor not to be tokenized // at whitespace // but: +editor:("Robert V" "Mathias S") is already split correctly! $sFqEditor = BsConfig::get('MW::ExtendedSearch::ShowFacets') ? '{!tag=ed}' : ''; $sFqEditor .= 'editor:("' . implode('"' . $sLogOp . '"', $this->aOptions['editor']) . '")'; $aFq[] = $sFqEditor; } // Boost query foreach ($wgContentNamespaces as $iNs) { $aBq[] = "namespace:{$iNs}^2"; } // We want that files are also seen as a content namespace $aBq[] = "namespace:999^2"; $searchLimit = BsConfig::get('MW::ExtendedSearch::LimitResults'); $this->aOptions['offset'] = $this->oSearchRequest->iOffset; $this->aOptions['order'] = $this->oSearchRequest->sOrder; $this->aOptions['asc'] = $this->oSearchRequest->sAsc; $this->aOptions['searchLimit'] = $searchLimit == 0 ? 15 : $searchLimit; $this->aOptions['titleExists'] = ExtendedSearchBase::titleExists($this->oSearchRequest->sInput, $this->aOptions); $this->aOptions['bExtendedForm'] = $this->oSearchRequest->bExtendedForm; $this->aSearchOptions['defType'] = 'edismax'; $this->aSearchOptions['fl'] = 'uid,type,title,path,namespace,cat,ts,redirects,overall_type'; $this->aSearchOptions['fq'] = $aFq; $this->aSearchOptions['sort'] = $this->aOptions['order'] . ' ' . $this->aOptions['asc']; $this->aSearchOptions['hl'] = 'on'; $this->aSearchOptions['hl.fl'] = 'titleWord, titleReverse, sections, textWord, textReverse'; $this->aSearchOptions['hl.snippets'] = BsConfig::get('MW::ExtendedSearch::HighlightSnippets'); $this->aSearchOptions['bq'] = implode(' ', $aBq); if (BsConfig::get('MW::ExtendedSearch::ShowFacets')) { $this->aSearchOptions['facet'] = 'on'; $this->aSearchOptions['facet.sort'] = 'false'; $this->aSearchOptions['facet.mincount'] = '1'; $this->aSearchOptions['facet.missing'] = 'true'; $this->aSearchOptions['facet.field'] = array(); $this->aSearchOptions['facet.field'][] = $bTagNamespace === true ? '{!ex=na}namespace' : 'namespace'; $this->aSearchOptions['facet.field'][] = isset($sFqCategories) ? '{!ex=ca}cat' : 'cat'; $this->aSearchOptions['facet.field'][] = isset($sFqType) ? '{!ex=ty}type' : 'type'; $this->aSearchOptions['facet.field'][] = isset($sFqEditor) ? '{!ex=ed}editor' : 'editor'; } }
/** * This method actually generates the output * @param array $aParams not used here * @return string HTML output */ public function execute($aParams = false) { global $wgUser; $sUserName = $this->oUser->getName(); $sUserRealName = $this->oUser->getRealName(); //Fallback for old entries without user_id if ($this->oUser->isAnon()) { $sUserName = $this->sUsername; } $aOut = array(); $aOut[] = '<li class="bs-sb-listitem clearfix" id="bs-sb-' . $this->iShoutID . '">'; $aOut[] = ' <div class="bs-user-image">'; if ($this->oMiniProfile instanceof ViewUserMiniProfile) { $aOut[] = $this->oMiniProfile->execute(); } $aOut[] = ' </div>'; $aOut[] = ' <div class="bs-sb-message">'; $aOut[] = ' <div class="bs-sb-message-head">'; $aOut[] = ' <strong>' . $sUserName . '</strong>'; if (!empty($sUserRealName)) { $aOut[] = ' <span class="bs-sb-meassage-head-small">' . $sUserRealName . '</span>'; } $aOut[] = ' </div>'; if (isset($this->sDate)) { $aOut[] = '<div class="bs-sb-message-time">' . $this->sDate; $aOut[] = '</div> '; } $aOut[] = ' <div class="bs-sb-message-text">' . nl2br($this->sMessage); $aOut[] = ' </div> '; $aOut[] = ' </div>'; $sArchiveButton = ''; $sArchiveButtonEnabled = ' <div class="bs-sb-archive"></div>'; //set button if user has the right to archive if (BsCore::checkAccessAdmission('archiveshoutbox')) { $sArchiveButton = $sArchiveButtonEnabled; } //if setting for "allow own entries to be archived" is set + username == shoutbox-entry-username => set button if (BsConfig::get('MW::ShoutBox::AllowArchive') && $wgUser->getName() == $sUserName) { $sArchiveButton = $sArchiveButtonEnabled; } $aOut[] = $sArchiveButton; $aOut[] = '</li>'; return implode("\n", $aOut); }
/** * Hook handler for LinkBegin * @param Linker $oLinker * @param Title $oTarget * @param string $sHtml * @param array $aCustomAttribs * @param array $aQuery * @param array $aOptions * @param string $sRet * @return boolean Always true to keep hook running */ public function onLinkBegin($oLinker, $oTarget, &$sHtml, &$aCustomAttribs, &$aQuery, &$aOptions, &$sRet) { if (in_array('known', $aOptions)) { return true; } if (!in_array('broken', $aOptions)) { //It's not marked as "known" and not as "broken" so we have to check if ($oTarget->isKnown()) { return true; } } $aExNs = BsConfig::get('MW::PageTemplates::ExcludeNs'); if (in_array($oTarget->getNamespace(), $aExNs)) { return true; } if (!isset($aQuery['preload'])) { $aQuery['action'] = 'view'; } return true; }
/** * Collects metadata and additional resources for this page * @param Title $oTitle * @param DOMDocument $oPageDOM * @param array $aParams * @return array array( 'meta' => ..., 'resources' => ...); */ private static function collectData($oTitle, $oPageDOM, $aParams) { $aMeta = array(); $aResources = array('ATTACHMENT' => array(), 'STYLESHEET' => array(), 'IMAGE' => array()); // TODO RBV (01.02.12 13:51): Handle oldid $aCategories = array(); if ($oTitle->exists()) { // TODO RBV (27.06.12 11:47): Throws an exception. Maybe better use try ... catch instead of $oTitle->exists() $aAPIParams = new FauxRequest(array('action' => 'parse', 'page' => $oTitle->getPrefixedText(), 'prop' => 'images|categories|links')); $oAPI = new ApiMain($aAPIParams); $oAPI->execute(); if (defined('ApiResult::META_CONTENT')) { $aResult = $oAPI->getResult()->getResultData(null, array('BC' => array(), 'Types' => array(), 'Strip' => 'all')); } else { $aResult = $oAPI->getResultData(); } foreach ($aResult['parse']['categories'] as $aCat) { $aCategories[] = $aCat['*']; } } /* //For future use... foreach($aResult['parse']['images'] as $sFileName ) { $oImage = RepoGroup::singleton()->getLocalRepo()->newFile( Title::newFromText( $sFileName, NS_FILE ) ); if( $oImage->exists() ) { $sAbsoluteFileSystemPath = $oImage->getFullPath(); } } */ //Dublin Core: $aMeta['DC.title'] = $oTitle->getPrefixedText(); $aMeta['DC.date'] = wfTimestamp(TS_ISO_8601); // TODO RBV (14.12.10 14:01): Check for conformity. Maybe there is a better way to acquire than wfTimestamp()? //Custom global $wgLang; $sCurrentTS = $wgLang->userAdjust(wfTimestampNow()); $aMeta['title'] = $oTitle->getPrefixedText(); $aMeta['exportdate'] = $wgLang->sprintfDate('d.m.Y', $sCurrentTS); $aMeta['exporttime'] = $wgLang->sprintfDate('H:i', $sCurrentTS); $aMeta['exporttimeexact'] = $wgLang->sprintfDate('H:i:s', $sCurrentTS); //Custom - Categories->Keywords $aMeta['keywords'] = implode(', ', $aCategories); $oDOMXPath = new DOMXPath($oPageDOM); $oMetadataElements = $oDOMXPath->query("//div[@class='bs-universalexport-meta']"); foreach ($oMetadataElements as $oMetadataElement) { if ($oMetadataElement->hasAttributes()) { foreach ($oMetadataElement->attributes as $oAttribute) { if ($oAttribute->name !== 'class') { $aMeta[$oAttribute->name] = $oAttribute->value; } } } $oMetadataElement->parentNode->removeChild($oMetadataElement); } //If it's a normal article if (!in_array($oTitle->getNamespace(), array(NS_SPECIAL, NS_IMAGE, NS_CATEGORY))) { $oArticle = new Article($oTitle); $aMeta['author'] = $oArticle->getUserText(); // TODO RBV (14.12.10 12:19): Realname/Username -> DisplayName $aMeta['date'] = $wgLang->sprintfDate('d.m.Y', $oArticle->getTouched()); } wfRunHooks('BSUEModulePDFcollectMetaData', array($oTitle, $oPageDOM, &$aParams, $oDOMXPath, &$aMeta)); $aMetaDataOverrides = json_decode(BsConfig::get('MW::UniversalExport::MetadataOverrides'), true); $aMeta = array_merge($aMeta, $aMetaDataOverrides); return array('meta' => $aMeta, 'resources' => $aResources); }
/** * * @param Title $oTitle * @return false|\ViewStateBarTopElement */ private function makeStateBarTopSubPages($oTitle) { if ($oTitle->hasSubpages() == false) { return false; } wfProfileIn('BS::' . __METHOD__); $oSubpageIcons = new ViewStateBarTopElement(); $oSubpageIcons->setKey('Subpages'); $oSubpageIcons->setIconSrc($this->getImagePath(true) . BsConfig::get('MW::ArticleInfo::ImageSubpages')); $oSubpageIcons->setIconAlt(wfMessage('bs-articleinfo-subpages-available')->plain()); $oSubpageIcons->setIconTogglesBody(true); $oSubpageIcons->setText(wfMessage('bs-articleinfo-subpages')->plain()); $oSubpageIcons->setTextLinkTitle(wfMessage('bs-articleinfo-subpages')->plain()); $oSubpageIcons->setTextLink('#'); wfRunHooks('BSArticleInfoBeforeSubpagesTopView', array($this, &$oSubpageIcons)); return $oSubpageIcons; }
/** * Creates the facets */ private function createFacets() { $sSiteUri = $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::MLT); // possible orders: count, name, checked // possible directions: 1 = desc, -1 = asc $aOrder = BsConfig::get('MW::SortAlph') ? array('name' => -1) : array('count' => 1); $this->setData('sortorder', $aOrder); $aBaseFacets = array('namespace' => array('param' => 'na', 'option' => 'namespaces', 'i18n' => 'bs-extendedsearch-facet-namespace', 'url' => $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::NAMESPACES | SearchUriBuilder::FILES)), 'cat' => array('param' => 'ca', 'option' => 'cats', 'i18n' => 'bs-extendedsearch-facet-category', 'url' => $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::CATS)), 'editor' => array('param' => 'ed', 'option' => 'editor', 'i18n' => 'bs-extendedsearch-facet-editors', 'url' => $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::NAMESPACES | SearchUriBuilder::EDITOR)), 'type' => array('param' => 'ty', 'option' => 'type', 'i18n' => 'bs-extendedsearch-facet-type', 'url' => $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::NAMESPACES | SearchUriBuilder::TYPE))); wfRunHooks('BSExtendedSearchBeforeCreateFacets', array(&$aBaseFacets)); foreach ($aBaseFacets as $sFacet => $aConfig) { $oFacet = new ViewSearchFacet(); if (!is_null($this->oResponse->facet_counts->facet_fields->{$sFacet})) { $oFacet->setOption('title', $aConfig['i18n']); /* alters to: * array( * 0 => array( 'checked' => true ), * 1 => array( 'count' => 15 ), * 999 => array( 'checked' => true, 'count' => 2 ) * )*/ $aFacets = array(); $aData = $this->oSearchOptions->getOption($aConfig['option']); if (!empty($aData)) { foreach ($aData as $key => $value) { $aFacets[$value]['checked'] = true; } unset($aData); } // Get all available facets $aFacetsInRespsonse = $this->oResponse->facet_counts->facet_fields->{$sFacet}; foreach ($aFacetsInRespsonse as $key => $count) { if ($key == '_empty_') { continue; } if ($sFacet === 'namespace') { if (BsNamespaceHelper::checkNamespacePermission($key, 'read') === false || $count == '0') { unset($aFacets[$key]); continue; } } elseif ($sFacet === 'type') { if ($key != 'wiki' && !$this->oContext->getUser()->isAllowed('searchfiles')) { continue; } } $aFacets[$key]['count'] = $count; } // Prepare available facets. Add some information for each facet foreach ($aFacets as $key => $attributes) { if (!isset($aFacets[$key]['count'])) { unset($aFacets[$key]); continue; } if ($sFacet === 'namespace') { if ($key == '999') { $sTitle = wfMessage('bs-extendedsearch-facet-namespace-files')->plain(); } elseif ($key == '998') { $sTitle = wfMessage('bs-extendedsearch-facet-namespace-extfiles')->plain(); } elseif ($key == '0') { $sTitle = wfMessage('bs-ns_main')->plain(); } else { $sTitle = BsNamespaceHelper::getNamespaceName($key, false); if (empty($sTitle)) { unset($aFacets[$key]); continue; } } } elseif ($sFacet === 'cat') { $sTitle = $key == 'notcategorized' ? wfMessage('bs-extendedsearch-facet-uncategorized')->plain() : $key; } elseif ($sFacet === 'editor') { $sTitle = $key === 'unknown' ? wfMessage('bs-extendedsearch-unknown')->plain() : $key; } elseif ($sFacet === 'type') { $sTitle = $key; } $aFacets[$key]['title'] = $this->getFacetTitle($sTitle); $aFacets[$key]['name'] = $this->reduceMaxFacetLength($sTitle); } uasort($aFacets, array($this, 'compareEntries')); $aFacetAll = array(); foreach ($aFacets as $key => $attributes) { $aDataSet = array(); if (isset($attributes['checked'])) { $aDataSet['checked'] = true; } if ($sFacet === 'namespace') { if ($key == '999') { $uri = $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::NAMESPACES | SearchUriBuilder::FILES); $uri .= '&search_files=' . isset($attributes['checked']) ? '0' : '1'; } else { $uri = $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::NAMESPACES); } } elseif ($sFacet === 'cat') { $uri = $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::CATS); } elseif ($sFacet === 'editor') { $uri = $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::EDITOR); } elseif ($sFacet === 'type') { $uri = $this->oSearchUriBuilder->buildUri(SearchUriBuilder::ALL, SearchUriBuilder::TYPE); } foreach ($aFacets as $namespaceUrl => $attributesUrl) { $bOwnUrlAndNotAlreadyChecked = $key == $namespaceUrl && !isset($attributesUrl['checked']); $bOtherUrlAndAlreadyChecked = $key != $namespaceUrl && isset($attributesUrl['checked']); if ($bOwnUrlAndNotAlreadyChecked || $bOtherUrlAndAlreadyChecked) { $uri .= "&{$aConfig['param']}[]=" . $namespaceUrl; } } $aDataSet['uri'] = $uri; $aDataSet['diff'] = "{$aConfig['param']}[]=" . $key; $aDataSet['name'] = $attributes['name']; $aDataSet['title'] = $attributes['title']; $aDataSet['count'] = (int) $attributes['count']; $oFacet->setData($aDataSet); $aFacetAll[] = "{$aConfig['param']}[]=" . $key; } if ($sFacet === 'namespace') { $aReqNs = $this->oSearchOptions->getOption('namespaces'); foreach ($aReqNs as $ikey => $value) { if (!array_key_exists($value, $aFacets)) { $aFacetAll[] = "{$aConfig['param']}[]=" . $value; $sSiteUri = str_replace("&{$aConfig['param']}[]={$value}", '', $sSiteUri); } } } $sFacetAll = implode('&', $aFacetAll); $oFacet->setOption('uri-facet-all-diff', $sFacetAll); } $this->vSearchResult->setFacet($oFacet); } $this->vSearchResult->setOption('siteUri', $sSiteUri); }
/** * Call the /admin/ping servlet, can be used to quickly tell if a connection to the * server is able to be made. * * @param float $timeout maximum time to wait for ping in seconds, -1 for unlimited (default is 2) * @return float Actual time taken to ping the server, FALSE if timeout occurs */ public function ping($timeout = 2) { $timeout = (double) $timeout; if ($timeout <= 0) { $timeout = -1; } $start = microtime(true); //to prevent strict errors $errno = 0; $errstr = ''; //try to connect to the host with timeout $fp = fsockopen($this->_host, $this->_port, $errno, $errstr, $timeout); if ($fp) { //If we have a timeout set, then determine the amount of time we have left //in the request and set the stream timeout for the write operation if ($timeout > 0) { //do the calculation $writeTimeout = $timeout - (microtime(true) - $start); //check if we're out of time if ($writeTimeout <= 0) { fclose($fp); return false; } //convert to microseconds and set the stream timeout $writeTimeoutInMicroseconds = (int) $writeTimeout * 1000000; stream_set_timeout($fp, 0, $writeTimeoutInMicroseconds); } $request = 'HEAD ' . $this->_path . BsConfig::get('MW::ExtendedSearch::SolrCore') . self::PING_SERVLET . ' HTTP/1.1' . "\r\n" . 'host: ' . $this->_host . "\r\n" . 'Connection: close' . "\r\n" . "\r\n"; fwrite($fp, $request); //check the stream meta data to see if we timed out during the operation $metaData = stream_get_meta_data($fp); if (isset($metaData['timeout']) && $metaData['timeout']) { fclose($fp); return false; } //if we have a timeout set and have made it this far, determine the amount of time //still remaining and set the timeout appropriately before the read operation if ($timeout > 0) { //do the calculation $readTimeout = $timeout - (microtime(true) - $start); //check if we've run out of time if ($readTimeout <= 0) { fclose($fp); return false; } //convert to microseconds and set the stream timeout $readTimeoutInMicroseconds = $readTimeout * 1000000; stream_set_timeout($fp, 0, $readTimeoutInMicroseconds); } //at the very least we should get a response header line of //HTTP/1.1 200 OK $response = fread($fp, 15); //check the stream meta data to see if we timed out during the operation $metaData = stream_get_meta_data($fp); fclose($fp); //we're done with the connection - ignore the rest if (isset($metaData['timeout']) && $metaData['timeout']) { return false; } //finally, check the response header line if ($response != 'HTTP/1.1 200 OK') { return false; } //we made it, return the approximate ping time return microtime(true) - $start; } //we weren't able to make a connection return false; }
/** * Sets values for search form. * @param SkinTemplate $sktemplate * @param BaseTemplate $tpl * @return boolean Always true to keep hook running */ public function onSkinTemplateOutputPageBeforeExec(&$sktemplate, &$tpl) { $tpl->set('searchtitle', SpecialPage::getTitleFor('SpecialExtendedSearch')->getFullText()); if (!empty(SearchOptions::$searchStringRaw)) { $tpl->set('q', SearchOptions::$searchStringRaw); } $tpl->set('bs_search_input', array('id' => 'bs-extendedsearch-input', 'type' => 'text', 'name' => 'q')); $aHiddenFields = array(); $aHiddenFields['sft'] = '1'; if (BsConfig::get('MW::ExtendedSearch::SearchFiles')) { $aHiddenFields['search_files'] = '1'; } $tpl->set('bs_search_hidden_fields', $aHiddenFields); return true; }
/** * * @param OutputPage $out * @param Skin $skin * @return boolean */ public static function onBeforePageDisplay(&$out, &$skin) { $out->addModuleStyles('ext.bluespice.insertcategory.styles'); $out->addModules('ext.bluespice.insertcategory'); $out->addJsConfigVars('BSInsertCategoryWithParents', BsConfig::get('MW::InsertCategory::WithParents')); return true; }
/** * Creates or changes a review for a page. Called by remote handler. * @return bool Allow other hooked methods to be executed. Always true. */ public static function doEditReview() { if (BsCore::checkAccessAdmission('workflowedit') === false) { return true; } $aAnswer = array('success' => true, 'errors' => array(), 'messages' => array()); $oUser = BsCore::loadCurrentUser(); $oReview = BsExtensionManager::getExtension('Review'); $userIsSysop = in_array('sysop', $oUser->getGroups()); //TODO: getEffectiveGroups()? if (!$userIsSysop && !$oUser->isAllowed('workflowedit')) { $aAnswer['success'] = false; $aAnswer['messages'][] = wfMessage('bs-review-save-norights')->plain(); return json_encode($aAnswer); } global $wgRequest; $paramRvPid = $wgRequest->getInt('pid', -1); // Check for id 0 prevents special pages to be put on a review if (empty($paramRvPid)) { $aAnswer['success'] = false; $aAnswer['messages'][] = wfMessage('bs-review-save-noid')->plain(); return json_encode($aAnswer); } $oReviewProcess = BsReviewProcess::newFromPid($paramRvPid); $bIsEdit = false; if (is_object($oReviewProcess) && $oReviewProcess->hasSteps()) { $bIsEdit = true; } if (!$userIsSysop && $oReviewProcess && BsConfig::get('MW::Review::CheckOwner') && $oReviewProcess->owner != $oUser->getID()) { $aAnswer['success'] = false; $aAnswer['messages'][] = wfMessage('bs-review-save-norights')->plain(); return json_encode($aAnswer); } $paramCmd = $wgRequest->getVal('cmd', ''); $paramSaveTmpl = $wgRequest->getInt('save_tmpl', 0); if (!($paramCmd === false)) { switch ($paramCmd) { case 'insert': $aErrors = array(); $review = BsReviewProcess::newFromJSON($wgRequest->getVal('review', ''), $aErrors); if (is_array($aErrors) && count($aErrors) > 0) { $aAnswer['success'] = false; foreach ($aErrors as $sError) { $aAnswer['messages'][] = wfMessage('bs-review-' . $sError)->plain(); } return json_encode($aAnswer); } $review->setOwner($oUser->getID()); $oOldReview = BsReviewProcess::newFromPid($paramRvPid); $update = is_object($oOldReview) ? $oOldReview->getPid() : false; BsReviewProcess::removeReviewSteps($paramRvPid); if ($paramSaveTmpl == 1) { $paramTmplChoice = $wgRequest->getInt('tmpl_choice', -1); $paramTmplName = $wgRequest->getVal('tmpl_name', ''); $review->asTemplate($paramTmplChoice, $paramTmplName); } if (!is_array($review->steps)) { $aAnswer['success'] = false; $aAnswer['messages'][] = wfMessage('bs-review-save-nosteps')->plain(); return json_encode($aAnswer); } if ($review->store($update)) { $oTitle = Title::newFromID($paramRvPid); $oTitle->invalidateCache(); $oWatchlist = WatchedItem::fromUserTitle($oUser, $oTitle); if (!$oWatchlist->isWatched()) { $oWatchlist->addWatch(); } $aParams = array('action' => $bIsEdit ? 'modify' : 'create', 'target' => $oTitle, 'comment' => '', 'params' => null, 'doer' => $oUser); $oReview->oLogger->addEntry($aParams['action'], $aParams['target'], $aParams['comment'], $aParams['params'], $aParams['doer']); $aAnswer['messages'][] = wfMessage('bs-review-save-success')->plain(); // Identify owner $oReviewProcess = BsReviewProcess::newFromPid($paramRvPid); $oReview->emailNotifyNextUsers($oReviewProcess); return json_encode($aAnswer); } else { $aAnswer['success'] = false; $aAnswer['messages'][] = wfMessage('bs-review-save-error')->plain(); return json_encode($aAnswer); } break; // 22.08.13 STM: WTF? // 22.08.13 STM: WTF? case 'delete': BsReviewProcess::removeReviews($paramRvPid); $oTitle = Title::newFromID($paramRvPid); $oTitle->invalidateCache(); $oWatchlist = WatchedItem::fromUserTitle($oUser, $oTitle); if ($oWatchlist->isWatched()) { $oWatchlist->removeWatch(); } $aParams = array('action' => 'delete', 'target' => $oTitle, 'comment' => '', 'params' => null, 'doer' => $oUser); $oReview->oLogger->addEntry($aParams['action'], $aParams['target'], $aParams['comment'], $aParams['params'], $aParams['doer']); $aAnswer['messages'][] = wfMessage('bs-review-save-removed')->plain(); return json_encode($aAnswer); break; } } return true; }
/** * * @global User $wgUser * @global WebRequest $wgRequest * @return type */ public static function ajaxSave() { $aResult = array("success" => false, "errors" => array(), "message" => '', "data" => array()); global $wgUser, $wgRequest; if (!$wgUser->isAllowed('read')) { $aResult["message"] = wfMessage('bs-statistics-not-allowed')->plain(); return json_encode($aResult); } $sDiagram = $wgRequest->getVal('inputDiagrams', ''); $sGrain = $wgRequest->getVal('InputDepictionGrain', 'Y'); $sFrom = $wgRequest->getVal('inputFrom', ''); $sMode = $wgRequest->getVal('rgInputDepictionMode', ''); $sTo = $wgRequest->getVal('inputTo', ''); $aAvailableDiagrams = Statistics::getAvailableDiagrams(); $aAllowedDiaKeys = array_keys($aAvailableDiagrams); if (empty($sDiagram)) { $aResult["errors"]['inputDiagrams'] = wfMessage('bs-statistics-err-emptyinput')->plain(); } elseif (!in_array($sDiagram, $aAllowedDiaKeys)) { $aResult["errors"]['inputDiagrams'] = wfMessage('bs-statistics-err-unknowndia')->plain(); } if (!array_key_exists($sGrain, BsConfig::get('MW::Statistics::AvailableGrains'))) { $aResult["errors"]['InputDepictionGrain'] = wfMessage('bs-statistics-err-unknowngrain')->plain(); } if (empty($sFrom)) { $aResult["errors"]['inputFrom'] = wfMessage('bs-statistics-err-emptyinput')->plain(); } elseif (!($oFrom = DateTime::createFromFormat('d.m.Y', $sFrom))) { $aResult["errors"]['inputFrom'] = wfMessage('bs-statistics-err-invaliddate')->plain(); } if (empty($sTo)) { $aResult["errors"]['inputTo'] = wfMessage('bs-statistics-err-emptyinput')->plain(); } elseif (!($oTo = DateTime::createFromFormat('d.m.Y', $sFrom))) { $aResult["errors"]['inputTo'] = wfMessage('bs-statistics-err-invaliddate')->plain(); } elseif ($oTo > new DateTime()) { $aResult["errors"]['inputTo'] = wfMessage('bs-statistics-err-invaliddate')->plain(); } if (isset($oFrom) && isset($oTo) && $oFrom > $oTo) { $aResult["errors"]['inputTo'] = wfMessage('bs-statistics-err-invalidtofromrelation')->plain(); } if (empty($sMode)) { $aResult["errors"]['rgInputDepictionMode'] = wfMessage('bs-statistics-err-emptyinput')->plain(); } elseif (!in_array($sMode, array('absolute', 'aggregated', 'list'))) { $aResult["errors"]['rgInputDepictionMode'] = wfMessage('bs-statistics-err-unknownmode')->plain(); } elseif (!isset($aResult["errors"]['inputDiagrams']) && $sMode == 'list' && !$aAvailableDiagrams[$sDiagram]->isListable()) { $aResult["errors"]['rgInputDepictionMode'] = wfMessage('bs-statistics-err-modeunsupported')->plain(); } if (!empty($aResult['errors'])) { return json_encode($aResult); } $oDiagram = Statistics::getDiagram($sDiagram); $oDiagram->setStartTime($sFrom); $oDiagram->setEndTime($sTo); $oDiagram->setActualGrain($sGrain); $oDiagram->setModLabel($sGrain); $oDiagram->setMode($sMode); //$oDiagram->setMessage( $sMessage ); //$oDiagram->setFilters( $aDiagFilter ); switch ($oDiagram->getActualGrain()) { // Here, only those grains are listed where label code differs from grain code. case 'm': $oDiagram->setModLabel('M y'); break; case 'd': $oDiagram->setModLabel('d.m'); break; //default : $oDiagram->modLabel = false; } switch ($oDiagram->getDataSource()) { case BsDiagram::DATASOURCE_DATABASE: global $wgDBtype, $wgDBserver, $wgDBuser, $wgDBpassword, $wgDBname; switch ($wgDBtype) { case "postgres": $oReader = new PostGreSQLDbReader(); break; case "oracle": $oReader = new OracleDbReader(); break; default: $oReader = new MySQLDbReader(); } //$oReader = $sDbType == 'mysql' ? new MySQLDbReader() : new PostGreSQLDbReader(); $oReader->host = $wgDBserver; $oReader->user = $wgDBuser; $oReader->pass = $wgDBpassword; $oReader->db = $wgDBname; break; } $intervals = Interval::getIntervalsFromDiagram($oDiagram); if (count($intervals) > BsConfig::get('MW::Statistics::MaxNumberOfIntervals')) { $aResult['message'] = wfMessage('bs-statistics-interval-too-big')->plain(); return json_encode($aResult); } //set_time_limit( 60 ); // TODO MRG (20.12.10 00:01): already called before //$intervals = Interval::getIntervalsFromDiagram( $oDiagram ); //$oDiagram->addFilterText( wfMessage( 'bs-statistics-from-to', $oDiagram->getStartTime(), $oDiagram->getEndTime() )->plain() ); // TODO MRG (20.12.10 00:19): This should be getModeText //$oDiagram->addFilterText( "\n".wfMessage( 'bs-statistics-mode' )->plain().": ".wfMessage( $oDiagram->getMessage() )->plain() ); // PostgreSQL-Check (uses mwuser instead of user) global $wgDBtype; // Pls. keep the space after user, otherwise, user_groups is also replaced $sql = $oDiagram->getSQL(); if ($wgDBtype == 'postgres') { $sql = str_replace('#__user', '#__mwuser', $sql); } if ($wgDBtype == 'postgres') { $sql = str_replace('#__mwuser_', '#__user_', $sql); } global $wgDBprefix; $sql = str_replace("#__", $wgDBprefix, $sql); foreach ($oDiagram->getFilters() as $oFilter) { $sFilterSql = $oFilter->getSql(); $sql = str_replace($oFilter->getSqlKey(), $sFilterSql, $sql); } $oReader->match = $sql; $oDiagram->setData(BsCharting::getDataPerDateInterval($oReader, $oDiagram->getMode(), $intervals, $oDiagram->isListable())); if ($oDiagram->isList()) { //$aResult['data']['list'] = BsCharting::drawTable($oDiagram); $aResult['data']['list'] = BsCharting::prepareList($oDiagram, $oReader); $aResult['label'] = $oDiagram->getTitle(); $aResult['success'] = true; return json_encode($aResult); } $aData = $oDiagram->getData(); $i = 0; foreach ($intervals as $interval) { $aResult['data'][] = array('name' => $interval->getLabel(), 'hits' => (int) $aData[$i]); $i++; } $aAvalableGrains = BsConfig::get('MW::Statistics::AvailableGrains'); $sLabelMsgKey = 'bs-statistics-label-time'; if (isset($aAvalableGrains[$oDiagram->getActualGrain()])) { $sLabelMsgKey = $aAvalableGrains[$oDiagram->getActualGrain()]; } $aResult['label'] = wfMessage($sLabelMsgKey)->plain(); $aResult['success'] = true; return json_encode($aResult); }
/** * Deletes a flexiskin defined by id via request parameter * @return String encoded result JSON string */ public function deleteFlexiskin() { $sId = $this->getMain()->getVal('id', ''); if ($sId == "") { return FormatJson::encode(array('success' => false, 'msg' => wfMessage('bs-flexiskin-api-error-missing-param', 'id')->plain())); } $oStatus = BsFileSystemHelper::deleteFolder("flexiskin" . DS . $iId); if (BsConfig::get("MW::Flexiskin::Active") == $iId) { BsConfig::set("MW::Flexiskin::Active", ""); BsConfig::saveSettings(); } if (!$oStatus->isGood()) { return FormatJson::encode(array('success' => false, 'msg' => wfMessage('bs-flexiskin-error-delete-skin', $this->getErrorMessage($oStatus))->plain())); } else { return FormatJson::encode(array('success' => true)); } }
public static function ajaxGetArticlesByNamespaceId() { if (BsCore::checkAccessAdmission('edit') === false) { return true; } global $wgOut, $wgRequest; $wgOut->disable(); $oParams = BsExtJSStoreParams::newFromRequest(); $iStart = $wgRequest->getInt('start', 0); $sSort = $oParams->getSort('page_title'); $sDirection = $oParams->getDirection(); $iLimit = $wgRequest->getInt('limit', 25); $sDisplayMode = $wgRequest->getVal('displayMode', 'only-assigned'); $iNamespaceId = $wgRequest->getInt('namespaceId', -99); $aActivatedNamespaces = BsConfig::get('MW::ResponsibleEditors::ActivatedNamespaces'); $oResult = new stdClass(); $aTables = array('bs_responsible_editors', 'user', 'page'); $aVariables = array('page_id', 'page_title', 'page_namespace'); $aConditions = array('page_namespace' => $aActivatedNamespaces); if ($sDisplayMode == 'only-assigned') { $aConditions[] = 're_user_id IS NOT NULL '; } else { if ($sDisplayMode == 'only-not-assigned') { $aConditions[] = 're_user_id IS NULL '; } } if ($iNamespaceId != -99) { $aConditions['page_namespace'] = $iNamespaceId; } $aOptions = array('ORDER BY' => $sSort . ' ' . $sDirection, 'LIMIT' => $iLimit, 'OFFSET' => $iStart, 'GROUP BY' => 'page_id'); if ($sSort == 'user_displayname') { $aOptions['ORDER BY'] = 'user_real_name, user_name ' . $sDirection; } $aJoinOptions = array('user' => array('JOIN', 'user_id = re_user_id'), 'page' => array('RIGHT JOIN', 'page_id = re_page_id')); $dbr = wfGetDB(DB_SLAVE); //TODO: Rework "total" calculation. This seems very complicated but it //should be as easy as excuting the main query without LIMIT/OFFSET. if ($sDisplayMode == 'only-assigned' || $sDisplayMode == 'only-not-assigned') { $row = $dbr->select(array('page', 'bs_responsible_editors'), 'page_id AS cnt', $aConditions, __METHOD__, array('GROUP BY' => 'page_id'), array('page' => array('RIGHT JOIN', 'page_id = re_page_id'))); $oResult->total = $row->numRows(); } if ($sDisplayMode == 'all') { $aConditionsWithoutRePageID = $aConditions; unset($aConditionsWithoutRePageID[0]); $row = $dbr->selectRow('page', 'COUNT( page_id ) AS cnt', $aConditionsWithoutRePageID); $oResult->total = $row->cnt; } $res = $dbr->select($aTables, $aVariables, $aConditions, __METHOD__, $aOptions, $aJoinOptions); $oResult->pages = array(); foreach ($res as $row) { $oTitle = Title::newFromId($row->page_id); $iPageId = $row->page_id; $sPageNsId = !empty($row->page_namespace) ? $row->page_namespace : 0; $sPageTitle = $row->page_title; $oPage = new stdClass(); $oPage->page_id = $iPageId; $oPage->page_namespace = $sPageNsId; $oPage->page_title = $sPageTitle; $oPage->page_prefixedtext = $oTitle->getPrefixedText(); $oPage->users = array(); $aEditorIDs = BsExtensionManager::getExtension('ResponsibleEditors')->getResponsibleEditorIdsByArticleId($row->page_id); $aEditorIDs = array_unique($aEditorIDs); foreach ($aEditorIDs as $iEditorID) { $oUser = User::newFromId($iEditorID); if ($oUser == null) { continue; } $oPage->users[] = array('user_id' => $iEditorID, 'user_page_link_url' => $oUser->getUserPage()->getFullUrl(), 'user_displayname' => BsCore::getUserDisplayName($oUser)); } $oResult->pages[] = $oPage; } return FormatJson::encode($oResult); }
/** * 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; }