static function onParserFirstCallSetup(Parser $parser) { if (!ExtensionRegistry::getInstance()->isLoaded('Math')) { die("The DMath extension requires the Math extension, please include it."); } $parser->setHook('dmath', 'DMathParse::dmathTagHook'); $parser->setHook('math', 'DMathParse::mathTagHook'); }
public function __construct() { parent::__construct(); $paths = []; // Autodiscover extension unit tests $registry = ExtensionRegistry::getInstance(); foreach ($registry->getAllThings() as $info) { $paths[] = dirname($info['path']) . '/tests/phpunit'; } // Extensions can return a list of files or directories Hooks::run('UnitTestsList', [&$paths]); foreach (array_unique($paths) as $path) { if (is_dir($path)) { // If the path is a directory, search for test cases. // @since 1.24 $suffixes = ['Test.php']; $fileIterator = new File_Iterator_Facade(); $matchingFiles = $fileIterator->getFilesAsArray($path, $suffixes); $this->addTestFiles($matchingFiles); } elseif (file_exists($path)) { // Add a single test case or suite class $this->addTestFile($path); } } if (!$paths) { $this->addTest(new DummyExtensionsTest('testNothing')); } }
/** * @return ExtensionRegistry */ public static function getInstance() { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; }
public static function providePassesValidation() { $values = []; foreach (ExtensionRegistry::getInstance()->getAllThings() as $thing) { $values[] = [$thing['path']]; } return $values; }
/** * @dataProvider getNameProvider */ public function testGetName($lang, $in, $expected) { if ($in !== null && !\ExtensionRegistry::getInstance()->isLoaded('CLDR')) { $this->markTestSkipped('CLDR extension required for full language name support'); } $languageNameLookup = new LanguageNameLookup($in); $name = $languageNameLookup->getName($lang); $this->assertSame($expected, $name); }
private function getEditActionArgs() { // default is wikitext editor $args = array('name' => 'action', 'value' => 'edit'); // check, if VE is installed and VE editor is requested if (ExtensionRegistry::getInstance()->isLoaded('VisualEditor') && $this->mUseVE) { $args = array('name' => 'veaction', 'value' => 'edit'); } return $args; }
protected function loadFromDefinition() { if ($this->definition === null) { return; } // Core default themes $themes = array('default' => 'mediawiki'); $themes += ExtensionRegistry::getInstance()->getAttribute('SkinOOUIThemes'); $name = $this->definition['name']; $rootPath = $this->definition['rootPath']; $definition = array(); foreach ($themes as $skin => $theme) { // TODO Allow extensions to specify this path somehow $dataPath = $this->localBasePath . '/' . $rootPath . '/' . $theme . '/' . $name . '.json'; if (file_exists($dataPath)) { $data = json_decode(file_get_contents($dataPath), true); $fixPath = function (&$path) use($rootPath, $theme) { // TODO Allow extensions to specify this path somehow $path = $rootPath . '/' . $theme . '/' . $path; }; array_walk($data['images'], function (&$value) use($fixPath) { if (is_string($value['file'])) { $fixPath($value['file']); } elseif (is_array($value['file'])) { array_walk_recursive($value['file'], $fixPath); } }); } else { $data = array(); } foreach ($data as $key => $value) { switch ($key) { case 'images': case 'variants': $definition[$key][$skin] = $data[$key]; break; default: if (!isset($definition[$key])) { $definition[$key] = $data[$key]; } elseif ($definition[$key] !== $data[$key]) { throw new Exception("Mismatched OOUI theme definitions are not supported: trying to load {$key} of {$theme} theme"); } break; } } } // Fields from definition silently override keys from JSON files $this->definition += $definition; parent::loadFromDefinition(); }
public static function onBeforePageDisplay(OutputPage &$out, Skin &$skin) { // Enable only if the user has turned it on in Beta Preferences, or BetaFeatures is not installed. // Will only be loaded if PageImages & TextExtracts extensions are installed. $registry = ExtensionRegistry::getInstance(); if (!$registry->isLoaded('TextExtracts') || !class_exists('ApiQueryPageImages')) { $logger = LoggerFactory::getInstance('popups'); $logger->error('Popups requires the PageImages and TextExtracts extensions.'); return true; } if (self::getConfig()->get('PopupsBetaFeature') === true) { if (!class_exists('BetaFeatures')) { $logger = LoggerFactory::getInstance('popups'); $logger->error('PopupsMode cannot be used as a beta feature unless ' . 'the BetaFeatures extension is present.'); return true; } if (!BetaFeatures::isFeatureEnabled($skin->getUser(), 'popups')) { return true; } } $out->addModules(array('ext.popups', 'schema.Popups')); return true; }
/** * Read the global and extract title objects from the corresponding messages * @return array Array( 'msg' => Title, 'cats' => Title[] ) */ private function prepareTrackingCategoriesData() { $categories = array_merge(self::$coreTrackingCategories, ExtensionRegistry::getInstance()->getAttribute('TrackingCategories'), $this->getConfig()->get('TrackingCategories')); $trackingCategories = []; foreach ($categories as $catMsg) { /* * Check if the tracking category varies by namespace * Otherwise only pages in the current namespace will be displayed * If it does vary, show pages considering all namespaces */ $msgObj = $this->msg($catMsg)->inContentLanguage(); $allCats = []; $catMsgTitle = Title::makeTitleSafe(NS_MEDIAWIKI, $catMsg); if (!$catMsgTitle) { continue; } // Match things like {{NAMESPACE}} and {{NAMESPACENUMBER}}. // False positives are ok, this is just an efficiency shortcut if (strpos($msgObj->plain(), '{{') !== false) { $ns = MWNamespace::getValidNamespaces(); foreach ($ns as $namesp) { $tempTitle = Title::makeTitleSafe($namesp, $catMsg); if (!$tempTitle) { continue; } $catName = $msgObj->title($tempTitle)->text(); # Allow tracking categories to be disabled by setting them to "-" if ($catName !== '-') { $catTitle = Title::makeTitleSafe(NS_CATEGORY, $catName); if ($catTitle) { $allCats[] = $catTitle; } } } } else { $catName = $msgObj->text(); # Allow tracking categories to be disabled by setting them to "-" if ($catName !== '-') { $catTitle = Title::makeTitleSafe(NS_CATEGORY, $catName); if ($catTitle) { $allCats[] = $catTitle; } } } $trackingCategories[$catMsg] = ['cats' => $allCats, 'msg' => $catMsgTitle]; } return $trackingCategories; }
<?php if (!defined('MEDIAWIKI')) { die('Not an entry point.'); } $GLOBALS['wgExtensionCredits']['wikibase'][] = array('path' => __FILE__, 'name' => 'Wikibase View', 'version' => WIKIBASE_VIEW_VERSION, 'author' => array('[http://www.snater.com H. Snater]'), 'url' => 'https://git.wikimedia.org/summary/mediawiki%2Fextensions%2FWikibaseView', 'description' => 'Wikibase View', 'license-name' => 'GPL-2.0+'); include 'resources.php'; include 'resources.test.php'; $GLOBALS['wgHooks']['UnitTestsList'][] = function (array &$paths) { $paths[] = __DIR__ . '/tests/phpunit'; }; /** * Register ResourceLoader modules with dynamic dependencies. * * @param ResourceLoader $resourceLoader * * @return bool */ $GLOBALS['wgHooks']['ResourceLoaderRegisterModules'][] = function (ResourceLoader $resourceLoader) { preg_match('+' . preg_quote(DIRECTORY_SEPARATOR) . '(?:vendor|extensions)' . preg_quote(DIRECTORY_SEPARATOR) . '.*+', __DIR__, $remoteExtPath); $moduleTemplate = array('localBasePath' => __DIR__, 'remoteExtPath' => '..' . $remoteExtPath[0], 'position' => 'top'); $modules = array('jquery.util.getDirectionality' => $moduleTemplate + array('scripts' => array('resources/jquery/jquery.util.getDirectionality.js'), 'dependencies' => array()), 'wikibase.getLanguageNameByCode' => $moduleTemplate + array('scripts' => array('resources/wikibase/wikibase.getLanguageNameByCode.js'), 'dependencies' => array('wikibase'))); $isUlsLoaded = ExtensionRegistry::getInstance()->isLoaded('UniversalLanguageSelector'); if ($isUlsLoaded) { $modules['jquery.util.getDirectionality']['dependencies'][] = 'ext.uls.mediawiki'; $modules['wikibase.getLanguageNameByCode']['dependencies'][] = 'ext.uls.mediawiki'; } $resourceLoader->register($modules); return true; };
foreach ($mmfl['setupFiles'] as $fileName) { if (strval($fileName) === '') { continue; } if (empty($mmfl['quiet'])) { fwrite(STDERR, "Loading data from {$fileName}\n"); } // Using extension.json or skin.json if (substr($fileName, -strlen('.json')) === '.json') { $queue[$fileName] = 1; } else { require_once $fileName; } } if ($queue) { $registry = new ExtensionRegistry(); $data = $registry->readFromQueue($queue); foreach (array('wgExtensionMessagesFiles', 'wgMessagesDirs') as $var) { if (isset($data['globals'][$var])) { $GLOBALS[$var] = array_merge($data['globals'][$var], $GLOBALS[$var]); } } } fwrite(STDERR, "\n"); $s = "<" . "?php\n" . "## This file is generated by mergeMessageFileList.php. Do not edit it directly.\n\n" . "if ( defined( 'MW_NO_EXTENSION_MESSAGES' ) ) return;\n\n" . '$wgExtensionMessagesFiles = ' . var_export($wgExtensionMessagesFiles, true) . ";\n\n" . '$wgMessagesDirs = ' . var_export($wgMessagesDirs, true) . ";\n\n"; $dirs = array($IP, dirname(__DIR__), realpath($IP)); foreach ($dirs as $dir) { $s = preg_replace("/'" . preg_quote($dir, '/') . "([^']*)'/", '"$IP\\1"', $s); } if (isset($mmfl['output'])) { file_put_contents($mmfl['output'], $s);
/** * Load multiple skins at once * * @see wfLoadExtensions * @param string[] $skins Array of extension names to load */ function wfLoadSkins(array $skins) { global $wgStyleDirectory; $registry = ExtensionRegistry::getInstance(); foreach ($skins as $skin) { $registry->queue("{$wgStyleDirectory}/{$skin}/skin.json"); } }
/** * Returns information about the source of this module, if known * * Returned array is an array with the following keys: * - path: Install path * - name: Extension name, or "MediaWiki" for core * - namemsg: (optional) i18n message key for a display name * - license-name: (optional) Name of license * * @return array|null */ protected function getModuleSourceInfo() { global $IP; if ($this->mModuleSource !== false) { return $this->mModuleSource; } // First, try to find where the module comes from... $rClass = new ReflectionClass($this); $path = $rClass->getFileName(); if (!$path) { // No path known? $this->mModuleSource = null; return null; } $path = realpath($path) ?: $path; // Build map of extension directories to extension info if (self::$extensionInfo === null) { self::$extensionInfo = array(realpath(__DIR__) ?: __DIR__ => array('path' => $IP, 'name' => 'MediaWiki', 'license-name' => 'GPL-2.0+'), realpath("{$IP}/extensions") ?: "{$IP}/extensions" => null); $keep = array('path' => null, 'name' => null, 'namemsg' => null, 'license-name' => null); foreach ($this->getConfig()->get('ExtensionCredits') as $group) { foreach ($group as $ext) { if (!isset($ext['path']) || !isset($ext['name'])) { // This shouldn't happen, but does anyway. continue; } $extpath = $ext['path']; if (!is_dir($extpath)) { $extpath = dirname($extpath); } self::$extensionInfo[realpath($extpath) ?: $extpath] = array_intersect_key($ext, $keep); } } foreach (ExtensionRegistry::getInstance()->getAllThings() as $ext) { $extpath = $ext['path']; if (!is_dir($extpath)) { $extpath = dirname($extpath); } self::$extensionInfo[realpath($extpath) ?: $extpath] = array_intersect_key($ext, $keep); } } // Now traverse parent directories until we find a match or run out of // parents. do { if (array_key_exists($path, self::$extensionInfo)) { // Found it! $this->mModuleSource = self::$extensionInfo[$path]; return $this->mModuleSource; } $oldpath = $path; $path = dirname($path); } while ($path !== $oldpath); // No idea what extension this might be. $this->mModuleSource = null; return null; }
/** * Verify that the required extensions are installed * * @since 1.28 */ public function checkRequiredExtensions() { $registry = ExtensionRegistry::getInstance(); $missing = []; foreach ($this->requiredExtensions as $name) { if (!$registry->isLoaded($name)) { $missing[] = $name; } } if ($missing) { $joined = implode(', ', $missing); $msg = "The following extensions are required to be installed " . "for this script to run: {$joined}. Please enable them and then try again."; $this->error($msg, 1); } }
/** * Get the stylesheet of the MediaWiki skin. * * @return string */ public function getCSS() { global $wgStyleDirectory; $moduleNames = array('mediawiki.legacy.shared', 'mediawiki.skinning.interface'); $resourceLoader = new ResourceLoader(); if (file_exists("{$wgStyleDirectory}/Vector/skin.json")) { // Force loading Vector skin if available as a fallback skin // for whatever ResourceLoader wants to have as the default. $registry = new ExtensionRegistry(); $data = $registry->readFromQueue(array("{$wgStyleDirectory}/Vector/skin.json" => 1)); if (isset($data['globals']['wgResourceModules'])) { $resourceLoader->register($data['globals']['wgResourceModules']); } $moduleNames[] = 'skins.vector.styles'; } $moduleNames[] = 'mediawiki.legacy.config'; $rlContext = new ResourceLoaderContext($resourceLoader, new FauxRequest(array('debug' => 'true', 'lang' => $this->getLanguageCode(), 'only' => 'styles'))); $styles = array(); foreach ($moduleNames as $moduleName) { /** @var ResourceLoaderFileModule $module */ $module = $resourceLoader->getModule($moduleName); if (!$module) { // T98043: Don't fatal, but it won't look as pretty. continue; } // Based on: ResourceLoaderFileModule::getStyles (without the DB query) $styles = array_merge($styles, ResourceLoader::makeCombinedStyles($module->readStyleFiles($module->getStyleFiles($rlContext), $module->getFlip($rlContext)))); } return implode("\n", $styles); }
/** * Hook into Content::getParserOutput to provide syntax highlighting for * script content. * * @return bool * @since MW 1.21 */ public static function onContentGetParserOutput(Content $content, Title $title, $revId, ParserOptions $options, $generateHtml, ParserOutput &$output) { global $wgParser, $wgTextModelsToParse; if (!$generateHtml) { // Nothing special for us to do, let MediaWiki handle this. return true; } // Determine the language $extension = ExtensionRegistry::getInstance(); $models = $extension->getAttribute('SyntaxHighlightModels'); $model = $content->getModel(); if (!isset($models[$model])) { // We don't care about this model, carry on. return true; } $lexer = $models[$model]; // Hope that $wgSyntaxHighlightModels does not contain silly types. $text = ContentHandler::getContentText($content); if (!$text) { // Oops! Non-text content? Let MediaWiki handle this. return true; } // Parse using the standard parser to get links etc. into the database, HTML is replaced below. // We could do this using $content->fillParserOutput(), but alas it is 'protected'. if ($content instanceof TextContent && in_array($model, $wgTextModelsToParse)) { $output = $wgParser->parse($text, $title, $options, true, true, $revId); } $status = self::highlight($text, $lexer); if (!$status->isOK()) { return true; } $out = $status->getValue(); $output->addModuleStyles('ext.pygments'); $output->setText('<div dir="ltr">' . $out . '</div>'); // Inform MediaWiki that we have parsed this page and it shouldn't mess with it. return false; }
/** * Hook into Content::getParserOutput to provide syntax highlighting for * script content. * * @return bool * @since MW 1.21 */ public static function renderHook(Content $content, Title $title, $revId, ParserOptions $options, $generateHtml, ParserOutput &$output) { global $wgSyntaxHighlightModels, $wgUseSiteCss, $wgParser, $wgTextModelsToParse; $highlightModels = ExtensionRegistry::getInstance()->getAttribute('SyntaxHighlightModels'); // Determine the language $model = $content->getModel(); if (!isset($highlightModels[$model]) && !isset($wgSyntaxHighlightModels[$model])) { // We don't care about this model, carry on. return true; } if (!$generateHtml) { // Nothing special for us to do, let MediaWiki handle this. return true; } // Hope that $wgSyntaxHighlightModels does not contain silly types. $text = ContentHandler::getContentText($content); if ($text === null || $text === false) { // Oops! Non-text content? Let MediaWiki handle this. return true; } // Parse using the standard parser to get links etc. into the database, HTML is replaced below. // We could do this using $content->fillParserOutput(), but alas it is 'protected'. if ($content instanceof TextContent && in_array($model, $wgTextModelsToParse)) { $output = $wgParser->parse($text, $title, $options, true, true, $revId); } if (isset($highlightModels[$model])) { $lang = $highlightModels[$model]; } else { // TODO: Add deprecation warning after a while? $lang = $wgSyntaxHighlightModels[$model]; } // Attempt to format $geshi = self::prepare($text, $lang); if ($geshi instanceof GeSHi) { $out = $geshi->parse_code(); if (!$geshi->error()) { // Done $output->addModuleStyles("ext.geshi.language.{$lang}"); $output->setText("<div dir=\"ltr\">{$out}</div>"); if ($wgUseSiteCss) { $output->addModuleStyles('ext.geshi.local'); } // Inform MediaWiki that we have parsed this page and it shouldn't mess with it. return false; } } // Bottle out return true; }
// Check the MW_INSTALL_PATH environment variable, to see if it is set. If so, // this is the root folder of the MediaWiki installation. $MWPath = getenv("MW_INSTALL_PATH"); if ($MWPath === false) { // if it is not set, then assume the default location $MWPath = dirname(__FILE__) . "/../../.."; // if the guess was wrong, then die if (!file_exists($MWPath . MWEntryPoint)) { die("Unable to locate MediaWiki installation. " . "Try setting the MW_INSTALL_PATH environment variable to the mediawiki folder.\n"); } } elseif (!file_exists($MWPath . MWEntryPoint)) { // if it was set and the maintence directory still can't be found, then die die("MediaWiki not found at MW_INSTALL_PATH (" . $MWPath . ").\n"); } // If we get here, then MediaWiki was found, so load Maintenance.php require_once $MWPath . MWEntryPoint; if (!ExtensionRegistry::getInstance()->isLoaded('ContentReferencer')) { die("This script requries that the ContentReferencer extension is loaded. \n Please add `wfLoadExtension('ContentReferencer')` to your LocalSettings.php file."); } // load the database wfWaitForSlaves(false); $DB =& wfGetDB(DB_MASTER); // check if the ContentReferencer table exists $hasContentRefTable = $DB->tableExists(ContentReferencerTableName); if (!$hasContentRefTable) { echo "Creating table \"" . ContentReferencerTableName . "\".\n"; // now we need to actually create the table $DB->query("\n CREATE TABLE IF NOT EXISTS " . ContentReferencerTableName . "(\n reference_name varchar(255),\n reference_page_name varchar(255),\n \n PRIMARY KEY (reference_name)\n )\n "); } else { echo "Table \"" . ContentReferencerTableName . "\" already exists, not creating.\n"; }
/** * Loads LocalSettings.php, if needed, and initialises everything needed for * LoadExtensionSchemaUpdates hook. */ private function loadExtensions() { if (!defined('MEDIAWIKI_INSTALL')) { return; // already loaded } $vars = Installer::getExistingLocalSettings(); $registry = ExtensionRegistry::getInstance(); $queue = $registry->getQueue(); // Don't accidentally load extensions in the future $registry->clearQueue(); // This will automatically add "AutoloadClasses" to $wgAutoloadClasses $data = $registry->readFromQueue($queue); $hooks = array('wgHooks' => array('LoadExtensionSchemaUpdates' => array())); if (isset($data['globals']['wgHooks']['LoadExtensionSchemaUpdates'])) { $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']; } if ($vars && isset($vars['wgHooks']['LoadExtensionSchemaUpdates'])) { $hooks = array_merge_recursive($hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates']); } global $wgHooks, $wgAutoloadClasses; $wgHooks['LoadExtensionSchemaUpdates'] = $hooks; if ($vars && isset($vars['wgAutoloadClasses'])) { $wgAutoloadClasses += $vars['wgAutoloadClasses']; } }
* GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ if (!defined('MEDIAWIKI')) { die('Not an entry point.'); } // WARNING: OOjs-UI is NOT TESTED with older browsers and is likely to break // if loaded in browsers that don't support ES5 return call_user_func(function () { $themes = ExtensionRegistry::getInstance()->getAttribute('SkinOOUIThemes'); // We only use the theme names for file names, and they are lowercase $themes = array_map('strtolower', $themes); $themes['default'] = 'mediawiki'; $modules = array(); $modules['oojs-ui'] = array('scripts' => array('resources/lib/oojs-ui/oojs-ui.js', 'resources/src/oojs-ui-local.js'), 'skinScripts' => array_combine(array_keys($themes), array_map(function ($theme) { // TODO Allow extensions to specify this path somehow return "resources/lib/oojs-ui/oojs-ui-{$theme}.js"; }, array_values($themes))), 'dependencies' => array('es5-shim', 'oojs', 'oojs-ui.styles', 'oojs-ui.styles.icons', 'oojs-ui.styles.indicators', 'oojs-ui.styles.textures', 'mediawiki.language'), 'messages' => array('ooui-dialog-message-accept', 'ooui-dialog-message-reject', 'ooui-dialog-process-continue', 'ooui-dialog-process-dismiss', 'ooui-dialog-process-error', 'ooui-dialog-process-retry', 'ooui-outline-control-move-down', 'ooui-outline-control-move-up', 'ooui-outline-control-remove', 'ooui-selectfile-button-select', 'ooui-selectfile-dragdrop-placeholder', 'ooui-selectfile-not-supported', 'ooui-selectfile-placeholder', 'ooui-toolbar-more', 'ooui-toolgroup-collapse', 'ooui-toolgroup-expand'), 'targets' => array('desktop', 'mobile')); $modules['oojs-ui.styles'] = array('position' => 'top', 'styles' => 'resources/src/oojs-ui-local.css', 'skinStyles' => array_combine(array_keys($themes), array_map(function ($theme) { // TODO Allow extensions to specify this path somehow return "resources/lib/oojs-ui/oojs-ui-{$theme}-noimages.css"; }, array_values($themes))), 'targets' => array('desktop', 'mobile')); $imageSets = array('icons', 'indicators', 'textures', 'icons-accessibility', 'icons-alerts', 'icons-content', 'icons-editing-advanced', 'icons-editing-core', 'icons-editing-list', 'icons-editing-styling', 'icons-interactions', 'icons-layout', 'icons-location', 'icons-media', 'icons-moderation', 'icons-movement', 'icons-user', 'icons-wikimedia'); $rootPath = 'resources/lib/oojs-ui/themes'; foreach ($imageSets as $name) {
public static function onExtensionSetup() { // FIXME: This doesn't do anything as if mobilefrontend is not present // The reported error is "This requires Gather." if (!defined('MOBILEFRONTEND') && !\ExtensionRegistry::getInstance()->isLoaded('MobileFrontend')) { echo "Gather extension requires MobileFrontend.\n"; die(-1); } }
/** * Returns array of all defined namespaces with their canonical * (English) names. * * @param bool $rebuild Rebuild namespace list (default = false). Used for testing. * * @return array * @since 1.17 */ public static function getCanonicalNamespaces($rebuild = false) { static $namespaces = null; if ($namespaces === null || $rebuild) { global $wgExtraNamespaces, $wgCanonicalNamespaceNames; $namespaces = [NS_MAIN => ''] + $wgCanonicalNamespaceNames; // Add extension namespaces $namespaces += ExtensionRegistry::getInstance()->getAttribute('ExtensionNamespaces'); if (is_array($wgExtraNamespaces)) { $namespaces += $wgExtraNamespaces; } Hooks::run('CanonicalNamespaces', [&$namespaces]); } return $namespaces; }
/** * Adds extra variables to the global config */ public static function onResourceLoaderGetConfigVars(array &$vars) { $coreConfig = RequestContext::getMain()->getConfig(); $defaultUserOptions = $coreConfig->get('DefaultUserOptions'); $thumbLimits = $coreConfig->get('ThumbLimits'); $veConfig = ConfigFactory::getDefaultInstance()->makeConfig('visualeditor'); $vars['wgVisualEditorConfig'] = array('disableForAnons' => $veConfig->get('VisualEditorDisableForAnons'), 'preferenceModules' => $veConfig->get('VisualEditorPreferenceModules'), 'namespaces' => $veConfig->get('VisualEditorNamespaces'), 'pluginModules' => array_merge(ExtensionRegistry::getInstance()->getAttribute('VisualEditorPluginModules'), $veConfig->get('VisualEditorPluginModules')), 'defaultUserOptions' => array('defaultthumbsize' => $thumbLimits[$defaultUserOptions['thumbsize']]), 'blacklist' => $veConfig->get('VisualEditorBrowserBlacklist'), 'skins' => $veConfig->get('VisualEditorSupportedSkins'), 'tabPosition' => $veConfig->get('VisualEditorTabPosition'), 'tabMessages' => $veConfig->get('VisualEditorTabMessages'), 'showBetaWelcome' => $veConfig->get('VisualEditorShowBetaWelcome'), 'enableTocWidget' => $veConfig->get('VisualEditorEnableTocWidget'), 'svgMaxSize' => $coreConfig->get('SVGMaxSize'), 'namespacesWithSubpages' => $coreConfig->get('NamespacesWithSubpages'), 'restbaseUrl' => $coreConfig->get('VisualEditorRestbaseURL')); return true; }
* http://www.gnu.org/copyleft/gpl.html * * @file */ use MediaWiki\MediaWikiServices; /** * This file is not a valid entry point, perform no further processing unless * MEDIAWIKI is defined */ if (!defined('MEDIAWIKI')) { exit(1); } $fname = 'Setup.php'; $ps_setup = Profiler::instance()->scopedProfileIn($fname); // If any extensions are still queued, force load them ExtensionRegistry::getInstance()->loadFromQueue(); // Check to see if we are at the file scope if (!isset($wgVersion)) { echo "Error, Setup.php must be included from the file scope, after DefaultSettings.php\n"; die(1); } mb_internal_encoding('UTF-8'); // Set various default paths sensibly... $ps_default = Profiler::instance()->scopedProfileIn($fname . '-defaults'); if ($wgScript === false) { $wgScript = "{$wgScriptPath}/index.php"; } if ($wgLoadScript === false) { $wgLoadScript = "{$wgScriptPath}/load.php"; } if ($wgArticlePath === false) {
/** * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with * MediaWiki and this OutputPage instance. * * @since 1.25 */ public function enableOOUI() { $themes = ExtensionRegistry::getInstance()->getAttribute('SkinOOUIThemes'); // Make keys (skin names) lowercase for case-insensitive matching. $themes = array_change_key_case($themes, CASE_LOWER); $skinName = strtolower($this->getSkin()->getSkinName()); $theme = isset($themes[$skinName]) ? $themes[$skinName] : 'MediaWiki'; // For example, 'OOUI\MediaWikiTheme'. $themeClass = "OOUI\\{$theme}Theme"; OOUI\Theme::setSingleton(new $themeClass()); OOUI\Element::setDefaultDir($this->getLanguage()->getDir()); $this->addModuleStyles(array('oojs-ui.styles', 'oojs-ui.styles.icons', 'oojs-ui.styles.indicators', 'oojs-ui.styles.textures', 'mediawiki.widgets.styles')); }
/** * Helper function to setup the PHP implementation of OOUI to use in this request. * * @since 1.26 * @param String $skinName The Skin name to determine the correct OOUI theme * @param String $dir Language direction */ public static function setupOOUI($skinName = '', $dir = 'ltr') { $themes = ExtensionRegistry::getInstance()->getAttribute('SkinOOUIThemes'); // Make keys (skin names) lowercase for case-insensitive matching. $themes = array_change_key_case($themes, CASE_LOWER); $theme = isset($themes[$skinName]) ? $themes[$skinName] : 'MediaWiki'; // For example, 'OOUI\MediaWikiTheme'. $themeClass = "OOUI\\{$theme}Theme"; OOUI\Theme::setSingleton(new $themeClass()); OOUI\Element::setDefaultDir($dir); }
/** * Installs the auto-detected extensions. * * @return Status */ protected function includeExtensions() { global $IP; $exts = $this->getVar('_Extensions'); $IP = $this->getVar('IP'); /** * We need to include DefaultSettings before including extensions to avoid * warnings about unset variables. However, the only thing we really * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work * if the extension has hidden hook registration in $wgExtensionFunctions, * but we're not opening that can of worms * @see https://phabricator.wikimedia.org/T28857 */ global $wgAutoloadClasses; $wgAutoloadClasses = []; $queue = []; require "{$IP}/includes/DefaultSettings.php"; foreach ($exts as $e) { if (file_exists("{$IP}/extensions/{$e}/extension.json")) { $queue["{$IP}/extensions/{$e}/extension.json"] = 1; } else { require_once "{$IP}/extensions/{$e}/{$e}.php"; } } $registry = new ExtensionRegistry(); $data = $registry->readFromQueue($queue); $wgAutoloadClasses += $data['autoload']; $hooksWeWant = isset($wgHooks['LoadExtensionSchemaUpdates']) ? $wgHooks['LoadExtensionSchemaUpdates'] : []; if (isset($data['globals']['wgHooks']['LoadExtensionSchemaUpdates'])) { $hooksWeWant = array_merge_recursive($hooksWeWant, $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']); } // Unset everyone else's hooks. Lord knows what someone might be doing // in ParserFirstCallInit (see bug 27171) $GLOBALS['wgHooks'] = ['LoadExtensionSchemaUpdates' => $hooksWeWant]; return Status::newGood(); }
/** * BeforePageDisplay hook handler * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageDisplay * * @param OutputPage $out * @param Skin $sk * @return bool */ public static function onBeforePageDisplay(&$out, &$sk) { global $wgWPBSkinBlacklist, $wgWPBEnableDefaultBanner; $context = MobileContext::singleton(); $config = $context->getMFConfig(); $mfEnableXAnalyticsLogging = $config->get('MFEnableXAnalyticsLogging'); $mfAppPackageId = $config->get('MFAppPackageId'); $mfAppScheme = $config->get('MFAppScheme'); $mfNoIndexPages = $config->get('MFNoindexPages'); $mfMobileUrlTemplate = $context->getMobileUrlTemplate(); $tabletSize = $config->get('MFDeviceWidthTablet'); // show banners using WikidataPageBanner, if installed and all pre-conditions fulfilled if (ExtensionRegistry::getInstance()->isLoaded('WikidataPageBanner') && $context->isBetaGroupMember()) { // turn default banners on $wgWPBEnableDefaultBanner = true; // Turn on the banner experiment $needle = array_search('minerva', $wgWPBSkinBlacklist); if ($needle !== false) { unset($wgWPBSkinBlacklist[$needle]); } } $title = $sk->getTitle(); $request = $context->getRequest(); // Migrate prefixed disableImages cookie to unprefixed cookie. if (isset($_COOKIE[$config->get('CookiePrefix') . 'disableImages'])) { if ((bool) $request->getCookie('disableImages')) { $context->setDisableImagesCookie(true); } $request->response()->clearCookie('disableImages'); } # Add deep link to a mobile app specified by $wgMFAppScheme if ($mfAppPackageId !== false && $title->isContentPage() && $request->getRawQueryString() === '') { $fullUrl = $title->getFullURL(); $mobileUrl = $context->getMobileUrl($fullUrl); $path = preg_replace("/^([a-z]+:)?(\\/)*/", '', $mobileUrl, 1); $scheme = 'http'; if ($mfAppScheme !== false) { $scheme = $mfAppScheme; } else { $protocol = $request->getProtocol(); if ($protocol != '') { $scheme = $protocol; } } $hreflink = 'android-app://' . $mfAppPackageId . '/' . $scheme . '/' . $path; $out->addLink(array('rel' => 'alternate', 'href' => $hreflink)); } // an canonical/alternate link is only useful, if the mobile and desktop URL are different // and $wgMFNoindexPages needs to be true if ($mfMobileUrlTemplate && $mfNoIndexPages) { if (!$context->shouldDisplayMobileView()) { // add alternate link to desktop sites - bug T91183 $desktopUrl = $title->getFullUrl(); $link = array('rel' => 'alternate', 'media' => 'only screen and (max-width: ' . $tabletSize . 'px)', 'href' => $context->getMobileUrl($desktopUrl)); } else { // add canonical link to mobile pages, instead of noindex - bug T91183 $link = array('rel' => 'canonical', 'href' => $title->getFullUrl()); } $out->addLink($link); } // Set X-Analytics HTTP response header if necessary if ($context->shouldDisplayMobileView()) { $analyticsHeader = $mfEnableXAnalyticsLogging ? $context->getXAnalyticsHeader() : false; if ($analyticsHeader) { $resp = $out->getRequest()->response(); $resp->header($analyticsHeader); } // in mobile view: always add vary header $out->addVaryHeader('Cookie'); // Allow modifications in mobile only mode Hooks::run('BeforePageDisplayMobile', array(&$out, &$sk)); } return true; }
/** * Adds extra variables to the global config */ public static function onResourceLoaderGetConfigVars(array &$vars) { $coreConfig = RequestContext::getMain()->getConfig(); $defaultUserOptions = $coreConfig->get('DefaultUserOptions'); $thumbLimits = $coreConfig->get('ThumbLimits'); $veConfig = ConfigFactory::getDefaultInstance()->makeConfig('visualeditor'); $availableNamespaces = $veConfig->get('VisualEditorAvailableNamespaces'); $enabledNamespaces = array_keys(array_filter($availableNamespaces)); $vars['wgVisualEditorConfig'] = array('disableForAnons' => $veConfig->get('VisualEditorDisableForAnons'), 'preferenceModules' => $veConfig->get('VisualEditorPreferenceModules'), 'namespaces' => $enabledNamespaces, 'signatureNamespaces' => array_values(array_filter($enabledNamespaces, 'MWNamespace::wantSignatures')), 'pluginModules' => array_merge(ExtensionRegistry::getInstance()->getAttribute('VisualEditorPluginModules'), $veConfig->get('VisualEditorPluginModules')), 'defaultUserOptions' => array('defaultthumbsize' => $thumbLimits[$defaultUserOptions['thumbsize']]), 'blacklist' => $veConfig->get('VisualEditorBrowserBlacklist'), 'skins' => $veConfig->get('VisualEditorSupportedSkins'), 'tabPosition' => $veConfig->get('VisualEditorTabPosition'), 'tabMessages' => $veConfig->get('VisualEditorTabMessages'), 'singleEditTab' => $veConfig->get('VisualEditorUseSingleEditTab'), 'showBetaWelcome' => $veConfig->get('VisualEditorShowBetaWelcome'), 'enableTocWidget' => $veConfig->get('VisualEditorEnableTocWidget'), 'svgMaxSize' => $coreConfig->get('SVGMaxSize'), 'namespacesWithSubpages' => $coreConfig->get('NamespacesWithSubpages'), 'specialBooksources' => urldecode(SpecialPage::getTitleFor('Booksources')->getPrefixedURL()), 'restbaseUrl' => $coreConfig->get('VisualEditorRestbaseURL'), 'fullRestbaseUrl' => $coreConfig->get('VisualEditorFullRestbaseURL'), 'feedbackApiUrl' => $veConfig->get('VisualEditorFeedbackAPIURL'), 'feedbackTitle' => $veConfig->get('VisualEditorFeedbackTitle')); return true; }