/**
  * @param ConfigFactory $configFactory
  * @param ResolverInterface $localeResolver
  * @param CurrentCustomer $currentCustomer
  * @param PayfastHelper $paymentHelper
  * @param PaymentHelper $paymentHelper
  */
 public function __construct(\Psr\Log\LoggerInterface $logger, ConfigFactory $configFactory, ResolverInterface $localeResolver, CurrentCustomer $currentCustomer, PayfastHelper $payfastHelper, PaymentHelper $paymentHelper)
 {
     $this->_logger = $logger;
     $pre = __METHOD__ . ' : ';
     $this->_logger->debug($pre . 'bof');
     $this->localeResolver = $localeResolver;
     $this->config = $configFactory->create();
     $this->currentCustomer = $currentCustomer;
     $this->payfastHelper = $payfastHelper;
     $this->paymentHelper = $paymentHelper;
     foreach ($this->methodCodes as $code) {
         $this->methods[$code] = $this->paymentHelper->getMethodInstance($code);
     }
     $this->_logger->debug($pre . 'eof and this  methods has : ', $this->methods);
 }
 /**
  * @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;
 }
Exemplo n.º 3
0
 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);
 }
Exemplo n.º 5
0
 public function __construct()
 {
     $this->config = ConfigFactory::getConfig();
     $this->db = DblFactory::getConn();
     $this->toShow = $this->config->get('xmlPostsToShow') - 1;
     $this->numPosts = $this->db->numRows($this->db->query('select * from ' . $this->config->get('prefix') . '_news'));
 }
Exemplo n.º 6
0
 /**
  * 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();
 }
Exemplo n.º 7
0
 /**
  * Destroy the default instance
  * Should only be called inside unit tests
  * @throws MWException
  * @codeCoverageIgnore
  */
 public static function destroyDefaultInstance()
 {
     if (!defined('MW_PHPUNIT_TEST')) {
         throw new MWException(__METHOD__ . ' was called outside of unit tests');
     }
     self::$self = null;
 }
 /**
  * 运行mvc
  */
 static function mvcRun()
 {
     /* mvc入口 */
     $config = ConfigFactory::get('controller');
     foreach (array('module' => 'm', 'controller' => 'c', 'action' => 'a') as $k => $v) {
         ${$k} = trim($_GET[$v]);
         if (empty(${$k})) {
             ${$k} = $config['default' . ucfirst($k)];
         }
     }
     $classController = ucfirst($controller) . 'Controller';
     $path = "{$module}/controllers/{$classController}";
     if (preg_match("/^([a-z\\d\\_\\-]+\\/){2}[a-z\\d\\_\\-]+\$/i", $path) && file_exists(WEB_SYSTEM . "/modules/{$path}.php")) {
         require WEB_SYSTEM . "/modules/{$path}.php";
         $instance = new $classController();
         $instance->module = $module;
         $instance->controller = $controller;
         $instance->action = $action;
         $methodAction = 'action' . $action;
         if (method_exists($instance, $methodAction)) {
             call_user_func(array($instance, 'beforeAction'));
             call_user_func(array($instance, $methodAction));
             call_user_func(array($instance, 'afterAction'));
             return true;
         }
     }
     die('Invalid params (path:' . htmlspecialchars($path) . ')');
     return false;
 }
Exemplo n.º 9
0
 /**
  * @return StatCounter
  */
 public static function singleton()
 {
     static $instance = null;
     if (!$instance) {
         $instance = new self(ConfigFactory::getDefaultInstance()->makeConfig('main'));
     }
     return $instance;
 }
Exemplo n.º 10
0
 /**
  * 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;
 }
Exemplo n.º 11
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;
 }
Exemplo n.º 13
0
 /**
  * @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;
 }
Exemplo n.º 15
0
 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;
 }
 /**
  * 获取redis client实例
  * @param string $key
  * @return IRedis
  */
 static function open($key = 'default')
 {
     $instance =& self::$INSTANCES[$key];
     if (isset($instance) == false) {
         $config = ConfigFactory::get('redis', $key);
         if (empty($config)) {
             die("Undefined Redis Config \"{$key}\"");
         }
         $instance = new RedisClient();
         $instance->setServers($config['servers']);
     }
     return $instance;
 }
 /**
  * 获取单例的数据库实例
  * @param string $key
  * @return IDatabase
  */
 static function open($key = 'default')
 {
     $instance =& self::$INSTANCES[$key];
     if (isset($instance) == false) {
         $config = ConfigFactory::get('db', $key);
         if (empty($config)) {
             die("Undefined Database Config \"{$key}\"");
         }
         $className = 'Database' . ucfirst($config['type']);
         $instance = new $className();
         $instance->connect($config['host'], $config['port'], $config['database'], $config['user'], $config['password'], $config['charset']);
     }
     return $instance;
 }
Exemplo n.º 18
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);
     }
 }
Exemplo n.º 19
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);
 }
Exemplo n.º 22
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 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;
 }
 /**
  * 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;
 }
Exemplo n.º 25
0
 private static function reversible($string, $operation = 'DECODE', $key = '', $expiry = 0)
 {
     $ckey_length = 4;
     $key = md5($key ? $key : ConfigFactory::get('encode', 'defaultReversibleKey'));
     $keya = md5(substr($key, 0, 16));
     $keyb = md5(substr($key, 16, 16));
     $keyc = $ckey_length ? $operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length) : '';
     $cryptkey = $keya . md5($keya . $keyc);
     $key_length = strlen($cryptkey);
     $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
     $string_length = strlen($string);
     $result = '';
     $box = range(0, 255);
     $rndkey = array();
     for ($i = 0; $i <= 255; $i++) {
         $rndkey[$i] = ord($cryptkey[$i % $key_length]);
     }
     for ($j = $i = 0; $i < 256; $i++) {
         $j = ($j + $box[$i] + $rndkey[$i]) % 256;
         $tmp = $box[$i];
         $box[$i] = $box[$j];
         $box[$j] = $tmp;
     }
     for ($a = $j = $i = 0; $i < $string_length; $i++) {
         $a = ($a + 1) % 256;
         $j = ($j + $box[$a]) % 256;
         $tmp = $box[$a];
         $box[$a] = $box[$j];
         $box[$j] = $tmp;
         $result .= chr(ord($string[$i]) ^ $box[($box[$a] + $box[$j]) % 256]);
     }
     if ($operation == 'DECODE') {
         if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
             return substr($result, 26);
         } else {
             return;
         }
     } else {
         return $keyc . str_replace('=', '', base64_encode($result));
     }
 }
Exemplo n.º 26
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();
 }
Exemplo n.º 27
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'));
 }
Exemplo n.º 28
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());
 }
Exemplo n.º 29
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;
 }
Exemplo n.º 30
0
 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()));
 }