/**
  * Getter for the $aNavigationSites array - either from hook, TopBarMenu title or cache
  * @global string $wgSitename
  * @return array
  */
 public static function getNavigationSites()
 {
     if (!is_null(self::$aNavigationSites)) {
         return self::$aNavigationSites;
     }
     $sKey = BsExtensionManager::getExtension('TopMenuBarCustomizer')->getCacheKey('NavigationSitesData');
     self::$aNavigationSites = BsCacheHelper::get($sKey);
     if (self::$aNavigationSites !== false) {
         return self::$aNavigationSites;
     }
     self::$aNavigationSites = array();
     $oTopBarMenuTitle = Title::makeTitle(NS_MEDIAWIKI, 'TopBarMenu');
     if (!is_null($oTopBarMenuTitle) && $oTopBarMenuTitle->exists()) {
         $sContent = BsPageContentProvider::getInstance()->getContentFromTitle($oTopBarMenuTitle);
         // Force unset of all menu items by creating an empty page
         if (!empty($sContent)) {
             self::$aNavigationSites = TopMenuBarCustomizerParser::getNavigationSites();
         }
         BsCacheHelper::set($sKey, self::$aNavigationSites, 60 * 1440);
         //max cache time 24h
         return self::$aNavigationSites;
     }
     global $wgSitename;
     $oCurrentTitle = RequestContext::getMain()->getTitle();
     $oMainPage = Title::newMainPage();
     self::$aNavigationSites[] = array('id' => 'wiki', 'href' => $oMainPage->getFullURL(), 'text' => $wgSitename, 'active' => $oCurrentTitle->equals($oMainPage), 'level' => 1, 'containsactive' => false, 'external' => false, 'children' => array());
     wfRunHooks('BSTopMenuBarCustomizerRegisterNavigationSites', array(&self::$aNavigationSites));
     BsCacheHelper::set($sKey, self::$aNavigationSites, 60 * 1440);
     //max cache time 24h
     return self::$aNavigationSites;
 }
 public static function ajaxGetPossibleEditors($iArticleId = -1)
 {
     $aResult = array('users' => array());
     if ($iArticleId == -1) {
         return FormatJson::encode($aResult);
     }
     $oResponsibleEditors = BsExtensionManager::getExtension('ResponsibleEditors');
     $aResult['users'] = $aEditors = $oResponsibleEditors->getListOfResponsibleEditorsForArticle($iArticleId);
     return FormatJson::encode($aResult);
 }
    public function execute($sParameter)
    {
        parent::execute($sParameter);
        $oRequestedTitle = null;
        $oOut = $this->getOutput();
        if (!empty($sParameter)) {
            $oRequestedTitle = Title::newFromText($sParameter);
            if ($oRequestedTitle->exists() && ($oRequestedTitle->getNamespace() !== NS_USER || $oRequestedTitle->isSubpage() === true)) {
                $sOut = $this->renderReadersGrid();
                $oOut->addModules('ext.bluespice.readers.specialreaders');
                $oOut->setPageTitle(wfMessage('readers', $oRequestedTitle->getFullText())->text());
                $oOut->addHtml('<script type="text/javascript">
						bsReadersTitle = "' . $oRequestedTitle->getPrefixedText() . '";
					</script>');
            } elseif ($oRequestedTitle->getNamespace() === NS_USER) {
                $sOut = $this->renderReaderspathGrid();
                $oOut->addModules('ext.bluespice.readers.specialreaderspath');
                $oUser = User::newFromName($oRequestedTitle->getText());
                $oOut->setPageTitle(wfMessage('readers-user', $oUser->getName())->text());
                $oOut->addHtml('<script type="text/javascript">
						bsReadersUserID = "' . $oUser->getId() . '";
					</script>');
            } else {
                $oErrorView = new ViewTagErrorList();
                $oErrorView->addItem(new ViewTagError(wfMessage('bs-readers-pagenotexists')->plain()));
                $sOut = $oErrorView->execute();
            }
        } else {
            $oErrorView = new ViewTagErrorList(BsExtensionManager::getExtension('Readers'));
            $oErrorView->addItem(new ViewTagError(wfMessage('bs-readers-emptyinput')->plain()));
            $sOut = $oErrorView->execute();
        }
        if ($oRequestedTitle === null) {
            $oOut->setPageTitle($oOut->getPageTitle());
        }
        $oOut->addHTML($sOut);
    }
 /**
  * returns the formular for Preferences
  * @return string the formular string
  */
 public function getForm()
 {
     if (wfReadOnly()) {
         throw new ReadOnlyError();
     }
     $this->getOutput()->addModuleScripts('ext.bluespice.preferences');
     $this->getOutput()->addHTML('<br />');
     $oRequest = $this->getRequest();
     if ($this->getRequest()->getVal('success') == true) {
         $this->getOutput()->wrapWikiMsg('<div class="successbox"><strong>$1</strong></div><div id="mw-pref-clear"></div>' . "\n", 'savedprefs');
     }
     $orig_deliver = BsConfig::deliverUsersSettings(false);
     BsConfig::loadSettings();
     BsExtensionManager::getExtensionInformation();
     $vars = BsConfig::getRegisteredVars();
     $bShowall = $oRequest->getFuzzyBool('showall');
     if ($bShowall) {
         $out = '';
         foreach ($vars as $var) {
             $out .= $var->getAdapter() . "::";
             if ($var->getExtension() !== null) {
                 $out .= $var->getExtension() . "::";
             }
             $out .= $var->getName() . "<br>";
         }
         return $out;
     }
     $preferences = array();
     $aSortedVariables = array();
     foreach ($vars as $var) {
         $options = $var->getOptions();
         if (!($options & (BsConfig::LEVEL_PUBLIC | BsConfig::LEVEL_USER))) {
             continue;
         }
         if ($options & BsConfig::NO_DEFAULT) {
             continue;
         }
         $extension = $var->getI18nExtension() ? $var->getI18nExtension() : 'BASE';
         $aSortedVariables[$extension][] = $var;
     }
     foreach ($aSortedVariables as $sExtensionName => $aExtensions) {
         if (!count($aExtensions)) {
             continue;
         }
         foreach ($aExtensions as $oVariable) {
             // if continue, then $oAdapterSetView is not added to output
             if (!count($oVariable)) {
                 continue;
             }
             $sSection = $sExtensionName;
             $oExtension = BsExtensionManager::getExtension($sExtensionName);
             $field = $oVariable->getFieldDefinition($sSection);
             if ($oVariable->getOptions() & BsConfig::USE_PLUGIN_FOR_PREFS) {
                 $oExtension = BsExtensionManager::getExtension($sExtensionName);
                 $tmp = $oExtension->runPreferencePlugin('MW', $oVariable);
                 $field = array_merge($field, $tmp);
             }
             $preferences[$oVariable->generateFieldId()] = $field;
         }
     }
     BsConfig::deliverUsersSettings($orig_deliver);
     $oForm = new HTMLFormEx($preferences, 'prefs');
     $oForm->setTitle($this->getTitle());
     $oForm->addHiddenField('mode', 'Preferences');
     $oForm->setSubmitText(wfMessage('bs-extjs-save')->plain());
     $oForm->setSubmitName('WikiAdminPreferencesSubmit');
     $oForm->setSubmitCallback(array($this, 'savePreferences'));
     $oForm->show();
     $this->getOutput()->addHTML('<br />');
     return '';
 }
 /**
  * Called when a review vote is cast. Handles votes. Called by remote handler.
  * @return bool Allow other hooked methods to be executed. always true.
  */
 public static function getVoteResponse()
 {
     global $wgRequest;
     $iArticleId = $wgRequest->getInt('articleID', 0);
     $sVote = $wgRequest->getVal('vote', '');
     $sComment = $wgRequest->getVal('comment', '');
     if (empty($iArticleId) || empty($sVote) || (int) $iArticleId === 0) {
         return wfMessage('bs-review-review-error')->plain();
     }
     $oTitle = Title::newFromID($iArticleId);
     $oUser = RequestContext::getMain()->getUser();
     //tbd: make bs-review-review-error more explicit
     if ($oTitle === false || !$oTitle->exists() || $oUser === false) {
         return wfMessage('bs-review-review-error')->plain();
     }
     if (!$oTitle->userCan("workflowview", $oUser)) {
         return wfMessage('bs-review-error-insufficient-permissions', 'workflowview')->text();
     }
     $oReview = BsExtensionManager::getExtension('Review');
     $oNext = null;
     $dbw = wfGetDB(DB_MASTER);
     // Get ID of the apropriate step
     $tables = array();
     $tables[] = 'bs_review';
     $tables[] = 'bs_review_steps';
     $tbl_rev = $dbw->tableName('bs_review');
     $tbl_step = $dbw->tableName('bs_review_steps');
     $conds = array();
     $conds[] = $tbl_step . '.revs_review_id = ' . $tbl_rev . '.rev_id';
     // join tables
     $conds[] = $tbl_rev . '.rev_pid=' . $iArticleId;
     // reviews only for current article
     $conds[] = $tbl_step . '.revs_status=-1';
     // prevent user from confirming twice
     $conds[] = $tbl_step . ".revs_user_id='{$oUser->getId()}'";
     // make sure we select a dataset for the current user
     $options = array('ORDER BY' => 'revs_sort_id ASC');
     $join_conds = array();
     $fields = $tbl_step . '.*';
     wfRunHooks('BsReview::buildDbQuery', array('getVoteResponse', &$tables, &$fields, &$conds, &$options, &$join_conds));
     $res = $dbw->select($tables, $fields, $conds, __METHOD__, $options, $join_conds);
     if (!($row = $dbw->fetchRow($res))) {
         return wfMessage('bs-review-review-error')->plain();
     }
     // Unexpectedly, no review could be found.
     if ($dbw->numRows($res) == 0) {
         return wfMessage('bs-review-review-secondtime')->plain();
     } elseif ($dbw->numRows($res) > 1) {
         $oNext = $dbw->fetchObject($res);
     }
     $dbw->freeResult($res);
     $step_id = $row['revs_id'];
     $initial_comment = $row['revs_comment'];
     // update data
     $data = array();
     switch ($sVote) {
         case "yes":
             $data['revs_status'] = 1;
             $oReview->oLogger->addEntry('approve', $oTitle, '', null, $oUser);
             break;
         case "no":
             $data['revs_status'] = 0;
             $oReview->oLogger->addEntry('deny', $oTitle, '', null, $oUser);
             break;
         default:
             $data['revs_status'] = -1;
             break;
     }
     // Identify owner
     $oReviewProcess = BsReviewProcess::newFromPid($iArticleId);
     $oOwner = User::newFromID($oReviewProcess->getOwner());
     $sUserName = BsCore::getUserDisplayName($oUser);
     $sOwnerName = BsCore::getUserDisplayName($oOwner);
     if (!empty($initial_comment)) {
         $initial_comment = "<em>{$sOwnerName}: </em>{$initial_comment}";
     }
     if (!empty($sComment)) {
         $data['revs_comment'] = "<em>{$sUserName}: </em>{$sComment}";
         //Prepend original comment
         if (!empty($initial_comment)) {
             $data['revs_comment'] = $initial_comment . " &rArr; " . $data['revs_comment'];
         }
     } else {
         $data['revs_comment'] = $initial_comment;
     }
     wfRunHooks('BsReview::dataBeforeSafe', array('getVoteResponse', &$data));
     $dbw->update('bs_review_steps', $data, array('revs_id' => $step_id));
     $oTitle->invalidateCache();
     if ($sVote == 'no' && $oReviewProcess->isSequential()) {
         $oReviewProcess->reset($sComment);
     }
     //PW(09.03.2015): Echo notifications
     //Notify the owner of the revie, that a user did some action
     // if the receiver deactivated mail notifications, we stop right here
     if (!BsConfig::getVarForUser('MW::Review::EmailNotifyReviewer', $oOwner->getName())) {
         // Unfortunately, there is no way of verifying the result :(
         return wfMessage('bs-review-review-saved')->plain();
     }
     $aParams = array(BsCore::getUserDisplayName($oUser), $oUser->getName(), $oTitle->getPrefixedText());
     if ($sVote == 'yes') {
         $sSubject = wfMessage("bs-review-mail-accept-header", $aParams)->inLanguage($oOwner->getOption('language'))->text();
         $sMessage = wfMessage("bs-review-mail-accept-body", $aParams)->inLanguage($oOwner->getOption('language'))->text();
     } elseif ($sVote == 'no') {
         if ($oReviewProcess->isSequential()) {
             $sSubject = wfMessage("bs-review-mail-deny-and-restart-header", $aParams)->inLanguage($oOwner->getOption('language'))->text();
             $sMessage = wfMessage("bs-review-mail-deny-and-restart-body", $aParams)->inLanguage($oOwner->getOption('language'))->text();
         } else {
             $sSubject = wfMessage("bs-review-mail-deny-header", $aParams)->inLanguage($oOwner->getOption('language'))->text();
             $sMessage = wfMessage("bs-review-mail-deny-body", $aParams)->inLanguage($oOwner->getOption('language'))->text();
         }
     }
     $sMessage .= wfMessage('bs-review-mail-link-to-page', $oTitle->getFullURL())->inLanguage($oOwner->getOption('language'))->text();
     BsMailer::getInstance('MW')->send($oOwner, $sSubject, $sMessage);
     wfRunHooks('BsReview::getVoteResponseOnMailAction', array($row, $oTitle, $oOwner));
     if ($oReviewProcess->isFinished() === false) {
         return wfMessage('bs-review-review-saved')->plain();
     }
     // Let flagged revision know that it's all goooooood (or not approved)
     $bResult = true;
     wfRunHooks('checkPageIsReviewable', array($oTitle, &$bResult));
     if ($bResult) {
         if ($oReviewProcess->isFinished() == 'status') {
             if (!$oUser->isAllowed('review')) {
                 $sSubject = wfMessage("bs-review-mail-finish-header", $aParams)->inLanguage($oOwner->getOption('language'))->text();
                 $sMessage = wfMessage("bs-review-mail-finish-body", $aParams)->inLanguage($oOwner->getOption('language'))->text();
             } else {
                 $sSubject = wfMessage("bs-review-mail-finish-and-review-header", $aParams)->inLanguage($oOwner->getOption('language'))->text();
                 $sMessage = wfMessage("bs-review-mail-finish-and-review-body", $aParams)->inLanguage($oOwner->getOption('language'))->text();
             }
         }
     } else {
         //This is probably handled somewhere else
         //return wfMessage('bs-review-review-saved')->plain();
         $sSubject = wfMessage("bs-review-mail-finish-header", $aParams)->inLanguage($oOwner->getOption('language'))->text();
         $sMessage = wfMessage("bs-review-mail-finish-body", $aParams)->inLanguage($oOwner->getOption('language'))->text();
     }
     $sMessage .= wfMessage('bs-review-mail-link-to-page', $oTitle->getFullURL())->inLanguage($oOwner->getOption('language'))->text();
     BsMailer::getInstance('MW')->send($oOwner, $sSubject, $sMessage);
     // Unfortunately, there is no way of verifying the result :(
     return wfMessage('bs-review-review-saved')->plain();
 }
 /**
  * removes a usergroup
  * @param string $output the ajax output string
  */
 public static function removeGroup($sGroup)
 {
     if (wfReadOnly()) {
         global $wgReadOnly;
         return FormatJson::encode(array('success' => false, 'message' => wfMessage('bs-readonly', $wgReadOnly)->plain()));
     }
     if (BsCore::checkAccessAdmission('wikiadmin') === false) {
         return true;
     }
     global $wgGroupPermissions, $wgAdditionalGroups, $wgNamespacePermissionLockdown;
     $output = FormatJson::encode(array('success' => true, 'message' => wfMessage('bs-groupmanager-grpremoved')->plain()));
     if ($sGroup) {
         if (!isset($wgAdditionalGroups[$sGroup])) {
             return FormatJson::encode(array('success' => false, 'message' => wfMessage('bs-groupmanager-msgnotremovable')->plain()));
         }
         $wgAdditionalGroups[$sGroup] = false;
         $dbw = wfGetDB(DB_MASTER);
         $res = $dbw->delete('user_groups', array('ug_group' => $sGroup));
         if ($res === false) {
             return FormatJson::encode(array('success' => false, 'message' => wfMessage('bs-groupmanager-removegroup-message-unknown')->plain()));
         }
         $result = BsExtensionManager::getExtension('GroupManager')->saveData();
         wfRunHooks("BSGroupManagerGroupDeleted", array($sGroup, &$result));
         if ($result['success'] === false) {
             return FormatJson::encode($result);
         }
     }
     return $output;
 }
 /**
  * Hook handler for GetPreferences
  * @param User $user User whose preferences are being modified.
  * @param Array &$preferences Preferences description array, to be fed to an HTMLForm object
  * @return true always true to keep hook alive
  */
 public function onGetPreferences($user, &$preferences)
 {
     $bOrigDeliver = BsConfig::deliverUsersSettings(true);
     $aRegisteredVariables = BsConfig::getRegisteredVars();
     $aSortedVariables = array();
     foreach ($aRegisteredVariables as $oVariable) {
         $iOptions = $oVariable->getOptions();
         if (!($iOptions & BsConfig::LEVEL_USER)) {
             continue;
         }
         $sExtensionName = $oVariable->getExtension();
         if (empty($sExtensionName)) {
             $sExtensionName = "BASE";
             $sExtensionTranslation = wfMessage('CORE')->plain();
         } else {
             $sExtensionNameLower = strtolower($sExtensionName);
             $sExtensionTranslation = wfMessage('prefs-' . $sExtensionNameLower)->plain();
         }
         $aSortedVariables[$sExtensionTranslation][$sExtensionName][] = $oVariable;
         ksort($aSortedVariables);
     }
     foreach ($aSortedVariables as $val) {
         if (!count($val)) {
             continue;
         }
         foreach ($val as $sExtensionName => $aSettings) {
             // if continue, then $oAdapterSetView is not added to output
             if (!count($aSettings)) {
                 continue;
             }
             $sSection = 'bluespice/' . $sExtensionName;
             foreach ($aSettings as $oVariable) {
                 $field = $oVariable->getFieldDefinition($sSection);
                 if ($oVariable->getOptions() & BsConfig::USE_PLUGIN_FOR_PREFS) {
                     $oExtension = BsExtensionManager::getExtension($sExtensionName);
                     $tmp = $oExtension->runPreferencePlugin('MW', $oVariable);
                     $field = array_merge($field, $tmp);
                 }
                 $preferences[$oVariable->generateFieldId()] = $field;
             }
         }
     }
     BsConfig::deliverUsersSettings($bOrigDeliver);
     return true;
 }
 /**
  * Returns list of most edited pages called via Ajax
  * @param integer $iCount number of items
  * @param sring $sCaller caller
  * @return string most edited pages
  */
 public static function getYourEditsPortlet($iCount)
 {
     return BsExtensionManager::getExtension('SmartList')->getYourEdits($iCount);
 }
 public static function loadModules()
 {
     if (!self::$prLoadModulesAndScripts) {
         return;
     }
     foreach (self::$prRegisteredModules as $name => $params) {
         self::$prRunningModules[$name] = BsExtensionManager::getExtension($name);
     }
     foreach (self::$prRegisteredModuleClasses as $name => $params) {
         self::$prRunningModules[$name] = new $name();
     }
 }
 /**
  * AJAX interface for BlueSpice SateBar body views
  * @return string The JSON formatted response
  */
 public static function ajaxCollectBodyViews()
 {
     global $wgUser;
     $aResult = array("success" => false, "views" => array(), "message" => '');
     $iArticleID = RequestContext::getMain()->getRequest()->getInt('articleID', 0);
     if ($iArticleID === 0) {
         $aResult['message'] = wfMessage("bs-statebar-ajax-nobodyviews")->plain();
         return FormatJson::encode($aResult);
     }
     $oStateBar = BsExtensionManager::getExtension('StateBar');
     $oStateBar->registerSortVars();
     $oTitle = $oStateBar->checkContext(Title::newFromID($iArticleID), true);
     if (is_null($oTitle)) {
         $aResult['message'] = wfMessage("bs-statebar-ajax-nobodyviews")->plain();
         return json_encode($aResult);
     }
     $aBodyViews = array();
     wfRunHooks('BSStateBarBeforeBodyViewAdd', array($oStateBar, &$aBodyViews, $wgUser, $oTitle));
     if (empty($aBodyViews)) {
         $aResult['success'] = true;
         $aResult['message'] = wfMessage('bs-statebar-ajax-nobodyviews')->plain();
         return json_encode($aResult);
     }
     $aSortBodyVars = BsConfig::get('MW::StateBar::SortBodyVars');
     if (!empty($aSortBodyVars)) {
         $aBodyViews = $oStateBar->reorderViews($aBodyViews, $aSortBodyVars);
     }
     //execute all views to an array with numeric index
     $aExecutedBodyViews = array();
     foreach ($aBodyViews as $oView) {
         $aExecutedBodyViews[] = $oView->execute();
     }
     $aResult['views'] = $aExecutedBodyViews;
     $aResult['success'] = true;
     return FormatJson::encode($aResult);
 }
 /**
  * Saves a given namespace configuration to bluespice-core/config/nm-settings.php
  * @param array $aUserNamespaceDefinition the namespace configuration
  */
 protected static function setUserNamespaces($aUserNamespaceDefinition)
 {
     global $wgNamespacesWithSubpages, $wgContentNamespaces, $wgNamespacesToBeSearchedDefault, $bsSystemNamespaces;
     $oNamespaceManager = BsExtensionManager::getExtension('NamespaceManager');
     wfRunHooks('BSNamespaceManagerBeforeSetUsernamespaces', array($oNamespaceManager, &$bsSystemNamespaces));
     $sSaveContent = "<?php\n\n";
     foreach ($aUserNamespaceDefinition as $iNS => $aDefinition) {
         $bIsSystemNs = false;
         if (isset($bsSystemNamespaces[$iNS])) {
             $bIsSystemNs = true;
         }
         if ($aDefinition) {
             if (isset($aDefinition['alias']) && $aDefinition['alias']) {
                 $sDefName = strtoupper($aDefinition['alias']);
             } else {
                 if ($iNS >= 100) {
                     $sDefName = strtoupper($aDefinition['name']);
                 } else {
                     $sDefName = $bsSystemNamespaces[$iNS];
                 }
             }
             if ($bIsSystemNs) {
                 $sConstName = $bsSystemNamespaces[$iNS];
                 $sSaveContent .= "// START Namespace {$sConstName}\n";
                 $sSaveContent .= "if( !defined( \"{$sConstName}\" ) ) define(\"{$sConstName}\", {$iNS});\n";
                 if ($iNS >= 100) {
                     $sSaveContent .= "\$wgExtraNamespaces[{$sConstName}] = '" . $aDefinition['name'] . "';\n";
                 }
             } else {
                 $sConstName = 'NS_' . $sDefName;
                 $sSaveContent .= "// START Namespace {$sDefName}\n";
                 $sSaveContent .= "define(\"{$sConstName}\", {$iNS});\n";
                 $sSaveContent .= "\$wgExtraNamespaces[{$sConstName}] = '" . $aDefinition['name'] . "';\n";
             }
             wfRunHooks('NamespaceManager::writeNamespaceConfiguration', array(&$sSaveContent, $sConstName, $aDefinition));
             if (!$bIsSystemNs && isset($aDefinition['alias']) && $aDefinition['alias']) {
                 $sSaveContent .= "\$wgNamespaceAliases['{$aDefinition['alias']}'] = {$sConstName};\n";
             }
             $sSaveContent .= "// END Namespace {$sDefName}\n\n";
         }
     }
     $sConfigFile = BSCONFIGDIR . DS . 'nm-settings.php';
     $res = file_put_contents($sConfigFile, $sSaveContent);
     if ($res) {
         return array('success' => true, 'message' => wfMessage('bs-namespacemanager-nsadded')->plain());
     }
     return array('success' => false, 'message' => 'Not able to create or write "' . $sConfigFile . '".');
 }
 /**
  * Constructor of PageTemplatesAdmin class
  */
 public function __construct()
 {
     wfProfileIn('BS::' . __METHOD__);
     $this->oExtension = BsExtensionManager::getExtension('PageTemplates');
     wfProfileOut('BS::' . __METHOD__);
 }
 /**
  * Handles the get wanted articles ajax request.
  * @param string $sOut The server response string.
  * @return bool true on correct processing. JSON answer is in $sOut parameter.
  */
 public static function ajaxGetWantedArticles($iCount, $sSort, $sOrder, $sType, $sTitle)
 {
     if (BsCore::checkAccessAdmission('read') === false) {
         return true;
     }
     $aResult = array('success' => false, 'view' => '', 'message' => '');
     //Validation
     $oValidationICount = BsValidator::isValid('IntegerRange', $iCount, array('fullResponse' => true, 'lowerBoundary' => 1, 'upperBoundary' => 30));
     if ($oValidationICount->getErrorCode()) {
         return false;
     }
     if (!in_array($sSort, array('', 'time', 'title'))) {
         return false;
     }
     if (!in_array($sOrder, array('', 'ASC', 'DESC'))) {
         return false;
     }
     $oWantedArticle = BsExtensionManager::getExtension('WantedArticle');
     //Create list
     $aWishList = $oWantedArticle->getTitleListFromTitle($oWantedArticle->getDataSourceTemplateArticle()->getTitle());
     switch ($sSort) {
         case 'title':
             $aTitleList = $oWantedArticle->sortWishListByTitle($aWishList);
             break;
         case 'time':
         default:
             $aTitleList = $oWantedArticle->getDefaultTitleList($aWishList);
     }
     if ($sOrder == 'ASC') {
         $aTitleList = array_reverse($aTitleList);
     }
     $oWishListView = new ViewWantedArticleTag();
     $oWishListView->setTitle($sTitle)->setType($sType)->setOrder($sOrder)->setSort($sSort)->setCount($iCount)->setList($aTitleList);
     //result
     $aResult['success'] = true;
     $aResult['view'] = $oWishListView->execute();
     return json_encode($aResult);
 }
 public static function uploadFile()
 {
     if (wfReadOnly()) {
         global $wgReadOnly;
         $oAjaxResponse = new AjaxResponse(FormatJson::encode(array('success' => false, 'msg' => wfMessage('bs-readonly', $wgReadOnly)->escaped())));
         $oAjaxResponse->setContentType('text/html');
         return $oAjaxResponse;
     }
     global $wgRequest, $wgUser;
     self::unsetUserImage($wgUser);
     $oAvatars = BsExtensionManager::getExtension('Avatars');
     $sAvatarFileName = self::$sAvatarFilePrefix . $wgUser->getId() . ".png";
     $oStatus = BsFileSystemHelper::uploadAndConvertImage($wgRequest->getVal('name'), $oAvatars->mInfo[EXTINFO::NAME], $sAvatarFileName);
     if (!$oStatus->isGood()) {
         $aErrors = $oStatus->getErrorsArray();
         $aResult = json_encode(array('success' => false, 'msg' => $aErrors[0][0]));
     } else {
         $aResult = json_encode(array('success' => true, 'msg' => wfMessage('bs-avatars-upload-complete')->plain(), 'name' => $oStatus->getValue()));
         # found no way to regenerate thumbs. just delete thumb folder if it exists
         $oStatus = BsFileSystemHelper::deleteFolder('Avatars' . DS . 'thumb' . DS . $sAvatarFileName, true);
         if (!$oStatus->isGood()) {
             throw new MWException('FATAL: Avatar thumbs could no be deleted!');
         }
     }
     $oAjaxResponse = new AjaxResponse($aResult);
     $oAjaxResponse->setContentType('text/html');
     return $oAjaxResponse;
 }
 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);
 }
 /**
  * Notification for Shoutbox messages
  * @param int $iArticleId ID of the article the message was posted to.
  * @param int $iUserId ID of the user that posted the message.
  * @param string $sNick Nickname of the user that posted the message.
  * @param string $sMessage The message posted.
  * @param string $sTimestamp Time when the message was posted.
  * @return boolean Allow other binds to this hook to be executed. Always true.
  */
 public function onBSShoutBoxAfterInsertShout($iArticleId, $iUserId, $sNick, $sMessage, $sTimestamp)
 {
     wfProfileIn('BS::' . __METHOD__);
     global $wgUser;
     // TODO SW: use user id
     if ($wgUser->isAllowed('bot')) {
         return true;
     }
     #check if users are mentioned in post
     $oShoutbox = BsExtensionManager::getExtension("ShoutBox");
     $aUsers = $oShoutbox::getUsersMentioned($sMessage);
     $bNotify = false;
     #if there is any user in the post mentioned that is not the poster himself
     #trigger the watched article notification
     foreach ($aUsers as $oUser) {
         if ($oUser->getId() !== $iUserId) {
             $bNotify = true;
             break;
         }
     }
     if ($bNotify === false) {
         return true;
     }
     EchoEvent::create(array('type' => 'bs-shoutbox', 'title' => Title::newFromID($iArticleId), 'agent' => $wgUser, 'extra' => array('shoutmsg' => $sMessage, 'realname' => BsCore::getUserDisplayName($wgUser))));
     wfProfileOut('BS::' . __METHOD__);
     return true;
 }
 /**
  * Adds an user to the database
  * @param String $uUser Json encoded new user
  * @return string json encoded response
  */
 public static function addUser($sUsername, $sPassword, $sRePassword, $sEmail, $sRealname, $aGroups = array())
 {
     $res = $resDelGroups = $resInsGroups = $resERealUser = false;
     if (wfReadOnly()) {
         global $wgReadOnly;
         return FormatJson::encode(array('success' => false, 'message' => array(wfMessage('bs-readonly', $wgReadOnly)->plain())));
     }
     if (BsCore::checkAccessAdmission('wikiadmin') === false) {
         return true;
     }
     //This is to overcome username case issues with custom AuthPlugin (i.e. LDAPAuth)
     //LDAPAuth woud otherwise turn the username to first-char-upper-rest-lower-case
     //At the end of this method we switch $_SESSION['wsDomain'] back again
     $tmpDomain = isset($_SESSION['wsDomain']) ? $_SESSION['wsDomain'] : '';
     $_SESSION['wsDomain'] = 'local';
     $aResponse = array('success' => false, 'errors' => array(), 'message' => array());
     $sUsername = ucfirst($sUsername);
     if (User::isCreatableName($sUsername) === false) {
         $aResponse['errors'][] = array('id' => 'username', 'message' => wfMessage('bs-usermanager-invalid-uname')->plain());
     }
     if ($sEmail != '' && Sanitizer::validateEmail($sEmail) === false) {
         $aResponse['errors'][] = array('id' => 'email', 'message' => wfMessage('bs-usermanager-invalid-email-gen')->plain());
     }
     if ($sPassword == '') {
         $aResponse['errors'][] = array('id' => 'pass', 'message' => wfMessage('bs-usermanager-enter-pwd')->plain());
     }
     if (strpos($sRealname, '\\')) {
         $aResponse['errors'][] = array('id' => 'realname', 'message' => wfMessage('bs-usermanager-invalid-realname')->plain());
     }
     if ($sPassword != $sRePassword) {
         $aResponse['errors'][] = array('id' => 'repass', 'message' => wfMessage('badretype')->plain());
     }
     if (strtolower($sUsername) == strtolower($sPassword)) {
         $aResponse['errors'][] = array('id' => 'pass', 'message' => wfMessage('password-name-match')->plain());
     }
     $oNewUser = User::newFromName($sUsername);
     if ($oNewUser == null) {
         //Should not be neccessary as we check for username validity above
         $aResponse['errors'][] = array('id' => 'username', 'message' => wfMessage('bs-usermanager-invalid-uname')->plain());
     }
     if ($oNewUser instanceof User) {
         if ($oNewUser->getId() != 0) {
             $aResponse['errors'][] = array('id' => 'username', 'message' => wfMessage('bs-usermanager-user-exists')->plain());
         }
         if ($oNewUser->isValidPassword($sPassword) == false) {
             //TODO: $oNewUser->getPasswordValidity() returns a message key in case of error. Maybe we sould return this message.
             $aResponse['errors'][] = array('id' => 'pass', 'message' => wfMessage('bs-usermanager-invalid-pwd')->plain());
         }
     }
     if (!empty($aResponse['errors'])) {
         //In case that any error occurred
         return FormatJson::encode($aResponse);
     }
     $oNewUser->addToDatabase();
     $oNewUser->setPassword($sPassword);
     $oNewUser->setEmail($sEmail);
     $oNewUser->setRealName($sRealname);
     $oNewUser->setToken();
     $oNewUser->saveSettings();
     $dbw = wfGetDB(DB_MASTER);
     $resDelGroups = $dbw->delete('user_groups', array('ug_user' => $oNewUser->getId()));
     $resInsGroups = true;
     if (is_array($aGroups)) {
         foreach ($aGroups as $sGroup) {
             if (in_array($sGroup, self::$excludegroups)) {
                 continue;
             }
             $resInsGroups = $dbw->insert('user_groups', array('ug_user' => $oNewUser->getId(), 'ug_group' => addslashes($sGroup)));
         }
     }
     if ($resDelGroups === false || $resInsGroups === false) {
         $aAnswer['success'] = false;
         $aAnswer['message'][] = wfMessage('bs-usermanager-db-error')->plain();
     }
     $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1);
     $ssUpdate->doUpdate();
     $aResponse['success'] = true;
     $aResponse['message'][] = wfMessage('bs-usermanager-user-added')->plain();
     $_SESSION['wsDomain'] = $tmpDomain;
     $oUserManager = BsExtensionManager::getExtension('UserManager');
     wfRunHooks('BSUserManagerAfterAddUser', array($oUserManager, $oNewUser, array('username' => $sUsername, 'email' => $sEmail, 'password' => $sPassword, 'realname' => $sRealname)));
     return FormatJson::encode($aResponse);
 }