/** * Hook function for EditFilterMergedContent * * @param IContextSource $context * @param Content $content * @param Status $status * @param string $summary * @param User $user * @param bool $minoredit * * @return bool */ static function filterMergedContent(IContextSource $context, Content $content, Status $status, $summary, User $user, $minoredit) { $title = $context->getTitle(); if (isset($title->spamBlackListFiltered) && $title->spamBlackListFiltered) { // already filtered return true; } // get the link from the not-yet-saved page content. // no need to generate html to get external links $pout = $content->getParserOutput($title, null, null, false); $links = array_keys($pout->getExternalLinks()); // HACK: treat the edit summary as a link if ($summary !== '') { $links[] = $summary; } $spamObj = BaseBlacklist::getInstance('spam'); $matches = $spamObj->filter($links, $title); if ($matches !== false) { $status->fatal('spamprotectiontext'); foreach ($matches as $match) { $status->fatal('spamprotectionmatch', $match); } } // Always return true, EditPage will look at $status->isOk(). return true; }
/** * Generates a brief review form for a page * @param \IContextSource|\RequestContext $context * @param FlaggableWikiPage $article * @param Revision $rev */ public function __construct(IContextSource $context, FlaggableWikiPage $article, Revision $rev) { $this->user = $context->getUser(); $this->request = $context->getRequest(); $this->article = $article; $this->rev = $rev; }
function __construct(IContextSource $context, $userName = null, $search = '', $including = false) { global $wgMiserMode; $this->mIncluding = $including; if ($userName) { $nt = Title::newFromText($userName, NS_USER); if (!is_null($nt)) { $this->mUserName = $nt->getText(); $this->mQueryConds['img_user_text'] = $this->mUserName; } } if ($search != '' && !$wgMiserMode) { $this->mSearch = $search; $nt = Title::newFromURL($this->mSearch); if ($nt) { $dbr = wfGetDB(DB_SLAVE); $this->mQueryConds[] = 'LOWER(img_name)' . $dbr->buildLike($dbr->anyString(), strtolower($nt->getDBkey()), $dbr->anyString()); } } if (!$including) { if ($context->getRequest()->getText('sort', 'img_date') == 'img_date') { $this->mDefaultDirection = true; } else { $this->mDefaultDirection = false; } } else { $this->mDefaultDirection = true; } parent::__construct($context); }
public function getDisplayNameMessage(\IContextSource $context) { if ($this->getType() === self::TYPE_FEATURED) { return $context->msg('cx-suggestionlist-featured'); } return new \RawMessage($this->getName()); }
/** * @param $context IContextSource * @param $pageType */ public static function addNavigationLinks(IContextSource $context, $pageType) { $linkDefs = array('home' => 'Special:AbuseFilter', 'recentchanges' => 'Special:AbuseFilter/history', 'examine' => 'Special:AbuseFilter/examine', 'log' => 'Special:AbuseLog'); if ($context->getUser()->isAllowed('abusefilter-modify')) { $linkDefs = array_merge($linkDefs, array('test' => 'Special:AbuseFilter/test', 'tools' => 'Special:AbuseFilter/tools', 'import' => 'Special:AbuseFilter/import')); } // Save some translator work $msgOverrides = array('recentchanges' => 'abusefilter-filter-log'); $links = array(); foreach ($linkDefs as $name => $page) { // Give grep a chance to find the usages: // abusefilter-topnav-home, abusefilter-topnav-test, abusefilter-topnav-examine // abusefilter-topnav-log, abusefilter-topnav-tools, abusefilter-topnav-import $msgName = "abusefilter-topnav-{$name}"; if (isset($msgOverrides[$name])) { $msgName = $msgOverrides[$name]; } $msg = wfMessage($msgName)->parse(); $title = Title::newFromText($page); if ($name == $pageType) { $links[] = Xml::tags('strong', null, $msg); } else { $links[] = Linker::link($title, $msg); } } $linkStr = wfMessage('parentheses', $context->getLanguage()->pipeList($links))->text(); $linkStr = wfMessage('abusefilter-topnav')->parse() . " {$linkStr}"; $linkStr = Xml::tags('div', array('class' => 'mw-abusefilter-navigation'), $linkStr); $context->getOutput()->setSubtitle($linkStr); }
function __construct(IContextSource $context, $par = null) { $this->like = $context->getRequest()->getText('like'); $this->showbots = $context->getRequest()->getBool('showbots', 0); if (is_numeric($par)) { $this->setLimit($par); } parent::__construct($context); }
/** * Constructor. * * @param IContextSource $context * @param array $conds * @param string $className */ public function __construct(IContextSource $context, array $conds, $className) { $this->conds = $conds; $this->className = $className; $this->context = $context; $this->mDefaultDirection = true; parent::__construct($context); $this->context->getOutput()->addModules('ep.pager'); }
/** * Display a pager with articles. * * @since 0.1 * * @param IContextSource $context * @param array $conditions */ public static function displayPager(IContextSource $context, array $conditions = array()) { $pager = new EPArticlePager($context, $conditions); if ($pager->getNumRows()) { $context->getOutput()->addHTML($pager->getFilterControl() . $pager->getNavigationBar() . $pager->getBody() . $pager->getNavigationBar() . $pager->getMultipleItemControl()); } else { $context->getOutput()->addHTML($pager->getFilterControl(true)); $context->getOutput()->addWikiMsg('ep-articles-noresults'); } }
/** * Check whether external edit or diff should be used. * * @param $context IContextSource context to use * @param $type String can be either 'edit' or 'diff' * @return Bool */ public static function useExternalEngine(IContextSource $context, $type) { global $wgUseExternalEditor; if (!$wgUseExternalEditor) { return false; } $pref = $type == 'diff' ? 'externaldiff' : 'externaleditor'; $request = $context->getRequest(); return !$request->getVal('internaledit') && ($context->getUser()->getOption($pref) || $request->getVal('externaledit')); }
/** * Fetch an appropriate changes list class for the specified context * Some users might want to use an enhanced list format, for instance * * @param $context IContextSource to use * @return ChangesList|EnhancedChangesList|OldChangesList derivative */ public static function newFromContext( IContextSource $context ) { $user = $context->getUser(); $sk = $context->getSkin(); $list = null; if ( wfRunHooks( 'FetchChangesList', array( $user, &$sk, &$list ) ) ) { $new = $context->getRequest()->getBool( 'enhanced', $user->getOption( 'usenewrc' ) ); return $new ? new EnhancedChangesList( $context ) : new OldChangesList( $context ); } else { return $list; } }
/** * @param IContextSource|Skin $obj * @throws MWException */ public function __construct($obj) { if ($obj instanceof Skin) { // @todo: deprecate constructing with Skin $context = $obj->getContext(); } else { if (!$obj instanceof IContextSource) { throw new MWException('EnhancedChangesList must be constructed with a ' . 'context source or skin.'); } $context = $obj; } parent::__construct($context); // message is set by the parent ChangesList class $this->cacheEntryFactory = new RCCacheEntryFactory($context, $this->message); }
function __construct(IContextSource $context, $userName = null, $search = '', $including = false, $showAll = false) { $this->mIncluding = $including; $this->mShowAll = $showAll; if ($userName) { $nt = Title::newFromText($userName, NS_USER); if (!is_null($nt)) { $this->mUserName = $nt->getText(); } } if ($search !== '' && !$this->getConfig()->get('MiserMode')) { $this->mSearch = $search; $nt = Title::newFromURL($this->mSearch); if ($nt) { $dbr = wfGetDB(DB_SLAVE); $this->mQueryConds[] = 'LOWER(img_name)' . $dbr->buildLike($dbr->anyString(), strtolower($nt->getDBkey()), $dbr->anyString()); } } if (!$including) { if ($context->getRequest()->getText('sort', 'img_date') == 'img_date') { $this->mDefaultDirection = IndexPager::DIR_DESCENDING; } else { $this->mDefaultDirection = IndexPager::DIR_ASCENDING; } } else { $this->mDefaultDirection = IndexPager::DIR_DESCENDING; } parent::__construct($context); }
/** * Return a link to the edit page, with the text * saying "view source" if the user can't edit the page * * @param Title $titleObj * @return string */ private function buildEditLink(Title $titleObj) { if ($titleObj->quickUserCan('edit', $this->context->getUser())) { $linkMsg = 'editlink'; } else { $linkMsg = 'viewsourcelink'; } return $this->linkRenderer->makeLink($titleObj, $this->context->msg($linkMsg)->text(), [], ['action' => 'edit']); }
/** * Generate help for the specified modules * * Help is placed into the OutputPage object returned by * $context->getOutput(). * * Recognized options include: * - headerlevel: (int) Header tag level * - nolead: (bool) Skip the inclusion of api-help-lead * - noheader: (bool) Skip the inclusion of the top-level section headers * - submodules: (bool) Include help for submodules of the current module * - recursivesubmodules: (bool) Include help for submodules recursively * - helptitle: (string) Title to link for additional modules' help. Should contain $1. * - toc: (bool) Include a table of contents * * @param IContextSource $context * @param ApiBase[]|ApiBase $modules * @param array $options Formatting options (described above) * @return string */ public static function getHelp(IContextSource $context, $modules, array $options) { global $wgContLang; if (!is_array($modules)) { $modules = array($modules); } $out = $context->getOutput(); $out->addModuleStyles('mediawiki.hlist'); $out->addModuleStyles('mediawiki.apihelp'); if (!empty($options['toc'])) { $out->addModules('mediawiki.toc'); } $out->setPageTitle($context->msg('api-help-title')); $cache = ObjectCache::getMainWANInstance(); $cacheKey = null; if (count($modules) == 1 && $modules[0] instanceof ApiMain && $options['recursivesubmodules'] && $context->getLanguage() === $wgContLang) { $cacheHelpTimeout = $context->getConfig()->get('APICacheHelpTimeout'); if ($cacheHelpTimeout > 0) { // Get help text from cache if present $cacheKey = wfMemcKey('apihelp', $modules[0]->getModulePath(), (int) (!empty($options['toc'])), str_replace(' ', '_', SpecialVersion::getVersion('nodb'))); $cached = $cache->get($cacheKey); if ($cached) { $out->addHTML($cached); return; } } } if ($out->getHTML() !== '') { // Don't save to cache, there's someone else's content in the page // already $cacheKey = null; } $options['recursivesubmodules'] = !empty($options['recursivesubmodules']); $options['submodules'] = $options['recursivesubmodules'] || !empty($options['submodules']); // Prepend lead if (empty($options['nolead'])) { $msg = $context->msg('api-help-lead'); if (!$msg->isDisabled()) { $out->addHTML($msg->parseAsBlock()); } } $haveModules = array(); $html = self::getHelpInternal($context, $modules, $options, $haveModules); if (!empty($options['toc']) && $haveModules) { $out->addHTML(Linker::generateTOC($haveModules, $context->getLanguage())); } $out->addHTML($html); $helptitle = isset($options['helptitle']) ? $options['helptitle'] : null; $html = self::fixHelpLinks($out->getHTML(), $helptitle, $haveModules); $out->clearHTML(); $out->addHTML($html); if ($cacheKey !== null) { $cache->set($cacheKey, $out->getHTML(), $cacheHelpTimeout); } }
/** * @param IContextSource $context * * @return string HTML */ public function getHtml(IContextSource $context) { $context->getOutput()->addModules('ext.translate.statsbar'); $total = $this->stats[MessageGroupStats::TOTAL]; $proofread = $this->stats[MessageGroupStats::PROOFREAD]; $translated = $this->stats[MessageGroupStats::TRANSLATED]; $fuzzy = $this->stats[MessageGroupStats::FUZZY]; if (!$total) { $untranslated = null; $wproofread = $wtranslated = $wfuzzy = $wuntranslated = 0; } else { // Proofread is subset of translated $untranslated = $total - $translated - $fuzzy; $wproofread = round(100 * $proofread / $total, 2); $wtranslated = round(100 * ($translated - $proofread) / $total, 2); $wfuzzy = round(100 * $fuzzy / $total, 2); $wuntranslated = round(100 - $wproofread - $wtranslated - $wfuzzy, 2); } return Html::rawElement('div', array('class' => 'tux-statsbar', 'data-total' => $total, 'data-group' => $this->group, 'data-language' => $this->language), Html::element('span', array('class' => 'tux-proofread', 'style' => "width: {$wproofread}%", 'data-proofread' => $proofread)) . Html::element('span', array('class' => 'tux-translated', 'style' => "width: {$wtranslated}%", 'data-translated' => $translated)) . Html::element('span', array('class' => 'tux-fuzzy', 'style' => "width: {$wfuzzy}%", 'data-fuzzy' => $fuzzy)) . Html::element('span', array('class' => 'tux-untranslated', 'style' => "width: {$wuntranslated}%", 'data-untranslated' => $untranslated))); }
/** * Prepare the label for a protection selector option * * @param string $permission Permission required * @return string */ private function getOptionLabel($permission) { if ($permission == '') { return $this->mContext->msg('protect-default')->text(); } else { // Messages: protect-level-autoconfirmed, protect-level-sysop $msg = $this->mContext->msg("protect-level-{$permission}"); if ($msg->exists()) { return $msg->text(); } return $this->mContext->msg('protect-fallback', $permission)->text(); } }
private function main() { global $wgUseFileCache, $wgTitle, $wgUseAjax; wfProfileIn(__METHOD__); $request = $this->context->getRequest(); // Send Ajax requests to the Ajax dispatcher. if ($wgUseAjax && $request->getVal('action', 'view') == 'ajax') { // Set a dummy title, because $wgTitle == null might break things $title = Title::makeTitle(NS_MAIN, 'AJAX'); $this->context->setTitle($title); $wgTitle = $title; $dispatcher = new AjaxDispatcher(); $dispatcher->performAction(); wfProfileOut(__METHOD__); return; } // Get title from request parameters, // is set on the fly by parseTitle the first time. $title = $this->getTitle(); $action = $this->getAction(); $wgTitle = $title; if ($wgUseFileCache && $title->getNamespace() >= 0) { wfProfileIn('main-try-filecache'); if (HTMLFileCache::useFileCache($this->context)) { // Try low-level file cache hit $cache = HTMLFileCache::newFromTitle($title, $action); if ($cache->isCacheGood()) { // Check incoming headers to see if client has this cached $timestamp = $cache->cacheTimestamp(); if (!$this->context->getOutput()->checkLastModified($timestamp)) { $cache->loadFromFileCache($this->context); } // Do any stats increment/watchlist stuff $this->context->getWikiPage()->doViewUpdates($this->context->getUser()); // Tell OutputPage that output is taken care of $this->context->getOutput()->disable(); wfProfileOut('main-try-filecache'); wfProfileOut(__METHOD__); return; } } wfProfileOut('main-try-filecache'); } $this->performRequest(); // Now commit any transactions, so that unreported errors after // output() don't roll back the whole DB transaction wfGetLBFactory()->commitMasterChanges(); // Output everything! $this->context->getOutput()->output(); wfProfileOut(__METHOD__); }
private function main() { global $wgUseFileCache, $wgTitle, $wgUseAjax; wfProfileIn(__METHOD__); $request = $this->context->getRequest(); // Send Ajax requests to the Ajax dispatcher. if ($wgUseAjax && $request->getVal('action', 'view') == 'ajax') { // Set a dummy title, because $wgTitle == null might break things // Wikia change - start // @author macbre, wladek $title = Wikia::createTitleFromRequest($request); // Wikia change - end $this->context->setTitle($title); $wgTitle = $title; $dispatcher = new AjaxDispatcher(); $dispatcher->performAction(); wfProfileOut(__METHOD__); return; } // Get title from request parameters, // is set on the fly by parseTitle the first time. $title = $this->getTitle(); $action = $this->getAction(); $wgTitle = $title; if ($wgUseFileCache && $title->getNamespace() >= 0) { wfProfileIn('main-try-filecache'); if (HTMLFileCache::useFileCache($this->context)) { // Try low-level file cache hit $cache = HTMLFileCache::newFromTitle($title, $action); if ($cache->isCacheGood()) { // Check incoming headers to see if client has this cached $timestamp = $cache->cacheTimestamp(); if (!$this->context->getOutput()->checkLastModified($timestamp)) { $cache->loadFromFileCache($this->context); } // Do any stats increment/watchlist stuff $this->context->getWikiPage()->doViewUpdates($this->context->getUser()); // Tell OutputPage that output is taken care of $this->context->getOutput()->disable(); wfProfileOut('main-try-filecache'); wfProfileOut(__METHOD__); return; } } wfProfileOut('main-try-filecache'); } $this->performRequest(); $this->finalCleanup(); wfProfileOut(__METHOD__); }
/** * Build protection level selector * * @param string $action Action to protect * @param string $selected Current protection level * @return string HTML fragment */ function buildSelector($action, $selected) { // If the form is disabled, display all relevant levels. Otherwise, // just show the ones this user can use. $levels = MWNamespace::getRestrictionLevels($this->mTitle->getNamespace(), $this->disabled ? null : $this->mContext->getUser()); $id = 'mwProtect-level-' . $action; $attribs = array('id' => $id, 'name' => $id, 'size' => count($levels)) + $this->disabledAttrib; $out = Xml::openElement('select', $attribs); foreach ($levels as $key) { $out .= Xml::option($this->getOptionLabel($key), $key, $key == $selected); } $out .= Xml::closeElement('select'); return $out; }
/** * MediaWiki extensions all should have key in their i18n files * describing them. This override method implements the logic * to retrieve them. Also URLs are included if available. * Needs the Configure extension. * @param IContextSource $context * @return string */ public function getDescription(IContextSource $context = null) { $language = $this->getSourceLanguage(); if ($context) { $language = $context->getLanguage()->getCode(); } $msgkey = $this->getFromConf('BASIC', 'descriptionmsg'); $desc = ''; if ($msgkey) { $desc = $this->getMessage($msgkey, $language); if (strval($desc) === '') { $desc = $this->getMessage($msgkey, $this->getSourceLanguage()); } } if (strval($desc) === '') { // That failed, default to 'description' $desc = parent::getDescription($context); } $url = $this->getFromConf('BASIC', 'extensionurl'); if ($url) { $desc .= "\n\n{$url}"; } return $desc; }
private function main() { global $wgUseFileCache, $wgTitle, $wgUseAjax; wfProfileIn(__METHOD__); # Set title from request parameters $wgTitle = $this->getTitle(); $action = $this->getAction(); $user = $this->context->getUser(); # Send Ajax requests to the Ajax dispatcher. if ($wgUseAjax && $action == 'ajax') { $dispatcher = new AjaxDispatcher(); $dispatcher->performAction(); wfProfileOut(__METHOD__); return; } if ($wgUseFileCache && $wgTitle->getNamespace() != NS_SPECIAL) { wfProfileIn('main-try-filecache'); // Raw pages should handle cache control on their own, // even when using file cache. This reduces hits from clients. if (HTMLFileCache::useFileCache()) { /* Try low-level file cache hit */ $cache = new HTMLFileCache($wgTitle, $action); if ($cache->isFileCacheGood()) { /* Check incoming headers to see if client has this cached */ $timestamp = $cache->fileCacheTime(); if (!$this->context->getOutput()->checkLastModified($timestamp)) { $cache->loadFromFileCache(); } # Do any stats increment/watchlist stuff $article = WikiPage::factory($wgTitle); $article->doViewUpdates($user); # Tell OutputPage that output is taken care of $this->context->getOutput()->disable(); wfProfileOut('main-try-filecache'); wfProfileOut(__METHOD__); return; } } wfProfileOut('main-try-filecache'); } $this->performRequest(); $this->finalCleanup(); wfProfileOut(__METHOD__); }
/** * RequestContextCreateSkin hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/RequestContextCreateSkin * * @param IContextSource $context * @param Skin $skin * @return bool */ public static function onRequestContextCreateSkin($context, &$skin) { // FIXME: This shouldn't be a global, it should be possible for other extensions // to set this via a static variable or set function in ULS global $wgULSPosition; $mobileContext = MobileContext::singleton(); $mobileContext->doToggling(); if (!$mobileContext->shouldDisplayMobileView() || $mobileContext->isBlacklistedPage()) { return true; } // enable wgUseMediaWikiUIEverywhere self::enableMediaWikiUI(); // FIXME: Remove hack around Universal Language selector bug 57091 $wgULSPosition = 'none'; // Handle any X-Analytics header values in the request by adding them // as log items. X-Analytics header values are serialized key=value // pairs, separated by ';', used for analytics purposes. if ($xanalytics = $mobileContext->getRequest()->getHeader('X-Analytics')) { $xanalytics_arr = explode(';', $xanalytics); if (count($xanalytics_arr) > 1) { foreach ($xanalytics_arr as $xanalytics_item) { $mobileContext->addAnalyticsLogItemFromXAnalytics($xanalytics_item); } } else { $mobileContext->addAnalyticsLogItemFromXAnalytics($xanalytics); } } // log whether user is using alpha/beta/stable $mobileContext->logMobileMode(); $skinName = $mobileContext->getMFConfig()->get('MFDefaultSkinClass'); $betaSkinName = $skinName . 'Beta'; $alphaSkinName = $skinName . 'Alpha'; // Force alpha for test mode to sure all modules can run $name = $context->getTitle()->getDBkey(); $inTestMode = $name === SpecialPage::getTitleFor('JavaScriptTest', 'qunit')->getDBkey(); if (($mobileContext->isAlphaGroupMember() || $inTestMode) && class_exists($alphaSkinName)) { $skinName = $alphaSkinName; } elseif ($mobileContext->isBetaGroupMember() && class_exists($betaSkinName)) { $skinName = $betaSkinName; } $skin = new $skinName($context); return false; }
public static function onGetEmailAuthentication(User &$user, IContextSource $context, &$disableEmailPrefs, &$emailauthenticated) { if ($user->getEmail()) { $emailTimestamp = $user->getEmailAuthenticationTimestamp(); $optionNewEmail = $user->getGlobalAttribute('new_email'); $msgKeyPrefixEmail = empty($optionNewEmail) && !$emailTimestamp ? 'usersignup-user-pref-unconfirmed-' : 'usersignup-user-pref-'; if (empty($optionNewEmail) && $emailTimestamp) { $lang = $context->getLanguage(); $displayUser = $context->getUser(); $time = $lang->userTimeAndDate($emailTimestamp, $displayUser); $d = $lang->userDate($emailTimestamp, $displayUser); $t = $lang->userTime($emailTimestamp, $displayUser); $emailauthenticated = $context->msg($msgKeyPrefixEmail . 'emailauthenticated', $time, $d, $t)->parse() . '<br />'; $disableEmailPrefs = false; } else { $disableEmailPrefs = true; $emailauthenticated = $context->msg($msgKeyPrefixEmail . 'emailnotauthenticated', array($optionNewEmail))->parse() . '<br />' . Linker::linkKnown(SpecialPage::getTitleFor('Confirmemail'), $context->msg('usersignup-user-pref-emailconfirmlink')->escaped()) . '<br />'; } } else { $disableEmailPrefs = true; $emailauthenticated = $context->msg('usersignup-user-pref-noemailprefs')->escaped(); } return true; }
/** * @param $context IContextSource * @return array */ static function getTimezoneOptions( IContextSource $context ) { $opt = array(); global $wgLocalTZoffset; $timestamp = MWTimestamp::getLocalInstance(); // Check that $wgLocalTZoffset is the same as the local time zone offset if ( $wgLocalTZoffset == $timestamp->format( 'Z' ) / 60 ) { $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $timestamp->getTimezone()->getName() )->text(); } else { $tzstring = sprintf( '%+03d:%02d', floor( $wgLocalTZoffset / 60 ), abs( $wgLocalTZoffset ) % 60 ); $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text(); } $opt[$server_tz_msg] = "System|$wgLocalTZoffset"; $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other'; $opt[$context->msg( 'guesstimezone' )->text()] = 'guess'; if ( function_exists( 'timezone_identifiers_list' ) ) { # Read timezone list $tzs = timezone_identifiers_list(); sort( $tzs ); $tzRegions = array(); $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text(); $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text(); $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text(); $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text(); $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text(); $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text(); $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text(); $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text(); $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text(); $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text(); asort( $tzRegions ); $prefill = array_fill_keys( array_values( $tzRegions ), array() ); $opt = array_merge( $opt, $prefill ); $now = date_create( 'now' ); foreach ( $tzs as $tz ) { $z = explode( '/', $tz, 2 ); # timezone_identifiers_list() returns a number of # backwards-compatibility entries. This filters them out of the # list presented to the user. if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) { continue; } # Localize region $z[0] = $tzRegions[$z[0]]; $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 ); $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] ); $value = "ZoneInfo|$minDiff|$tz"; $opt[$z[0]][$display] = $value; } } return $opt; }
/** * Just like executePath() but will override global variables and execute * the page in "inclusion" mode. Returns true if the execution was * successful or false if there was no such special page, or a title object * if it was a redirect. * * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang * variables so that the special page will get the context it'd expect on a * normal request, and then restores them to their previous values after. * * @param $title Title * @param $context IContextSource * * @return String: HTML fragment */ static function capturePath(Title $title, IContextSource $context) { global $wgOut, $wgTitle, $wgRequest, $wgUser, $wgLang; // Save current globals $oldTitle = $wgTitle; $oldOut = $wgOut; $oldRequest = $wgRequest; $oldUser = $wgUser; $oldLang = $wgLang; // Set the globals to the current context $wgTitle = $title; $wgOut = $context->getOutput(); $wgRequest = $context->getRequest(); $wgUser = $context->getUser(); $wgLang = $context->getLanguage(); // The useful part $ret = self::executePath($title, $context, true); // And restore the old globals $wgTitle = $oldTitle; $wgOut = $oldOut; $wgRequest = $oldRequest; $wgUser = $oldUser; $wgLang = $oldLang; return $ret; }
/** * Handler for non-standard (edit/log) entries that need IP data * * @param $context IContextSource * @param $data Array * @return bool */ protected static function onLoggableUserIPData(IContextSource $context, array $data) { $user = $context->getUser(); $request = $context->getRequest(); // Get IP address $ip = $request->getIP(); // Get XFF header $xff = $request->getHeader('X-Forwarded-For'); list($xff_ip, $isSquidOnly) = IP::getClientIPfromXFF($xff); // Get agent $agent = $request->getHeader('User-Agent'); $dbw = wfGetDB(DB_MASTER); $cuc_id = $dbw->nextSequenceValue('cu_changes_cu_id_seq'); $rcRow = array('cuc_id' => $cuc_id, 'cuc_page_id' => $data['pageid'], 'cuc_namespace' => $data['namespace'], 'cuc_title' => $data['title'], 'cuc_minor' => 0, 'cuc_user' => $user->getId(), 'cuc_user_text' => $user->getName(), 'cuc_actiontext' => $data['action'], 'cuc_comment' => $data['comment'], 'cuc_this_oldid' => 0, 'cuc_last_oldid' => 0, 'cuc_type' => RC_LOG, 'cuc_timestamp' => $dbw->timestamp($data['timestamp']), 'cuc_ip' => IP::sanitizeIP($ip), 'cuc_ip_hex' => $ip ? IP::toHex($ip) : null, 'cuc_xff' => !$isSquidOnly ? $xff : '', 'cuc_xff_hex' => $xff_ip && !$isSquidOnly ? IP::toHex($xff_ip) : null, 'cuc_agent' => $agent); $dbw->insert('cu_changes', $rcRow, __METHOD__); return true; }
protected function acceptRequest(IContextSource $context) { global $wgAuth, $wgAccountRequestTypes, $wgConfirmAccountSaveInfo; global $wgAllowAccountRequestFiles, $wgConfirmAccountFSRepos; $accReq = $this->accountReq; // convenience # Now create user and check if the name is valid $user = User::newFromName($this->userName, 'creatable'); if (!$user) { return array('accountconf_invalid_name', wfMsgHtml('noname')); } # Check if account name is already in use if (0 != $user->idForName() || $wgAuth->userExists($user->getName())) { return array('accountconf_user_exists', wfMsgHtml('userexists')); } $dbw = wfGetDB(DB_MASTER); $dbw->begin(); # Make a random password $p = User::randomPassword(); # Insert the new user into the DB... $tokenExpires = $accReq->getEmailTokenExpires(); $authenticated = $accReq->getEmailAuthTimestamp(); $params = array('real_name' => $accReq->getRealName(), 'newpassword' => User::crypt($p), 'email' => $accReq->getEmail(), 'email_authenticated' => $dbw->timestampOrNull($authenticated), 'email_token_expires' => $dbw->timestamp($tokenExpires), 'email_token' => $accReq->getEmailToken()); $user = User::createNew($user->getName(), $params); # Grant any necessary rights (exclude blank or dummy groups) $group = self::getGroupFromType($this->type); if ($group != '' && $group != 'user' && $group != '*') { $user->addGroup($group); } $acd_id = null; // used for rollback cleanup # Save account request data to credentials system if ($wgConfirmAccountSaveInfo) { $key = $accReq->getFileStorageKey(); # Copy any attached files to new storage group if ($wgAllowAccountRequestFiles && $key) { $repoOld = new FSRepo($wgConfirmAccountFSRepos['accountreqs']); $repoNew = new FSRepo($wgConfirmAccountFSRepos['accountcreds']); $pathRel = UserAccountRequest::relPathFromKey($key); $oldPath = $repoOld->getZonePath('public') . '/' . $pathRel; $triplet = array($oldPath, 'public', $pathRel); $status = $repoNew->storeBatch(array($triplet)); // copy! if (!$status->isOK()) { $dbw->rollback(); # DELETE new rows in case there was a COMMIT somewhere $this->acceptRequest_rollback($dbw, $user->getId(), $acd_id); return array('accountconf_copyfailed', $context->getOutput()->parse($status->getWikiText())); } } $acd_id = $dbw->nextSequenceValue('account_credentials_acd_id_seq'); # Move request data into a separate table $dbw->insert('account_credentials', array('acd_user_id' => $user->getID(), 'acd_real_name' => $accReq->getRealName(), 'acd_email' => $accReq->getEmail(), 'acd_email_authenticated' => $dbw->timestampOrNull($authenticated), 'acd_bio' => $accReq->getBio(), 'acd_notes' => $accReq->getNotes(), 'acd_urls' => $accReq->getUrls(), 'acd_ip' => $accReq->getIP(), 'acd_filename' => $accReq->getFileName(), 'acd_storage_key' => $accReq->getFileStorageKey(), 'acd_areas' => $accReq->getAreas('flat'), 'acd_registration' => $dbw->timestamp($accReq->getRegistration()), 'acd_accepted' => $dbw->timestamp(), 'acd_user' => $this->admin->getID(), 'acd_comment' => $this->reason, 'acd_id' => $acd_id), __METHOD__); if (is_null($acd_id)) { $acd_id = $dbw->insertId(); // set $acd_id to ID inserted } } # Add to global user login system (if there is one) if (!$wgAuth->addUser($user, $p, $accReq->getEmail(), $accReq->getRealName())) { $dbw->rollback(); # DELETE new rows in case there was a COMMIT somewhere $this->acceptRequest_rollback($dbw, $user->getId(), $acd_id); return array('accountconf_externaldberror', wfMsgHtml('externaldberror')); } # OK, now remove the request from the queue $accReq->remove(); # Commit this if we make past the CentralAuth system # and the groups are added. Next step is sending out an # email, which we cannot take back... $dbw->commit(); # Prepare a temporary password email... if ($this->reason != '') { $msg = "confirmaccount-email-body2-pos{$this->type}"; # If the user is in a group and there is a welcome for that group, use it if ($group && !wfEmptyMsg($msg)) { $ebody = wfMsgExt($msg, array('parsemag', 'content'), $user->getName(), $p, $this->reason); # Use standard if none found... } else { $ebody = wfMsgExt('confirmaccount-email-body2', array('parsemag', 'content'), $user->getName(), $p, $this->reason); } } else { $msg = "confirmaccount-email-body-pos{$this->type}"; # If the user is in a group and there is a welcome for that group, use it if ($group && !wfEmptyMsg($msg)) { $ebody = wfMsgExt($msg, array('parsemag', 'content'), $user->getName(), $p, $this->reason); # Use standard if none found... } else { $ebody = wfMsgExt('confirmaccount-email-body', array('parsemag', 'content'), $user->getName(), $p, $this->reason); } } # Actually send out the email (@TODO: rollback on failure including $wgAuth) $result = $user->sendMail(wfMsgForContent('confirmaccount-email-subj'), $ebody); /* if ( !$result->isOk() ) { # DELETE new rows in case there was a COMMIT somewhere $this->acceptRequest_rollback( $dbw, $user->getId(), $acd_id ); return array( 'accountconf_mailerror', wfMsg( 'mailerror', $context->getOutput()->parse( $result->getWikiText() ) ) ); } */ # Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); # Safe to hook/log now... wfRunHooks('AddNewAccount', array($user, false)); $user->addNewUserLogEntry(); # Clear cache for notice of how many account requests there are ConfirmAccount::clearAccountRequestCountCache(); # Delete any attached file and don't stop the whole process if this fails if ($wgAllowAccountRequestFiles) { $key = $accReq->getFileStorageKey(); if ($key) { $repoOld = new FSRepo($wgConfirmAccountFSRepos['accountreqs']); $pathRel = UserAccountRequest::relPathFromKey($key); $oldPath = $repoOld->getZonePath('public') . '/' . $pathRel; if (file_exists($oldPath)) { unlink($oldPath); // delete! } } } # Start up the user's userpages if set to do so. # Will not append, so previous content will be blanked. $this->createUserPage($user); # Greet the new user if set to do so. $this->createUserTalkPage($user); return array(true, null); }
/** * Returns the default nav items for @see displayNavigation. * * @since 0.1 * * @return array */ public static function getDefaultNavigationItems(IContextSource $context) { $items = array(wfMsg('ep-nav-orgs') => SpecialPage::getTitleFor('Institutions'), wfMsg('ep-nav-courses') => SpecialPage::getTitleFor('Courses')); $items[wfMsg('ep-nav-students')] = SpecialPage::getTitleFor('Students'); $items[wfMsg('ep-nav-oas')] = SpecialPage::getTitleFor('OnlineAmbassadors'); $items[wfMsg('ep-nav-cas')] = SpecialPage::getTitleFor('CampusAmbassadors'); $user = $context->getUser(); if (EPStudent::has(array('user_id' => $user->getId()))) { $items[wfMsg('ep-nav-mycourses')] = SpecialPage::getTitleFor('MyCourses'); } if ($user->isAllowed('ep-online') && EPOA::newFromUser($user)->hasCourse()) { $items[wfMsg('ep-nav-oaprofile')] = SpecialPage::getTitleFor('OnlineAmbassadorProfile'); } if ($user->isAllowed('ep-campus') && EPCA::newFromUser($user)->hasCourse()) { $items[wfMsg('ep-nav-caprofile')] = SpecialPage::getTitleFor('CampusAmbassadorProfile'); } return $items; }
/** * Just like executePath() but will override global variables and execute * the page in "inclusion" mode. Returns true if the execution was * successful or false if there was no such special page, or a title object * if it was a redirect. * * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang * variables so that the special page will get the context it'd expect on a * normal request, and then restores them to their previous values after. * * @param Title $title * @param IContextSource $context * @return string HTML fragment */ public static function capturePath(Title $title, IContextSource $context) { global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang; $main = RequestContext::getMain(); // Save current globals and main context $glob = ['title' => $wgTitle, 'output' => $wgOut, 'request' => $wgRequest, 'user' => $wgUser, 'language' => $wgLang]; $ctx = ['title' => $main->getTitle(), 'output' => $main->getOutput(), 'request' => $main->getRequest(), 'user' => $main->getUser(), 'language' => $main->getLanguage()]; // Override $wgTitle = $title; $wgOut = $context->getOutput(); $wgRequest = $context->getRequest(); $wgUser = $context->getUser(); $wgLang = $context->getLanguage(); $main->setTitle($title); $main->setOutput($context->getOutput()); $main->setRequest($context->getRequest()); $main->setUser($context->getUser()); $main->setLanguage($context->getLanguage()); // The useful part $ret = self::executePath($title, $context, true); // Restore old globals and context $wgTitle = $glob['title']; $wgOut = $glob['output']; $wgRequest = $glob['request']; $wgUser = $glob['user']; $wgLang = $glob['language']; $main->setTitle($ctx['title']); $main->setOutput($ctx['output']); $main->setRequest($ctx['request']); $main->setUser($ctx['user']); $main->setLanguage($ctx['language']); return $ret; }
/** * Get a ParserOptions object from a IContextSource object * * @param IContextSource $context * @return ParserOptions */ public static function newFromContext(IContextSource $context) { return new ParserOptions($context->getUser(), $context->getLanguage()); }