/** Fetch the math */ function fetchMath($sum) { if (MWInit::classExists('MathRenderer')) { $math = MathRenderer::getRenderer($sum, array(), MW_MATH_PNG); } else { throw new MWException('MathCaptcha requires the Math extension for MediaWiki versions 1.18 and above.'); } $html = $math->render(); return preg_replace('/alt=".*?"/', '', $html); }
/** * Get an external store object of the given type, with the given parameters * * @param string $proto Type of external storage, should be a value in $wgExternalStores * @param array $params Associative array of ExternalStoreMedium parameters * @return ExternalStoreMedium|bool The store class or false on error */ public static function getStoreObject($proto, array $params = array()) { global $wgExternalStores; if (!$wgExternalStores || !in_array($proto, $wgExternalStores)) { return false; // protocol not enabled } $class = 'ExternalStore' . ucfirst($proto); // Any custom modules should be added to $wgAutoLoadClasses for on-demand loading return MWInit::classExists($class) ? new $class($params) : false; }
/** * Get a job queue object of the specified type. * $params includes: * class : What job class to use (determines job type) * wiki : wiki ID of the wiki the jobs are for (defaults to current wiki) * type : The name of the job types this queue handles * order : Order that pop() selects jobs, either "timestamp" or "random". * If "timestamp" is used, the queue will effectively be FIFO. Note that * pop() will not be exactly FIFO, and even if it was, job completion would * not appear to be exactly FIFO since jobs can take different times to finish. * If "random" is used, pop() will pick jobs in random order. This might be * useful for improving concurrency depending on the queue storage medium. * * @param $params array * @return JobQueue * @throws MWException */ public static final function factory(array $params) { $class = $params['class']; if (!MWInit::classExists($class)) { throw new MWException("Invalid job queue class '{$class}'."); } $obj = new $class($params); if (!$obj instanceof self) { throw new MWException("Class '{$class}' is not a " . __CLASS__ . " class."); } return $obj; }
public function load() { if ($this->mLoaded) { return; } if (!MWInit::classExists('luasandbox')) { throw new MWException('luasandbox PHP extension is not installed'); } $this->mSandbox = new LuaSandbox(); $this->mSandbox->setMemoryLimit($this->mOptions['memoryLimit']); $this->mSandbox->setCPULimit($this->mOptions['maxCPU']); $this->mSandbox->registerLibrary('mw', array('import' => array($this, 'importModule'))); $this->mLoaded = true; }
/** * Get an external store object of the given type, with the given parameters * * @param $proto String: type of external storage, should be a value in $wgExternalStores * @param $params Array: associative array of parameters for the ExternalStore object. * @return ExternalStore subclass or false on error */ static function getStoreObject($proto, $params = array()) { global $wgExternalStores; if (!$wgExternalStores) { return false; } /* Protocol not enabled */ if (!in_array($proto, $wgExternalStores)) { return false; } $class = 'ExternalStore' . ucfirst($proto); /* Any custom modules should be added to $wgAutoLoadClasses for on-demand loading */ if (!MWInit::classExists($class)) { return false; } return new $class($params); }
/** * Create a language object for a given language code * @param $code String * @return Language */ protected static function newFromCode($code) { global $IP; static $recursionLevel = 0; // Protect against path traversal below if (!Language::isValidCode($code) || strcspn($code, ":/\\") !== strlen($code)) { throw new MWException("Invalid language code \"{$code}\""); } if (!Language::isValidBuiltInCode($code)) { // It's not possible to customise this code with class files, so // just return a Language object. This is to support uselang= hacks. $lang = new Language(); $lang->setCode($code); return $lang; } if ($code == 'en') { $class = 'Language'; } else { $class = 'Language' . str_replace('-', '_', ucfirst($code)); if (!defined('MW_COMPILED')) { // Preload base classes to work around APC/PHP5 bug if (file_exists("{$IP}/languages/classes/{$class}.deps.php")) { include_once "{$IP}/languages/classes/{$class}.deps.php"; } if (file_exists("{$IP}/languages/classes/{$class}.php")) { include_once "{$IP}/languages/classes/{$class}.php"; } } } if ($recursionLevel > 5) { throw new MWException("Language fallback loop detected when creating class {$class}\n"); } if (!MWInit::classExists($class)) { $fallback = Language::getFallbackFor($code); ++$recursionLevel; $lang = Language::newFromCode($fallback); --$recursionLevel; $lang->setCode($code); } else { $lang = new $class(); } return $lang; }
/** * Create a language object for a given language code * @param $code String * @throws MWException * @return Language */ protected static function newFromCode($code) { // Protect against path traversal below if (!Language::isValidCode($code) || strcspn($code, ":/\\") !== strlen($code)) { throw new MWException("Invalid language code \"{$code}\""); } if (!Language::isValidBuiltInCode($code)) { // It's not possible to customise this code with class files, so // just return a Language object. This is to support uselang= hacks. $lang = new Language(); $lang->setCode($code); return $lang; } // Check if there is a language class for the code $class = self::classFromCode($code); self::preloadLanguageClass($class); if (MWInit::classExists($class)) { $lang = new $class(); return $lang; } // Keep trying the fallback list until we find an existing class $fallbacks = Language::getFallbacksFor($code); foreach ($fallbacks as $fallbackCode) { if (!Language::isValidBuiltInCode($fallbackCode)) { throw new MWException("Invalid fallback '{$fallbackCode}' in fallback sequence for '{$code}'"); } $class = self::classFromCode($fallbackCode); self::preloadLanguageClass($class); if (MWInit::classExists($class)) { $lang = Language::newFromCode($fallbackCode); $lang->setCode($code); return $lang; } } throw new MWException("Invalid fallback sequence for language '{$code}'"); }
/** * Factory method for loading a skin of a given type * @param string $key 'monobook', 'standard', etc. * @return Skin */ static function &newFromKey($key) { global $wgStyleDirectory; $key = Skin::normalizeKey($key); $skinNames = Skin::getSkinNames(); $skinName = $skinNames[$key]; $className = "Skin{$skinName}"; # Grab the skin class and initialise it. if (!MWInit::classExists($className)) { if (!defined('MW_COMPILED')) { require_once "{$wgStyleDirectory}/{$skinName}.php"; } # Check if we got if not fallback to default skin if (!MWInit::classExists($className)) { # DO NOT die if the class isn't found. This breaks maintenance # scripts and can cause a user account to be unrecoverable # except by SQL manipulation if a previously valid skin name # is no longer valid. wfDebug("Skin class does not exist: {$className}\n"); $className = 'SkinVector'; if (!defined('MW_COMPILED')) { require_once "{$wgStyleDirectory}/Vector.php"; } } } $skin = new $className($key); return $skin; }
/** * @see FileBackendStore::__construct() * Additional $config params include: * - swiftAuthUrl : Swift authentication server URL * - swiftUser : Swift user used by MediaWiki (account:username) * - swiftKey : Swift authentication key for the above user * - swiftAuthTTL : Swift authentication TTL (seconds) * - swiftAnonUser : Swift user used for end-user requests (account:username). * If set, then views of public containers are assumed to go * through this user. If not set, then public containers are * accessible to unauthenticated requests via ".r:*" in the ACL. * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up * - swiftCDNExpiry : How long (in seconds) to store content in the CDN. * If files may likely change, this should probably not exceed * a few days. For example, deletions may take this long to apply. * If object purging is enabled, however, this is not an issue. * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN. * - shardViaHashLevels : Map of container names to sharding config with: * - base : base of hash characters, 16 or 36 * - levels : the number of hash levels (and digits) * - repeat : hash subdirectories are prefixed with all the * parent hash directory names (e.g. "a/ab/abc") * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect. * If those are not available, then the main cache will be used. * This is probably insecure in shared hosting environments. */ public function __construct(array $config) { parent::__construct($config); if (!MWInit::classExists('CF_Constants')) { throw new MWException('SwiftCloudFiles extension not installed.'); } // Required settings $this->auth = new CF_Authentication($config['swiftUser'], $config['swiftKey'], null, $config['swiftAuthUrl']); // Optional settings $this->authTTL = isset($config['swiftAuthTTL']) ? $config['swiftAuthTTL'] : 5 * 60; // some sane number $this->swiftAnonUser = isset($config['swiftAnonUser']) ? $config['swiftAnonUser'] : ''; $this->shardViaHashLevels = isset($config['shardViaHashLevels']) ? $config['shardViaHashLevels'] : ''; $this->swiftUseCDN = isset($config['swiftUseCDN']) ? $config['swiftUseCDN'] : false; $this->swiftCDNExpiry = isset($config['swiftCDNExpiry']) ? $config['swiftCDNExpiry'] : 12 * 3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org) $this->swiftCDNPurgable = isset($config['swiftCDNPurgable']) ? $config['swiftCDNPurgable'] : true; // Cache container information to mask latency $this->memCache = wfGetMainCache(); // Process cache for container info $this->connContainerCache = new ProcessCacheLRU(300); // Cache auth token information to avoid RTTs if (!empty($config['cacheAuthInfo'])) { if (php_sapi_name() === 'cli') { $this->srvCache = wfGetMainCache(); // preferrably memcached } else { try { // look for APC, XCache, WinCache, ect... $this->srvCache = ObjectCache::newAccelerator(array()); } catch (Exception $e) { } } } $this->srvCache = $this->srvCache ? $this->srvCache : new EmptyBagOStuff(); }
/** * Run a child maintenance script. Pass all of the current arguments * to it. * @param $maintClass String: a name of a child maintenance class * @param $classFile String: full path of where the child is * @return Maintenance child */ public function runChild($maintClass, $classFile = null) { // Make sure the class is loaded first if (!MWInit::classExists($maintClass)) { if ($classFile) { require_once $classFile; } if (!MWInit::classExists($maintClass)) { $this->error("Cannot spawn child: {$maintClass}"); } } /** * @var $child Maintenance */ $child = new $maintClass(); $child->loadParamsAndArgs($this->mSelf, $this->mOptions, $this->mArgs); if (!is_null($this->mDb)) { $child->setDB($this->mDb); } return $child; }
/** * Use the HTML tidy extension to use the tidy library in-process, * saving the overhead of spawning a new process. * * @param $text String: HTML to check * @param $stderr Boolean: Whether to read result from error status instead of output * @param &$retval Exit code (-1 on internal error) * @return mixed String or null */ private static function execInternalTidy($text, $stderr = false, &$retval = null) { global $wgTidyConf, $wgDebugTidy; wfProfileIn(__METHOD__); if (!MWInit::classExists('tidy')) { wfWarn("Unable to load internal tidy class."); $retval = -1; wfProfileOut(__METHOD__); return null; } $tidy = new tidy(); $tidy->parseString($text, $wgTidyConf, 'utf8'); if ($stderr) { $retval = $tidy->getStatus(); wfProfileOut(__METHOD__); return $tidy->errorBuffer; } else { $tidy->cleanRepair(); $retval = $tidy->getStatus(); if ($retval == 2) { // 2 is magic number for fatal error // http://www.php.net/manual/en/function.tidy-get-status.php $cleansource = null; } else { $cleansource = tidy_get_output($tidy); if ($wgDebugTidy && $retval > 0) { $cleansource .= "<!--\nTidy reports:\n" . str_replace('-->', '-->', $tidy->errorBuffer) . "\n-->"; } } wfProfileOut(__METHOD__); return $cleansource; } }
/** * @param $dir string file system directory */ public function __construct($dir) { $dir = realpath($dir); // normalize $this->suffixStart = strlen($dir) + 1; // size of "path/to/dir/" try { # Get an iterator that will return leaf nodes (non-directories) if (MWInit::classExists('FilesystemIterator')) { // PHP >= 5.3 # RecursiveDirectoryIterator extends FilesystemIterator. # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x. $flags = FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS; $this->iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, $flags)); } else { // PHP < 5.3 # RecursiveDirectoryIterator extends DirectoryIterator $this->iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); } } catch (UnexpectedValueException $e) { $this->iter = null; // bad permissions? deleted? } }
$wgLogNames['newusers'] = 'newuserlogpage'; $wgLogHeaders['newusers'] = 'newuserlogpagetext'; # newusers, create, create2, autocreate $wgLogActionsHandlers['newusers/*'] = 'NewUsersLogFormatter'; } if ($wgCookieSecure === 'detect') { $wgCookieSecure = substr($wgServer, 0, 6) === 'https:'; } // Disable MWDebug for command line mode, this prevents MWDebug from eating up // all the memory from logging SQL queries on maintenance scripts global $wgCommandLineMode; if ($wgDebugToolbar && !$wgCommandLineMode) { MWDebug::init(); } if (!defined('MW_COMPILED')) { if (!MWInit::classExists('AutoLoader')) { require_once "{$IP}/includes/AutoLoader.php"; } wfProfileIn($fname . '-exception'); MWExceptionHandler::installHandler(); wfProfileOut($fname . '-exception'); wfProfileIn($fname . '-includes'); require_once "{$IP}/includes/normal/UtfNormalUtil.php"; require_once "{$IP}/includes/GlobalFunctions.php"; require_once "{$IP}/includes/ProxyTools.php"; require_once "{$IP}/includes/ImageFunctions.php"; require_once "{$IP}/includes/normal/UtfNormalDefines.php"; wfProfileOut($fname . '-includes'); } # Now that GlobalFunctions is loaded, set the default for $wgCanonicalServer if ($wgCanonicalServer === false) {
$wgLogNames['gblrights'] = 'centralauth-rightslog-name'; $wgLogHeaders['gblrights'] = 'centralauth-rightslog-header'; $wgLogActions['gblrights/usergroups'] = 'centralauth-rightslog-entry-usergroups'; $wgLogActions['gblrights/groupperms'] = 'centralauth-rightslog-entry-groupperms'; $wgLogActions['gblrights/groupprms2'] = 'centralauth-rightslog-entry-groupperms2'; $wgLogActions['gblrights/groupprms3'] = 'centralauth-rightslog-entry-groupperms3'; foreach (array('newset', 'setrename', 'setnewtype', 'setchange', 'deleteset') as $type) { $wgLogActionsHandlers["gblrights/{$type}"] = 'efHandleWikiSetLogEntry'; } $commonModuleInfo = array('localBasePath' => dirname(__FILE__) . '/modules', 'remoteExtPath' => 'CentralAuth/modules'); $wgResourceModules['ext.centralauth'] = array('scripts' => 'ext.centralauth.js', 'styles' => 'ext.centralauth.css', 'messages' => array('centralauth-merge-method-primary', 'centralauth-merge-method-primary-desc', 'centralauth-merge-method-new', 'centralauth-merge-method-new-desc', 'centralauth-merge-method-empty', 'centralauth-merge-method-empty-desc', 'centralauth-merge-method-password', 'centralauth-merge-method-password-desc', 'centralauth-merge-method-mail', 'centralauth-merge-method-mail-desc', 'centralauth-merge-method-admin', 'centralauth-merge-method-admin-desc', 'centralauth-merge-method-login', 'centralauth-merge-method-login-desc')) + $commonModuleInfo; $wgResourceModules['ext.centralauth.noflash'] = array('styles' => 'ext.centralauth.noflash.css') + $commonModuleInfo; // If AntiSpoof is installed, we can do some AntiSpoof stuff for CA // Though, doing it this way, AntiSpoof has to be loaded/included first // I guess this is bug 30234 if (MWInit::classExists('AntiSpoof')) { $wgExtensionCredits['antispam'][] = array('path' => __FILE__, 'name' => 'AntiSpoof for CentralAuth', 'url' => 'https://www.mediawiki.org/wiki/Extension:AntiSpoof', 'author' => 'Sam Reed', 'descriptionmsg' => 'centralauth-antispoof-desc'); $wgAutoloadClasses['CentralAuthSpoofUser'] = "******"; $wgAutoloadClasses['CentralAuthAntiSpoofHooks'] = "{$caBase}/AntiSpoof/CentralAuthAntiSpoofHooks.php"; $wgHooks['AbortNewAccount'][] = 'CentralAuthAntiSpoofHooks::asAbortNewAccountHook'; $wgHooks['AddNewAccount'][] = 'CentralAuthAntiSpoofHooks::asAddNewAccountHook'; $wgHooks['RenameUserComplete'][] = 'CentralAuthAntiSpoofHooks::asAddRenameUserHook'; } /** * @param $type * @param $action * @param $title * @param $skin Skin * @param $params * @param $filterWikilinks bool * @return String