/**
  * Creates an ImportXMLReader drawing from the source provided
  * @param ImportSource $source
  * @param Config $config
  */
 function __construct(ImportSource $source, Config $config = null)
 {
     $this->reader = new XMLReader();
     if (!$config) {
         wfDeprecated(__METHOD__ . ' without a Config instance', '1.25');
         $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     $this->config = $config;
     if (!in_array('uploadsource', stream_get_wrappers())) {
         stream_wrapper_register('uploadsource', 'UploadSourceAdapter');
     }
     $id = UploadSourceAdapter::registerSource($source);
     if (defined('LIBXML_PARSEHUGE')) {
         $this->reader->open("uploadsource://{$id}", null, LIBXML_PARSEHUGE);
     } else {
         $this->reader->open("uploadsource://{$id}");
     }
     // Default callbacks
     $this->setPageCallback(array($this, 'beforeImportPage'));
     $this->setRevisionCallback(array($this, "importRevision"));
     $this->setUploadCallback(array($this, 'importUpload'));
     $this->setLogItemCallback(array($this, 'importLogItem'));
     $this->setPageOutCallback(array($this, 'finishImportPage'));
     $this->importTitleFactory = new NaiveImportTitleFactory();
 }
 public function execute()
 {
     $dbw = wfGetDB(DB_MASTER);
     $rl = new ResourceLoader(ConfigFactory::getDefaultInstance()->makeConfig('main'));
     $moduleNames = $rl->getModuleNames();
     $moduleList = implode(', ', array_map(array($dbw, 'addQuotes'), $moduleNames));
     $limit = max(1, intval($this->getOption('batchsize', 500)));
     $this->output("Cleaning up module_deps table...\n");
     $i = 1;
     $modDeps = $dbw->tableName('module_deps');
     do {
         // $dbw->delete() doesn't support LIMIT :(
         $where = $moduleList ? "md_module NOT IN ({$moduleList})" : '1=1';
         $dbw->query("DELETE FROM {$modDeps} WHERE {$where} LIMIT {$limit}", __METHOD__);
         $numRows = $dbw->affectedRows();
         $this->output("Batch {$i}: {$numRows} rows\n");
         $i++;
         wfWaitForSlaves();
     } while ($numRows > 0);
     $this->output("done\n");
     $this->output("Cleaning up msg_resource table...\n");
     $i = 1;
     $mrRes = $dbw->tableName('msg_resource');
     do {
         $where = $moduleList ? "mr_resource NOT IN ({$moduleList})" : '1=1';
         $dbw->query("DELETE FROM {$mrRes} WHERE {$where} LIMIT {$limit}", __METHOD__);
         $numRows = $dbw->affectedRows();
         $this->output("Batch {$i}: {$numRows} rows\n");
         $i++;
         wfWaitForSlaves();
     } while ($numRows > 0);
     $this->output("done\n");
 }
 public function testSetPasswordResetFlag()
 {
     $config = new \HashConfig(['InvalidPasswordReset' => true]);
     $manager = new AuthManager(new \FauxRequest(), \ConfigFactory::getDefaultInstance()->makeConfig('main'));
     $provider = $this->getMockForAbstractClass(AbstractPasswordPrimaryAuthenticationProvider::class);
     $provider->setConfig($config);
     $provider->setLogger(new \Psr\Log\NullLogger());
     $provider->setManager($manager);
     $providerPriv = \TestingAccessWrapper::newFromObject($provider);
     $manager->removeAuthenticationSessionData(null);
     $status = \Status::newGood();
     $providerPriv->setPasswordResetFlag('Foo', $status);
     $this->assertNull($manager->getAuthenticationSessionData('reset-pass'));
     $manager->removeAuthenticationSessionData(null);
     $status = \Status::newGood();
     $status->error('testing');
     $providerPriv->setPasswordResetFlag('Foo', $status);
     $ret = $manager->getAuthenticationSessionData('reset-pass');
     $this->assertNotNull($ret);
     $this->assertSame('resetpass-validity-soft', $ret->msg->getKey());
     $this->assertFalse($ret->hard);
     $config->set('InvalidPasswordReset', false);
     $manager->removeAuthenticationSessionData(null);
     $providerPriv->setPasswordResetFlag('Foo', $status);
     $ret = $manager->getAuthenticationSessionData('reset-pass');
     $this->assertNull($ret);
 }
 /**
  * @throws RuntimeException
  * @return boolean
  */
 public function run()
 {
     $this->unregisterUploadsource();
     $start = microtime(true);
     $config = null;
     $source = ImportStreamSource::newFromFile($this->assertThatFileIsReadableOrThrowException($this->file));
     if (!$source->isGood()) {
         throw new RuntimeException('Import returned with error(s) ' . serialize($source->errors));
     }
     // WikiImporter::__construct without a Config instance was deprecated in MediaWiki 1.25.
     if (class_exists('\\ConfigFactory')) {
         $config = \ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     $importer = new WikiImporter($source->value, $config);
     $importer->setDebug($this->verbose);
     $reporter = new ImportReporter($importer, false, '', false);
     $reporter->setContext($this->acquireRequestContext());
     $reporter->open();
     $this->exception = false;
     try {
         $importer->doImport();
     } catch (\Exception $e) {
         $this->exception = $e;
     }
     $this->result = $reporter->close();
     $this->importTime = microtime(true) - $start;
     return $this->result->isGood() && !$this->exception;
 }
Beispiel #5
0
 /**
  * @return StatCounter
  */
 public static function singleton()
 {
     static $instance = null;
     if (!$instance) {
         $instance = new self(ConfigFactory::getDefaultInstance()->makeConfig('main'));
     }
     return $instance;
 }
 /**
  * Get the Config object
  *
  * @return Config
  */
 public function getConfig()
 {
     if ($this->config === null) {
         // @todo In the future, we could move this to WebStart.php so
         // the Config object is ready for when initialization happens
         $this->config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     return $this->config;
 }
Beispiel #7
0
 /**
  * @param Config $config
  */
 function __construct(Config $config = null)
 {
     $this->data = [];
     $this->translator = new MediaWikiI18N();
     if ($config === null) {
         wfDebug(__METHOD__ . ' was called with no Config instance passed to it');
         $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     $this->config = $config;
 }
 /**
  * Get an instance of the provider
  * @return LegacyHookPreAuthenticationProvider
  */
 protected function getProvider()
 {
     $request = $this->getMock('FauxRequest', ['getIP']);
     $request->expects($this->any())->method('getIP')->will($this->returnValue('127.0.0.42'));
     $manager = new AuthManager($request, \ConfigFactory::getDefaultInstance()->makeConfig('main'));
     $provider = new LegacyHookPreAuthenticationProvider();
     $provider->setManager($manager);
     $provider->setLogger(new \Psr\Log\NullLogger());
     $provider->setConfig(new \HashConfig(['PasswordAttemptThrottle' => ['count' => 23, 'seconds' => 42]]));
     return $provider;
 }
 function __construct($title, Config $config = null)
 {
     if (is_null($title)) {
         throw new MWException(__METHOD__ . ' given a null title.');
     }
     $this->title = $title;
     if ($config === null) {
         wfDebug(__METHOD__ . ' did not have a Config object passed to it');
         $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     $this->config = $config;
 }
 /**
  * @covers ConfigFactory::getDefaultInstance
  */
 public function testGetDefaultInstance()
 {
     // Set $wgConfigRegistry, and check the default
     // instance read from it
     $this->setMwGlobals('wgConfigRegistry', array('conf1' => 'GlobalVarConfig::newInstance', 'conf2' => 'GlobalVarConfig::newInstance'));
     ConfigFactory::destroyDefaultInstance();
     $factory = ConfigFactory::getDefaultInstance();
     $this->assertInstanceOf('Config', $factory->makeConfig('conf1'));
     $this->assertInstanceOf('Config', $factory->makeConfig('conf2'));
     $this->setExpectedException('ConfigException');
     $factory->makeConfig('conf3');
 }
 public function getFieldInfo()
 {
     $config = \ConfigFactory::getDefaultInstance()->makeConfig('main');
     $ret = ['email' => ['type' => 'string', 'label' => wfMessage('authmanager-email-label'), 'help' => wfMessage('authmanager-email-help'), 'optional' => true], 'realname' => ['type' => 'string', 'label' => wfMessage('authmanager-realname-label'), 'help' => wfMessage('authmanager-realname-help'), 'optional' => true]];
     if (!$config->get('EnableEmail')) {
         unset($ret['email']);
     }
     if (in_array('realname', $config->get('HiddenPrefs'), true)) {
         unset($ret['realname']);
     }
     return $ret;
 }
Beispiel #12
0
 /**
  * @param string|null $text
  * @param Config|null $config
  */
 function __construct($text = null, Config $config = null)
 {
     $this->mCacheDuration = null;
     $this->mVary = null;
     $this->mConfig = $config ?: ConfigFactory::getDefaultInstance()->makeConfig('main');
     $this->mDisabled = false;
     $this->mText = '';
     $this->mResponseCode = 200;
     $this->mLastModified = false;
     $this->mContentType = 'application/x-wiki';
     if ($text) {
         $this->addText($text);
     }
 }
Beispiel #13
0
 /**
  * Returns a given template function if found, otherwise throws an exception.
  * @param string $templateName The name of the template (without file suffix)
  * @return callable
  * @throws RuntimeException
  */
 protected function getTemplate($templateName)
 {
     // If a renderer has already been defined for this template, reuse it
     if (isset($this->renderers[$templateName]) && is_callable($this->renderers[$templateName])) {
         return $this->renderers[$templateName];
     }
     $filename = $this->getTemplateFilename($templateName);
     if (!file_exists($filename)) {
         throw new RuntimeException("Could not locate template: {$filename}");
     }
     // Read the template file
     $fileContents = file_get_contents($filename);
     // Generate a quick hash for cache invalidation
     $fastHash = md5($fileContents);
     // Fetch a secret key for building a keyed hash of the PHP code
     $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     $secretKey = $config->get('SecretKey');
     if ($secretKey) {
         // See if the compiled PHP code is stored in cache.
         // CACHE_ACCEL throws an exception if no suitable object cache is present, so fall
         // back to CACHE_ANYTHING.
         $cache = ObjectCache::newAccelerator(array(), CACHE_ANYTHING);
         $key = wfMemcKey('template', $templateName, $fastHash);
         $code = $this->forceRecompile ? null : $cache->get($key);
         if (!$code) {
             $code = $this->compileForEval($fileContents, $filename);
             // Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
             $cache->set($key, hash_hmac('sha256', $code, $secretKey) . $code);
         } else {
             // Verify the integrity of the cached PHP code
             $keyedHash = substr($code, 0, 64);
             $code = substr($code, 64);
             if ($keyedHash !== hash_hmac('sha256', $code, $secretKey)) {
                 // Generate a notice if integrity check fails
                 trigger_error("Template failed integrity check: {$filename}");
             }
         }
         // If there is no secret key available, don't use cache
     } else {
         $code = $this->compileForEval($fileContents, $filename);
     }
     $renderer = eval($code);
     if (!is_callable($renderer)) {
         throw new RuntimeException("Requested template, {$templateName}, is not callable");
     }
     $this->renderers[$templateName] = $renderer;
     return $renderer;
 }
 private function doImport($importStreamSource)
 {
     $importer = new WikiImporter($importStreamSource->value, ConfigFactory::getDefaultInstance()->makeConfig('main'));
     $importer->setDebug(true);
     $reporter = new ImportReporter($importer, false, '', false);
     $reporter->setContext(new RequestContext());
     $reporter->open();
     $exception = false;
     try {
         $importer->doImport();
     } catch (Exception $e) {
         $exception = $e;
     }
     $result = $reporter->close();
     $this->assertFalse($exception);
     $this->assertTrue($result->isGood());
 }
 /**
  * Return an instance with a new, random password
  * @return TemporaryPasswordAuthenticationRequest
  */
 public static function newRandom()
 {
     $config = \ConfigFactory::getDefaultInstance()->makeConfig('main');
     // get the min password length
     $minLength = $config->get('MinimalPasswordLength');
     $policy = $config->get('PasswordPolicy');
     foreach ($policy['policies'] as $p) {
         if (isset($p['MinimalPasswordLength'])) {
             $minLength = max($minLength, $p['MinimalPasswordLength']);
         }
         if (isset($p['MinimalPasswordLengthToLogin'])) {
             $minLength = max($minLength, $p['MinimalPasswordLengthToLogin']);
         }
     }
     $password = \PasswordFactory::generateRandomPasswordString($minLength);
     return new self($password);
 }
 /**
  * Get an instance of the provider
  *
  * $provider->checkPasswordValidity is mocked to return $this->validity,
  * because we don't need to test that here.
  *
  * @param bool $loginOnly
  * @return LocalPasswordPrimaryAuthenticationProvider
  */
 protected function getProvider($loginOnly = false)
 {
     if (!$this->config) {
         $this->config = new \HashConfig();
     }
     $config = new \MultiConfig([$this->config, \ConfigFactory::getDefaultInstance()->makeConfig('main')]);
     if (!$this->manager) {
         $this->manager = new AuthManager(new \FauxRequest(), $config);
     }
     $this->validity = \Status::newGood();
     $provider = $this->getMock(LocalPasswordPrimaryAuthenticationProvider::class, ['checkPasswordValidity'], [['loginOnly' => $loginOnly]]);
     $provider->expects($this->any())->method('checkPasswordValidity')->will($this->returnCallback(function () {
         return $this->validity;
     }));
     $provider->setConfig($config);
     $provider->setLogger(new \Psr\Log\NullLogger());
     $provider->setManager($this->manager);
     return $provider;
 }
Beispiel #17
0
 /**
  * @param array $conditions An array of arrays describing throttling conditions.
  *     Defaults to $wgPasswordAttemptThrottle. See documentation of that variable for format.
  * @param array $params Parameters (all optional):
  *   - type: throttle type, used as a namespace for counters,
  *   - cache: a BagOStuff object where throttle counters are stored.
  *   - warningLimit: the log level will be raised to warning when rejecting an attempt after
  *     no less than this many failures.
  */
 public function __construct(array $conditions = null, array $params = [])
 {
     $invalidParams = array_diff_key($params, array_fill_keys(['type', 'cache', 'warningLimit'], true));
     if ($invalidParams) {
         throw new \InvalidArgumentException('unrecognized parameters: ' . implode(', ', array_keys($invalidParams)));
     }
     if ($conditions === null) {
         $config = \ConfigFactory::getDefaultInstance()->makeConfig('main');
         $conditions = $config->get('PasswordAttemptThrottle');
         $params += ['type' => 'password', 'cache' => \ObjectCache::getLocalClusterInstance(), 'warningLimit' => 50];
     } else {
         $params += ['type' => 'custom', 'cache' => \ObjectCache::getLocalClusterInstance(), 'warningLimit' => INF];
     }
     $this->type = $params['type'];
     $this->conditions = static::normalizeThrottleConditions($conditions);
     $this->cache = $params['cache'];
     $this->warningLimit = $params['warningLimit'];
     $this->setLogger(LoggerFactory::getInstance('throttler'));
 }
 /**
  * Get an instance of the provider
  *
  * $provider->checkPasswordValidity is mocked to return $this->validity,
  * because we don't need to test that here.
  *
  * @param array $params
  * @return TemporaryPasswordPrimaryAuthenticationProvider
  */
 protected function getProvider($params = [])
 {
     if (!$this->config) {
         $this->config = new \HashConfig(['EmailEnabled' => true]);
     }
     $config = new \MultiConfig([$this->config, \ConfigFactory::getDefaultInstance()->makeConfig('main')]);
     if (!$this->manager) {
         $this->manager = new AuthManager(new \FauxRequest(), $config);
     }
     $this->validity = \Status::newGood();
     $mockedMethods[] = 'checkPasswordValidity';
     $provider = $this->getMock(TemporaryPasswordPrimaryAuthenticationProvider::class, $mockedMethods, [$params]);
     $provider->expects($this->any())->method('checkPasswordValidity')->will($this->returnCallback(function () {
         return $this->validity;
     }));
     $provider->setConfig($config);
     $provider->setLogger(new \Psr\Log\NullLogger());
     $provider->setManager($this->manager);
     return $provider;
 }
Beispiel #19
0
 /**
  * Creates an ImportXMLReader drawing from the source provided
  * @param ImportSource $source
  * @param Config $config
  * @throws Exception
  */
 function __construct(ImportSource $source, Config $config = null)
 {
     if (!class_exists('XMLReader')) {
         throw new Exception('Import requires PHP to have been compiled with libxml support');
     }
     $this->reader = new XMLReader();
     if (!$config) {
         wfDeprecated(__METHOD__ . ' without a Config instance', '1.25');
         $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     $this->config = $config;
     if (!in_array('uploadsource', stream_get_wrappers())) {
         stream_wrapper_register('uploadsource', 'UploadSourceAdapter');
     }
     $id = UploadSourceAdapter::registerSource($source);
     // Enable the entity loader, as it is needed for loading external URLs via
     // XMLReader::open (T86036)
     $oldDisable = libxml_disable_entity_loader(false);
     if (defined('LIBXML_PARSEHUGE')) {
         $status = $this->reader->open("uploadsource://{$id}", null, LIBXML_PARSEHUGE);
     } else {
         $status = $this->reader->open("uploadsource://{$id}");
     }
     if (!$status) {
         $error = libxml_get_last_error();
         libxml_disable_entity_loader($oldDisable);
         throw new MWException('Encountered an internal error while initializing WikiImporter object: ' . $error->message);
     }
     libxml_disable_entity_loader($oldDisable);
     // Default callbacks
     $this->setPageCallback(array($this, 'beforeImportPage'));
     $this->setRevisionCallback(array($this, "importRevision"));
     $this->setUploadCallback(array($this, 'importUpload'));
     $this->setLogItemCallback(array($this, 'importLogItem'));
     $this->setPageOutCallback(array($this, 'finishImportPage'));
     $this->importTitleFactory = new NaiveImportTitleFactory();
 }
Beispiel #20
0
 function restoreText($revIds, $xml)
 {
     global $wgDBname;
     $tmpDir = wfTempDir();
     if (!count($revIds)) {
         return;
     }
     print "Restoring text from XML backup...\n";
     $revFileName = "{$tmpDir}/broken-revlist-{$wgDBname}";
     $filteredXmlFileName = "{$tmpDir}/filtered-{$wgDBname}.xml";
     // Write revision list
     if (!file_put_contents($revFileName, implode("\n", $revIds))) {
         echo "Error writing revision list, can't restore text\n";
         return;
     }
     // Run mwdumper
     echo "Filtering XML dump...\n";
     $exitStatus = 0;
     passthru('mwdumper ' . wfEscapeShellArg("--output=file:{$filteredXmlFileName}", "--filter=revlist:{$revFileName}", $xml), $exitStatus);
     if ($exitStatus) {
         echo "mwdumper died with exit status {$exitStatus}\n";
         return;
     }
     $file = fopen($filteredXmlFileName, 'r');
     if (!$file) {
         echo "Unable to open filtered XML file\n";
         return;
     }
     $dbr = wfGetDB(DB_SLAVE);
     $dbw = wfGetDB(DB_MASTER);
     $dbr->ping();
     $dbw->ping();
     $source = new ImportStreamSource($file);
     $importer = new WikiImporter($source, ConfigFactory::getDefaultInstance()->makeConfig('main'));
     $importer->setRevisionCallback([$this, 'importRevision']);
     $importer->doImport();
 }
Beispiel #21
0
 /**
  * @param array $options
  *  - config: Config to fetch configuration from. Defaults to the default 'main' config.
  *  - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
  *  - store: BagOStuff to store session data in.
  */
 public function __construct($options = array())
 {
     if (isset($options['config'])) {
         $this->config = $options['config'];
         if (!$this->config instanceof Config) {
             throw new \InvalidArgumentException('$options[\'config\'] must be an instance of Config');
         }
     } else {
         $this->config = \ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     if (isset($options['logger'])) {
         if (!$options['logger'] instanceof LoggerInterface) {
             throw new \InvalidArgumentException('$options[\'logger\'] must be an instance of LoggerInterface');
         }
         $this->setLogger($options['logger']);
     } else {
         $this->setLogger(\MediaWiki\Logger\LoggerFactory::getInstance('session'));
     }
     if (isset($options['store'])) {
         if (!$options['store'] instanceof BagOStuff) {
             throw new \InvalidArgumentException('$options[\'store\'] must be an instance of BagOStuff');
         }
         $this->store = $options['store'];
     } else {
         $this->store = \ObjectCache::getInstance($this->config->get('SessionCacheType'));
         $this->store->setLogger($this->logger);
     }
     register_shutdown_function(array($this, 'shutdown'));
 }
 public function __construct(Config $config = null, LoggerInterface $logger = null)
 {
     $this->setLogger($logger ?: new NullLogger());
     $this->config = $config ?: ConfigFactory::getDefaultInstance()->makeConfig('main');
     $this->setMessageBlobStore(new MessageBlobStore($this, $this->getLogger()));
 }
Beispiel #23
0
 /**
  * Return JS code that calls mw.loader.implement with given module properties.
  *
  * @param string $name Module name
  * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
  * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
  *   to CSS files keyed by media type
  * @param mixed $messages List of messages associated with this module. May either be an
  *   associative array mapping message key to value, or a JSON-encoded message blob containing
  *   the same data, wrapped in an XmlJsCode object.
  * @param array $templates Keys are name of templates and values are the source of
  *   the template.
  * @throws MWException
  * @return string
  */
 public static function makeLoaderImplementScript($name, $scripts, $styles, $messages, $templates)
 {
     if (is_string($scripts)) {
         // Site and user module are a legacy scripts that run in the global scope (no closure).
         // Transportation as string instructs mw.loader.implement to use globalEval.
         if ($name === 'site' || $name === 'user') {
             // Minify manually because the general makeModuleResponse() minification won't be
             // effective here due to the script being a string instead of a function. (T107377)
             if (!ResourceLoader::inDebugMode()) {
                 $scripts = self::applyFilter('minify-js', $scripts, ConfigFactory::getDefaultInstance()->makeConfig('main'));
             }
         } else {
             $scripts = new XmlJsCode("function ( \$, jQuery ) {\n{$scripts}\n}");
         }
     } elseif (!is_array($scripts)) {
         throw new MWException('Invalid scripts error. Array of URLs or string of code expected.');
     }
     // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
     // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
     // of "{}". Force them to objects.
     $module = array($name, $scripts, (object) $styles, (object) $messages, (object) $templates);
     self::trimArray($module);
     return Xml::encodeJsCall('mw.loader.implement', $module, ResourceLoader::inDebugMode());
 }
Beispiel #24
0
 /**
  * Get the initial image page text based on a comment and optional file status information
  * @param string $comment
  * @param string $license
  * @param string $copyStatus
  * @param string $source
  * @param Config $config Configuration object to load data from
  * @return string
  */
 public static function getInitialPageText($comment = '', $license = '', $copyStatus = '', $source = '', Config $config = null)
 {
     if ($config === null) {
         wfDebug(__METHOD__ . ' called without a Config instance passed to it');
         $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     $msg = array();
     $forceUIMsgAsContentMsg = (array) $config->get('ForceUIMsgAsContentMsg');
     /* These messages are transcluded into the actual text of the description page.
      * Thus, forcing them as content messages makes the upload to produce an int: template
      * instead of hardcoding it there in the uploader language.
      */
     foreach (array('license-header', 'filedesc', 'filestatus', 'filesource') as $msgName) {
         if (in_array($msgName, $forceUIMsgAsContentMsg)) {
             $msg[$msgName] = "{{int:{$msgName}}}";
         } else {
             $msg[$msgName] = wfMessage($msgName)->inContentLanguage()->text();
         }
     }
     if ($config->get('UseCopyrightUpload')) {
         $licensetxt = '';
         if ($license != '') {
             $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
         }
         $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" . '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" . "{$licensetxt}" . '== ' . $msg['filesource'] . " ==\n" . $source;
     } else {
         if ($license != '') {
             $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
             $pageText = $filedesc . '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
         } else {
             $pageText = $comment;
         }
     }
     return $pageText;
 }
Beispiel #25
0
 public function execute()
 {
     $userName = $this->getOption('user', false);
     $summary = $this->getOption('summary', 'Imported from text file');
     $useTimestamp = $this->hasOption('use-timestamp');
     $rc = $this->hasOption('rc');
     $bot = $this->hasOption('bot');
     $overwrite = $this->hasOption('overwrite');
     $prefix = $this->getOption('prefix', '');
     // Get all the arguments. A loop is required since Maintenance doesn't
     // support an arbitrary number of arguments.
     $files = [];
     $i = 0;
     while ($arg = $this->getArg($i++)) {
         if (file_exists($arg)) {
             $files[$arg] = file_get_contents($arg);
         } else {
             // use glob to support the Windows shell, which doesn't automatically
             // expand wildcards
             $found = false;
             foreach (glob($arg) as $filename) {
                 $found = true;
                 $files[$filename] = file_get_contents($filename);
             }
             if (!$found) {
                 $this->error("Fatal error: The file '{$arg}' does not exist!", 1);
             }
         }
     }
     $count = count($files);
     $this->output("Importing {$count} pages...\n");
     if ($userName === false) {
         $user = User::newSystemUser('Maintenance script', ['steal' => true]);
     } else {
         $user = User::newFromName($userName);
     }
     if (!$user) {
         $this->error("Invalid username\n", true);
     }
     if ($user->isAnon()) {
         $user->addToDatabase();
     }
     $exit = 0;
     $successCount = 0;
     $failCount = 0;
     $skipCount = 0;
     foreach ($files as $file => $text) {
         $pageName = $prefix . pathinfo($file, PATHINFO_FILENAME);
         $timestamp = $useTimestamp ? wfTimestamp(TS_UNIX, filemtime($file)) : wfTimestampNow();
         $title = Title::newFromText($pageName);
         // Have to check for # manually, since it gets interpreted as a fragment
         if (!$title || $title->hasFragment()) {
             $this->error("Invalid title {$pageName}. Skipping.\n");
             $skipCount++;
             continue;
         }
         $exists = $title->exists();
         $oldRevID = $title->getLatestRevID();
         $oldRev = $oldRevID ? Revision::newFromId($oldRevID) : null;
         $actualTitle = $title->getPrefixedText();
         if ($exists) {
             $touched = wfTimestamp(TS_UNIX, $title->getTouched());
             if (!$overwrite) {
                 $this->output("Title {$actualTitle} already exists. Skipping.\n");
                 $skipCount++;
                 continue;
             } elseif ($useTimestamp && intval($touched) >= intval($timestamp)) {
                 $this->output("File for title {$actualTitle} has not been modified since the " . "destination page was touched. Skipping.\n");
                 $skipCount++;
                 continue;
             }
         }
         $rev = new WikiRevision(ConfigFactory::getDefaultInstance()->makeConfig('main'));
         $rev->setText(rtrim($text));
         $rev->setTitle($title);
         $rev->setUserObj($user);
         $rev->setComment($summary);
         $rev->setTimestamp($timestamp);
         if ($exists && $overwrite && $rev->getContent()->equals($oldRev->getContent())) {
             $this->output("File for title {$actualTitle} contains no changes from the current " . "revision. Skipping.\n");
             $skipCount++;
             continue;
         }
         $status = $rev->importOldRevision();
         $newId = $title->getLatestRevID();
         if ($status) {
             $action = $exists ? 'updated' : 'created';
             $this->output("Successfully {$action} {$actualTitle}\n");
             $successCount++;
         } else {
             $action = $exists ? 'update' : 'create';
             $this->output("Failed to {$action} {$actualTitle}\n");
             $failCount++;
             $exit = 1;
         }
         // Create the RecentChanges entry if necessary
         if ($rc && $status) {
             if ($exists) {
                 if (is_object($oldRev)) {
                     $oldContent = $oldRev->getContent();
                     RecentChange::notifyEdit($timestamp, $title, $rev->getMinor(), $user, $summary, $oldRevID, $oldRev->getTimestamp(), $bot, '', $oldContent ? $oldContent->getSize() : 0, $rev->getContent()->getSize(), $newId, 1);
                 }
             } else {
                 RecentChange::notifyNew($timestamp, $title, $rev->getMinor(), $user, $summary, $bot, '', $rev->getContent()->getSize(), $newId, 1);
             }
         }
     }
     $this->output("Done! {$successCount} succeeded, {$skipCount} skipped.\n");
     if ($exit) {
         $this->error("Import failed with {$failCount} failed pages.\n", $exit);
     }
 }
Beispiel #26
0
 /**
  * Register core modules and runs registration hooks.
  * @param Config|null $config
  */
 public function __construct(Config $config = null, LoggerInterface $logger = null)
 {
     global $IP;
     if (!$logger) {
         $logger = new NullLogger();
     }
     $this->setLogger($logger);
     if (!$config) {
         $this->logger->debug(__METHOD__ . ' was called without providing a Config instance');
         $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     $this->config = $config;
     // Add 'local' source first
     $this->addSource('local', wfScript('load'));
     // Add other sources
     $this->addSource($config->get('ResourceLoaderSources'));
     // Register core modules
     $this->register(include "{$IP}/resources/Resources.php");
     $this->register(include "{$IP}/resources/ResourcesOOUI.php");
     // Register extension modules
     $this->register($config->get('ResourceModules'));
     Hooks::run('ResourceLoaderRegisterModules', array(&$this));
     if ($config->get('EnableJavaScriptTest') === true) {
         $this->registerTestModules();
     }
     $this->setMessageBlobStore(new MessageBlobStore());
 }
Beispiel #27
0
 /**
  * Check whether a user is allowed to send email
  *
  * @param User $user
  * @param string $editToken Edit token
  * @param Config $config optional for backwards compatibility
  * @return string|null Null on success or string on error
  */
 public static function getPermissionsError($user, $editToken, Config $config = null)
 {
     if ($config === null) {
         wfDebug(__METHOD__ . ' called without a Config instance passed to it');
         $config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     if (!$config->get('EnableEmail') || !$config->get('EnableUserEmail')) {
         return 'usermaildisabled';
     }
     if (!$user->isAllowed('sendemail')) {
         return 'badaccess';
     }
     if (!$user->isEmailConfirmed()) {
         return 'mailnologin';
     }
     if ($user->isBlockedFromEmailuser()) {
         wfDebug("User is blocked from sending e-mail.\n");
         return "blockedemailuser";
     }
     if ($user->pingLimiter('emailuser')) {
         wfDebug("Ping limiter triggered.\n");
         return 'actionthrottledtext';
     }
     $hookErr = false;
     Hooks::run('UserCanSendEmail', array(&$user, &$hookErr));
     Hooks::run('EmailUserPermissionsErrors', array($user, $editToken, &$hookErr));
     if ($hookErr) {
         return $hookErr;
     }
     return null;
 }
 /**
  * @return Config
  * @since 1.24
  */
 public function getConfig()
 {
     if ($this->config === null) {
         // Ugh, fall back to default
         $this->config = ConfigFactory::getDefaultInstance()->makeConfig('main');
     }
     return $this->config;
 }
 /**
  * Return a dummy ResourceLoaderContext object suitable for passing into
  * things that don't "really" need a context.
  * @return ResourceLoaderContext
  */
 public static function newDummyContext()
 {
     return new self(new ResourceLoader(ConfigFactory::getDefaultInstance()->makeConfig('main')), new FauxRequest(array()));
 }
Beispiel #30
0
    require_once "{$IP}/vendor/autoload.php";
}
if (defined('MW_CONFIG_CALLBACK')) {
    # Use a callback function to configure MediaWiki
    call_user_func(MW_CONFIG_CALLBACK);
} else {
    // Require the configuration (probably LocalSettings.php)
    require $maintenance->loadSettings();
}
if ($maintenance->getDbType() === Maintenance::DB_NONE) {
    if ($wgLocalisationCacheConf['storeClass'] === false && ($wgLocalisationCacheConf['store'] == 'db' || $wgLocalisationCacheConf['store'] == 'detect' && !$wgCacheDirectory)) {
        $wgLocalisationCacheConf['storeClass'] = 'LCStoreNull';
    }
}
$maintenance->finalSetup();
// Some last includes
require_once "{$IP}/includes/Setup.php";
// Initialize main config instance
$maintenance->setConfig(ConfigFactory::getDefaultInstance()->makeConfig('main'));
// Do the work
$maintenance->execute();
// Potentially debug globals
$maintenance->globals();
// Perform deferred updates.
DeferredUpdates::doUpdates();
// log profiling info
wfLogProfilingData();
// Commit and close up!
$factory = wfGetLBFactory();
$factory->commitMasterChanges('doMaintenance');
$factory->shutdown();