/**
  * Prepare data output
  *
  * @since 1.8
  *
  * @param array $data label => value
  */
 protected function getFormatOutput(array $data)
 {
     static $statNr = 0;
     $chartID = 'jqplot-' . $this->params['charttype'] . '-' . ++$statNr;
     $this->isHTML = true;
     // Prepare data objects
     if (in_array($this->params['charttype'], array('bar', 'line'))) {
         // Parse bar relevant data
         $dataObject = $this->prepareBarData($data);
     } elseif (in_array($this->params['charttype'], array('pie', 'donut'))) {
         //Parse pie/donut relevant data
         $dataObject = $this->preparePieData($data);
     } else {
         // Return with an error
         return Html::rawElement('span', array('class' => "error"), wfMessage('srf-error-missing-layout')->inContentLanguage()->text());
     }
     // Encode data objects
     $requireHeadItem = array($chartID => FormatJson::encode($dataObject));
     SMWOutputs::requireHeadItem($chartID, Skin::makeVariablesScript($requireHeadItem));
     // Processing placeholder
     $processing = SRFUtils::htmlProcessingElement($this->isHTML);
     // Ensure right conversion
     $width = strstr($this->params['width'], "%") ? $this->params['width'] : $this->params['width'] . 'px';
     // Chart/graph placeholder
     $chart = Html::rawElement('div', array('id' => $chartID, 'class' => 'container', 'style' => "display:none; width: {$width}; height: {$this->params['height']}px;"), null);
     // Beautify class selector
     $class = $this->params['charttype'] ? '-' . $this->params['charttype'] : '';
     $class = $this->params['class'] ? $class . ' ' . $this->params['class'] : $class . ' jqplot-common';
     // Chart/graph wrappper
     return Html::rawElement('div', array('class' => 'srf-jqplot' . $class), $processing . $chart);
 }
Example #2
0
 public function execute()
 {
     $variantLangs = array();
     $variants = array();
     foreach (LanguageConverter::$languagesWithVariants as $langCode) {
         $lang = Language::factory($langCode);
         if (count($lang->getVariants()) > 1) {
             $variants += array_flip($lang->getVariants());
             $variantLangs[$langCode] = $lang->getVariants();
         }
     }
     $variants = array_keys($variants);
     sort($variants);
     $result = $this->hasOption('flat') ? $variants : $variantLangs;
     // Not using $this->output() because muting makes no sense here
     if ($this->hasOption('json')) {
         echo FormatJson::encode($result, true) . "\n";
     } else {
         foreach ($result as $key => $value) {
             if (is_array($value)) {
                 echo "{$key}\n";
                 foreach ($value as $variant) {
                     echo "   {$variant}\n";
                 }
             } else {
                 echo "{$value}\n";
             }
         }
     }
 }
Example #3
0
 /**
  * Prepare data output
  *
  * @since 1.8
  *
  * @param array $data label => value
  */
 protected function getFormatOutput(array $data)
 {
     //Init
     $dataObject = array();
     static $statNr = 0;
     $chartID = 'sparkline-' . $this->params['charttype'] . '-' . ++$statNr;
     $this->isHTML = true;
     // Prepare data array
     foreach ($data as $key => $value) {
         if ($value >= $this->params['min']) {
             $dataObject['label'][] = $key;
             $dataObject['value'][] = $value;
         }
     }
     $dataObject['charttype'] = $this->params['charttype'];
     // Encode data objects
     $requireHeadItem = array($chartID => FormatJson::encode($dataObject));
     SMWOutputs::requireHeadItem($chartID, Skin::makeVariablesScript($requireHeadItem));
     // RL module
     SMWOutputs::requireResource('ext.srf.sparkline');
     // Processing placeholder
     $processing = SRFUtils::htmlProcessingElement(false);
     // Chart/graph placeholder
     $chart = Html::rawElement('div', array('id' => $chartID, 'class' => 'container', 'style' => "display:none;"), null);
     // Beautify class selector
     $class = $this->params['class'] ? ' ' . $this->params['class'] : '';
     // Chart/graph wrappper
     return Html::rawElement('span', array('class' => 'srf-sparkline' . $class), $processing . $chart);
 }
Example #4
0
 /**
  * @return string
  */
 public function execute()
 {
     $r = $this->parent->request;
     if ($r->wasPosted()) {
         if ($this->submit()) {
             return 'continue';
         }
     }
     $this->startForm();
     // Encourage people to not name their site 'MediaWiki' by blanking the
     // field. I think that was the intent with the original $GLOBALS['wgSitename']
     // but these two always were the same so had the effect of making the
     // installer forget $wgSitename when navigating back to this page.
     if ($this->getVar('wgSitename') == 'MediaWiki') {
         $this->setVar('wgSitename', '');
     }
     // Set wgMetaNamespace to something valid before we show the form.
     // $wgMetaNamespace defaults to $wgSiteName which is 'MediaWiki'
     $metaNS = $this->getVar('wgMetaNamespace');
     $this->setVar('wgMetaNamespace', wfMessage('config-ns-other-default')->inContentLanguage()->text());
     $pingbackInfo = (new Pingback())->getSystemInfo();
     // Database isn't available in config yet, so take it
     // from the installer
     $pingbackInfo['database'] = $this->getVar('wgDBtype');
     $this->addHTML($this->parent->getTextBox(['var' => 'wgSitename', 'label' => 'config-site-name', 'help' => $this->parent->getHelpBox('config-site-name-help')]) . $this->parent->getRadioSet(['var' => '_NamespaceType', 'label' => 'config-project-namespace', 'itemLabelPrefix' => 'config-ns-', 'values' => ['site-name', 'generic', 'other'], 'commonAttribs' => ['class' => 'enableForOther', 'rel' => 'config_wgMetaNamespace'], 'help' => $this->parent->getHelpBox('config-project-namespace-help')]) . $this->parent->getTextBox(['var' => 'wgMetaNamespace', 'label' => '', 'attribs' => ['readonly' => 'readonly', 'class' => 'enabledByOther']]) . $this->getFieldsetStart('config-admin-box') . $this->parent->getTextBox(['var' => '_AdminName', 'label' => 'config-admin-name', 'help' => $this->parent->getHelpBox('config-admin-help')]) . $this->parent->getPasswordBox(['var' => '_AdminPassword', 'label' => 'config-admin-password']) . $this->parent->getPasswordBox(['var' => '_AdminPasswordConfirm', 'label' => 'config-admin-password-confirm']) . $this->parent->getTextBox(['var' => '_AdminEmail', 'attribs' => ['dir' => 'ltr'], 'label' => 'config-admin-email', 'help' => $this->parent->getHelpBox('config-admin-email-help')]) . $this->parent->getCheckBox(['var' => '_Subscribe', 'label' => 'config-subscribe', 'help' => $this->parent->getHelpBox('config-subscribe-help')]) . $this->parent->getCheckBox(['var' => 'wgPingback', 'label' => 'config-pingback', 'help' => $this->parent->getHelpBox('config-pingback-help', FormatJson::encode($pingbackInfo, true)), 'value' => true]) . $this->getFieldsetEnd() . $this->parent->getInfoBox(wfMessage('config-almost-done')->text()) . $this->parent->getRadioSet(['var' => '_SkipOptional', 'itemLabelPrefix' => 'config-optional-', 'values' => ['continue', 'skip']]));
     // Restore the default value
     $this->setVar('wgMetaNamespace', $metaNS);
     $this->endForm();
     return 'output';
 }
Example #5
0
 public function execute()
 {
     global $wgCommandLineMode;
     if ($this->hasOption('procs')) {
         $procs = intval($this->getOption('procs'));
         if ($procs < 1 || $procs > 1000) {
             $this->error("Invalid argument to --procs", true);
         } elseif ($procs != 1) {
             $fc = new ForkController($procs);
             if ($fc->start() != 'child') {
                 exit(0);
             }
         }
     }
     $outputJSON = $this->getOption('result') === 'json';
     // Enable DBO_TRX for atomicity; JobRunner manages transactions
     // and works well in web server mode already (@TODO: this is a hack)
     $wgCommandLineMode = false;
     $runner = new JobRunner(LoggerFactory::getInstance('runJobs'));
     if (!$outputJSON) {
         $runner->setDebugHandler(array($this, 'debugInternal'));
     }
     $response = $runner->run(array('type' => $this->getOption('type', false), 'maxJobs' => $this->getOption('maxjobs', false), 'maxTime' => $this->getOption('maxtime', false), 'throttle' => $this->hasOption('nothrottle') ? false : true));
     if ($outputJSON) {
         $this->output(FormatJson::encode($response, true));
     }
     $wgCommandLineMode = true;
 }
Example #6
0
 public function execute()
 {
     if (wfReadOnly()) {
         $this->error("Unable to run jobs; the wiki is in read-only mode.", 1);
         // die
     }
     if ($this->hasOption('procs')) {
         $procs = intval($this->getOption('procs'));
         if ($procs < 1 || $procs > 1000) {
             $this->error("Invalid argument to --procs", true);
         } elseif ($procs != 1) {
             $fc = new ForkController($procs);
             if ($fc->start() != 'child') {
                 exit(0);
             }
         }
     }
     $json = $this->getOption('result') === 'json';
     $runner = new JobRunner();
     if (!$json) {
         $runner->setDebugHandler(array($this, 'debugInternal'));
     }
     $response = $runner->run(array('type' => $this->getOption('type', false), 'maxJobs' => $this->getOption('maxjobs', false), 'maxTime' => $this->getOption('maxtime', false), 'throttle' => $this->hasOption('nothrottle') ? false : true));
     if ($json) {
         $this->output(FormatJson::encode($response, true));
     }
 }
 public function execute()
 {
     $res = array();
     foreach (explode(' ', $this->getOption('settings')) as $name) {
         if (!preg_match('/^wg[A-Z]/', $name)) {
             throw new MWException("Variable '{$name}' does start with 'wg'.");
         } elseif (!isset($GLOBALS[$name])) {
             throw new MWException("Variable '{$name}' is not set.");
         } elseif (!$this->isAllowedVariable($GLOBALS[$name])) {
             throw new MWException("Variable '{$name}' includes non-array, non-scalar, items.");
         }
         $res[$name] = $GLOBALS[$name];
     }
     $out = null;
     switch ($this->getOption('format')) {
         case 'PHP':
             $out = serialize($res);
             break;
         case 'JSON':
             $out = FormatJson::encode($res);
             break;
         default:
             throw new MWException("Invalid serialization format given.");
     }
     if (!is_string($out)) {
         throw new MWException("Failed to serialize the requested settings.");
     }
     $this->output($out . "\n");
 }
 /**
  * @param $username string
  * @return CollaborationListContent
  */
 public static function makeMemberList($username, $initialDescription)
 {
     $linkToUserpage = Title::makeTitleSafe(NS_USER, $username)->getPrefixedText();
     $newMemberList = ["displaymode" => "members", "columns" => [["items" => [["title" => $linkToUserpage]]]], "options" => ["mode" => "normal"], "description" => "{$initialDescription}"];
     $newMemberListJson = FormatJson::encode($newMemberList, "\t", FormatJson::ALL_OK);
     return new CollaborationListContent($newMemberListJson);
 }
 /**
  * @dataProvider provideDataAndParserText
  */
 public function testFillParserOutput($data, $expected)
 {
     $obj = new JsonContent(FormatJson::encode($data));
     $parserOutput = $obj->getParserOutput($this->getMockTitle(), null, null, true);
     $this->assertInstanceOf('ParserOutput', $parserOutput);
     $this->assertEquals($expected, $parserOutput->getText());
 }
Example #10
0
 /**
  * @see SMWResultPrinter::getFormatOutput
  *
  * @since 1.8
  *
  * @param array $data label => value
  * @return string
  */
 protected function getFormatOutput(array $data)
 {
     // Object count
     static $statNr = 0;
     $d3chartID = 'd3-chart-' . ++$statNr;
     $this->isHTML = true;
     // Reorganize the raw data
     foreach ($data as $name => $value) {
         if ($value >= $this->params['min']) {
             $dataObject[] = array('label' => $name, 'value' => $value);
         }
     }
     // Ensure right conversion
     $width = strstr($this->params['width'], "%") ? $this->params['width'] : $this->params['width'] . 'px';
     // Prepare transfer objects
     $d3data = array('data' => $dataObject, 'parameters' => array('colorscheme' => $this->params['colorscheme'] ? $this->params['colorscheme'] : null, 'charttitle' => $this->params['charttitle'], 'charttext' => $this->params['charttext'], 'datalabels' => $this->params['datalabels']));
     // Encoding
     $requireHeadItem = array($d3chartID => FormatJson::encode($d3data));
     SMWOutputs::requireHeadItem($d3chartID, Skin::makeVariablesScript($requireHeadItem));
     // RL module
     $resource = 'ext.srf.d3.chart.' . $this->params['charttype'];
     SMWOutputs::requireResource($resource);
     // Chart/graph placeholder
     $chart = Html::rawElement('div', array('id' => $d3chartID, 'class' => 'container', 'style' => 'display:none;'), null);
     // Processing placeholder
     $processing = SRFUtils::htmlProcessingElement($this->isHTML);
     // Beautify class selector
     $class = $this->params['charttype'] ? '-' . $this->params['charttype'] : '';
     $class = $this->params['class'] ? $class . ' ' . $this->params['class'] : $class . ' d3-chart-common';
     // D3 wrappper
     return Html::rawElement('div', array('class' => 'srf-d3-chart' . $class, 'style' => "width:{$width}; height:{$this->params['height']}px;"), $processing . $chart);
 }
 public function execute()
 {
     $filename = $this->getArg(0);
     if (!is_readable($filename)) {
         $this->error("Error: Unable to read {$filename}", 1);
     }
     $json = FormatJson::decode(file_get_contents($filename), true);
     if ($json === null) {
         $this->error("Error: Invalid JSON", 1);
     }
     if (!isset($json['manifest_version'])) {
         $json['manifest_version'] = 1;
     }
     if ($json['manifest_version'] == ExtensionRegistry::MANIFEST_VERSION) {
         $this->output("Already at the latest version: {$json['manifest_version']}\n");
         return;
     }
     while ($json['manifest_version'] !== ExtensionRegistry::MANIFEST_VERSION) {
         $json['manifest_version'] += 1;
         $func = "updateTo{$json['manifest_version']}";
         $this->{$func}($json);
     }
     file_put_contents($filename, FormatJson::encode($json, "\t", FormatJson::ALL_OK) . "\n");
     $this->output("Updated to {$json['manifest_version']}...\n");
 }
Example #12
0
 public function testParseGeocoderCircle()
 {
     global $egMultiMaps_AllowGeocoderTests;
     if (!$egMultiMaps_AllowGeocoderTests) {
         return;
     }
     $this->assertRegExp('{"circles":\\[{"radius":\\[[0-9\\.]+\\],"pos":\\[{"lat":[0-9\\.]+,"lon":[0-9\\.]+}\\]}\\],"bounds":{"ne":{"lat":[0-9\\.]+,"lon":[0-9\\.]+},"sw":{"lat":[0-9\\.]+,"lon":[0-9\\.]+}}}', \FormatJson::encode($this->object->getMapData(array('circle=Moscow', 'service=google'))));
 }
Example #13
0
 public function testGetTourNames()
 {
     $this->assertSame(array(), GuidedTourHooks::getTourNames(null), 'Returns empty array for null parameter');
     $this->assertSame(array('test'), GuidedTourHooks::getTourNames(FormatJson::encode(array('version' => 1, 'tours' => array('test' => array('step' => 3))))), 'Valid JSON cookie with a single tour is parsed correctly');
     $this->assertSame(array('firsttour', 'secondtour', 'thirdtour'), GuidedTourHooks::getTourNames(FormatJson::encode(array('version' => 1, 'tours' => array('firsttour' => array('step' => 4), 'secondtour' => array('step' => 2), 'thirdtour' => array('step' => 3, 'firstArticleId' => 38333))))), 'Valid JSON cookie with multiple tours is parsed correctly');
     $this->assertSame(array(), GuidedTourHooks::getTourNames('{"bad": "cookie"}'), 'Valid JSON with missing tours field returns empty array');
     $this->assertSame(array(), GuidedTourHooks::getTourNames('<invalid: JSON>'), 'Invalid JSON returns empty array');
 }
	/**
	 * BeforePageDisplay hook
	 *
	 * Adds the modules to the page
	 *
	 * @param $out OutputPage output page
	 * @param $skin Skin current skin
	 */
	public static function beforePageDisplay( $out, $skin ) {
		$title = $out->getTitle();
		if( $title->isSpecial( 'Preferences' ) ) {
			$out->addModules('ext.tzpicker');
			$out->addInlineScript("window.mw_ext_tzpicker_ZoneInfo=" .
					FormatJson::encode(self::zoneInfo()));
		}
		return true;
	}
 /**
  * Adds the needed JS messages to the page output.
  * This is for backward compatibility with pre-RL MediaWiki.
  * 
  * @since 0.1
  */
 protected static function addJSLocalisation()
 {
     global $egLTJSMessages, $wgOut;
     $data = array();
     foreach ($egLTJSMessages as $msg) {
         $data[$msg] = wfMsgNoTrans($msg);
     }
     $wgOut->addInlineScript('var wgLTEMessages = ' . FormatJson::encode($data) . ';');
 }
 function toString()
 {
     $stringContestants = array();
     /**
      * @var $contestant ContestContestant
      */
     foreach ($this->params['contestants'] as $contestant) {
         $stringContestants[] = FormatJson::encode($contestant->getFields());
     }
     return 'Contest reminder email for contest ' . $this->params['contest']->getId() . ' for these ' . count($this->params['contestants']) . ' contestants: ' . implode(', ', $stringContestants) . '.';
 }
Example #17
0
 public function execute()
 {
     $prefix = $suffix = '';
     $params = $this->extractRequestParams();
     $callback = $params['callback'];
     if (!is_null($callback)) {
         $prefix = preg_replace("/[^][.\\'\\\"_A-Za-z0-9]/", '', $callback) . '(';
         $suffix = ')';
     }
     $this->printText($prefix . FormatJson::encode($this->getResultData(), $this->getIsHtml()) . $suffix);
 }
 /**
  * Tests behavior when content is missing from memcached and has to
  * be retrieved via HTTP instead.
  */
 function testSchemaNotInCacheDoUpdate()
 {
     global $wgEventLoggingDBname;
     // If the revision was not in memcached...
     $this->cache->expects($this->once())->method('get')->with($this->equalTo("schema:{$wgEventLoggingDBname}:Test:99"))->will($this->returnValue(false));
     // ...RemoteSchema will attempt to acquire an update lock:
     $this->cache->expects($this->any())->method('add')->with($this->stringContains("schema:{$wgEventLoggingDBname}:Test:99"))->will($this->returnValue(true));
     // With the lock acquired, we'll see an HTTP request
     // for the revision:
     $this->http->expects($this->once())->method('get')->with($this->stringContains('?'), $this->lessThan(RemoteSchema::LOCK_TIMEOUT))->will($this->returnValue(FormatJson::encode($this->statusSchema)));
     $this->assertEquals($this->statusSchema, $this->schema->get());
 }
Example #19
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $json = FormatJson::encode($this->getResultData(), $this->getIsHtml(), $params['utf8'] ? FormatJson::ALL_OK : FormatJson::XMLMETA_OK);
     $callback = $params['callback'];
     if ($callback !== null) {
         $callback = preg_replace("/[^][.\\'\\\"_A-Za-z0-9]/", '', $callback);
         $this->printText("{$callback}({$json})");
     } else {
         $this->printText($json);
     }
 }
 /**
  * EditPage::showEditForm:initial hook
  * Adds the modules to the edit form
  */
 public static function addModules(&$toolbar)
 {
     global $wgOut, $wgUser, $wgJsMimeType;
     global $wgWikiEditorModules, $wgUsabilityInitiativeResourceMode;
     // Modules
     $preferences = array();
     $enabledModules = array();
     $modules = $wgWikiEditorModules;
     $modules['global'] = true;
     foreach ($modules as $module => $enable) {
         if ($enable['global'] || $enable['user'] && isset(self::$modules[$module]['preferences']['enable']) && $wgUser->getOption(self::$modules[$module]['preferences']['enable']['key']) || $module == 'global') {
             if ($module !== 'global') {
                 UsabilityInitiativeHooks::initialize();
             }
             $enabledModules[$module] = true;
             // Messages
             if (isset(self::$modules[$module]['i18n'], self::$modules[$module]['messages'])) {
                 wfLoadExtensionMessages(self::$modules[$module]['i18n']);
                 UsabilityInitiativeHooks::addMessages(self::$modules[$module]['messages']);
             }
             // Variables
             if (isset(self::$modules[$module]['variables'])) {
                 $variables = array();
                 foreach (self::$modules[$module]['variables'] as $variable) {
                     global ${$variable};
                     $variables[$variable] = ${$variable};
                 }
                 UsabilityInitiativeHooks::addVariables($variables);
             }
             // Preferences
             if (isset(self::$modules[$module]['preferences'])) {
                 foreach (self::$modules[$module]['preferences'] as $name => $preference) {
                     if (!isset($preferences[$module])) {
                         $preferences[$module] = array();
                     }
                     $preferences[$module][$name] = $wgUser->getOption($preference['key']);
                 }
             }
         } else {
             $enabledModules[$module] = false;
         }
     }
     // Load global messages
     wfLoadExtensionMessages('WikiEditor');
     UsabilityInitiativeHooks::addMessages(self::$messages);
     // Add all scripts
     foreach (self::$scripts[$wgUsabilityInitiativeResourceMode] as $script) {
         UsabilityInitiativeHooks::addScript(basename(dirname(__FILE__)) . '/' . $script['src'], $script['version']);
     }
     // Preferences (maybe the UsabilityInitiative class could do most of this for us?)
     $wgOut->addScript(Xml::tags('script', array('type' => $wgJsMimeType), 'var wgWikiEditorPreferences = ' . FormatJson::encode($preferences, true) . ";\n" . 'var wgWikiEditorEnabledModules = ' . FormatJson::encode($enabledModules, true) . ';'));
     return true;
 }
 public function execute($par = '')
 {
     $this->getOutput()->disable();
     if (wfReadOnly()) {
         header("HTTP/1.0 423 Locked");
         print 'Wiki is in read-only mode';
         return;
     } elseif (!$this->getRequest()->wasPosted()) {
         header("HTTP/1.0 400 Bad Request");
         print 'Request must be POSTed';
         return;
     }
     $optional = array('maxjobs' => 0, 'maxtime' => 30, 'type' => false, 'async' => true);
     $required = array_flip(array('title', 'tasks', 'signature', 'sigexpiry'));
     $params = array_intersect_key($this->getRequest()->getValues(), $required + $optional);
     $missing = array_diff_key($required, $params);
     if (count($missing)) {
         header("HTTP/1.0 400 Bad Request");
         print 'Missing parameters: ' . implode(', ', array_keys($missing));
         return;
     }
     $squery = $params;
     unset($squery['signature']);
     $correctSignature = self::getQuerySignature($squery, $this->getConfig()->get('SecretKey'));
     $providedSignature = $params['signature'];
     $verified = is_string($providedSignature) && hash_equals($correctSignature, $providedSignature);
     if (!$verified || $params['sigexpiry'] < time()) {
         header("HTTP/1.0 400 Bad Request");
         print 'Invalid or stale signature provided';
         return;
     }
     // Apply any default parameter values
     $params += $optional;
     if ($params['async']) {
         // Client will usually disconnect before checking the response,
         // but it needs to know when it is safe to disconnect. Until this
         // reaches ignore_user_abort(), it is not safe as the jobs won't run.
         ignore_user_abort(true);
         // jobs may take a bit of time
         header("HTTP/1.0 202 Accepted");
         ob_flush();
         flush();
         // Once the client receives this response, it can disconnect
     }
     // Do all of the specified tasks...
     if (in_array('jobs', explode('|', $params['tasks']))) {
         $runner = new JobRunner(LoggerFactory::getInstance('runJobs'));
         $response = $runner->run(array('type' => $params['type'], 'maxJobs' => $params['maxjobs'] ? $params['maxjobs'] : 1, 'maxTime' => $params['maxtime'] ? $params['maxjobs'] : 30));
         if (!$params['async']) {
             print FormatJson::encode($response, true);
         }
     }
 }
 /**
  * BeforePageDisplay hook
  * Adds the modules to the edit form
  */
 public static function addModules()
 {
     global $wgUser, $wgJsMimeType, $wgOut;
     global $wgVectorModules, $wgUsabilityInitiativeResourceMode;
     // Don't load Vector modules for non-Vector skins
     // They won't work but will throw unused JS in the client's face
     // Using instanceof to catch any skins subclassing Vector
     if (!$wgUser->getSkin() instanceof SkinVector) {
         return true;
     }
     // Modules
     $preferences = array();
     $enabledModules = array();
     foreach ($wgVectorModules as $module => $enable) {
         if ($enable['global'] || $enable['user'] && isset(self::$modules[$module]['preferences']['enable']) && $wgUser->getOption(self::$modules[$module]['preferences']['enable']['key'])) {
             UsabilityInitiativeHooks::initialize();
             $enabledModules[$module] = true;
             // Messages
             if (isset(self::$modules[$module]['i18n'], self::$modules[$module]['messages'])) {
                 wfLoadExtensionMessages(self::$modules[$module]['i18n']);
                 UsabilityInitiativeHooks::addMessages(self::$modules[$module]['messages']);
             }
             // Variables
             if (isset(self::$modules[$module]['variables'])) {
                 $variables = array();
                 foreach (self::$modules[$module]['variables'] as $variable) {
                     global ${$variable};
                     $variables[$variable] = ${$variable};
                 }
                 UsabilityInitiativeHooks::addVariables($variables);
             }
             // Preferences
             if (isset(self::$modules[$module]['preferences'])) {
                 foreach (self::$modules[$module]['preferences'] as $name => $preference) {
                     if (!isset($preferences[$module])) {
                         $preferences[$module] = array();
                     }
                     $preferences[$module][$name] = $wgUser->getOption($preference['key']);
                 }
             }
         } else {
             $enabledModules[$module] = false;
         }
     }
     // Add all scripts
     foreach (self::$scripts[$wgUsabilityInitiativeResourceMode] as $script) {
         UsabilityInitiativeHooks::addScript(basename(dirname(__FILE__)) . '/' . $script['src'], $script['version']);
     }
     // Preferences (maybe the UsabilityInitiative class could do most of this for us?)
     $wgOut->addScript(Xml::tags('script', array('type' => $wgJsMimeType), 'var wgVectorPreferences = ' . FormatJson::encode($preferences, true) . ";\n" . 'var wgVectorEnabledModules = ' . FormatJson::encode($enabledModules, true) . ';'));
     return true;
 }
 /**
  * Generate the JS for the requested banner
  * @return a string of Javascript containing a call to insertBanner()
  *   with JSON containing the banner content as the parameter
  * @throws SpecialBannerLoaderException
  */
 function getJsNotice($bannerName)
 {
     // Make sure the banner exists
     if (CentralNoticeDB::bannerExists($bannerName)) {
         $this->bannerName = $bannerName;
         $bannerHtml = '';
         $bannerHtml .= preg_replace_callback('/{{{(.*?)}}}/', array($this, 'getNoticeField'), $this->getNoticeTemplate());
         $bannerArray = array('bannerName' => $bannerName, 'bannerHtml' => $bannerHtml, 'campaign' => $this->campaign, 'fundraising' => $this->getFundraising($bannerName), 'autolink' => $this->getAutolink($bannerName), 'landingPages' => $this->getLandingPages($bannerName));
         $bannerJs = 'insertBanner(' . FormatJson::encode($bannerArray) . ');';
         return $bannerJs;
     }
     return '';
 }
Example #24
0
 public function jsonEncode($value, $flags)
 {
     $this->checkTypeOptional('mw.text.jsonEncode', 2, $flags, 'number', 0);
     $flags = (int) $flags;
     if (!($flags & self::JSON_PRESERVE_KEYS) && is_array($value)) {
         $value = self::reindexArrays($value, true);
     }
     $ret = FormatJson::encode($value, (bool) ($flags & self::JSON_PRETTY), FormatJson::ALL_OK);
     if ($ret === false) {
         throw new Scribunto_LuaError('mw.text.jsonEncode: Unable to encode value');
     }
     return array($ret);
 }
 public function execute()
 {
     $params = $this->extractRequestParams();
     $json = FormatJson::encode($this->getResultData(), $this->getIsHtml(), $params['utf8'] ? FormatJson::ALL_OK : FormatJson::XMLMETA_OK);
     $callback = $params['callback'];
     if ($callback !== null) {
         $callback = preg_replace("/[^][.\\'\\\"_A-Za-z0-9]/", '', $callback);
         # Prepend a comment to try to avoid attacks against content
         # sniffers, such as bug 68187.
         $this->printText("/**/{$callback}({$json})");
     } else {
         $this->printText($json);
     }
 }
 public function getScript(ResourceLoaderContext $context)
 {
     // Messages
     $msgInfo = $this->getMessageInfo();
     $parsedMessages = array();
     $messages = array();
     foreach ($msgInfo['args'] as $msgKey => $msgArgs) {
         $parsedMessages[$msgKey] = call_user_func_array('wfMessage', $msgArgs)->inLanguage($context->getLanguage())->parse();
     }
     foreach ($msgInfo['vals'] as $msgKey => $msgVal) {
         $messages[$msgKey] = $msgVal;
     }
     return 've.init.platform.addParsedMessages(' . FormatJson::encode($parsedMessages, ResourceLoader::inDebugMode()) . ');' . 've.init.platform.addMessages(' . FormatJson::encode($messages, ResourceLoader::inDebugMode()) . ');';
 }
 public function execute()
 {
     $phpfile = $this->getArg(0);
     $jsondir = $this->getArg(1);
     if ($this->hasOption('shim-only')) {
         $this->shimOnly($phpfile, $jsondir);
         return;
     }
     if ($jsondir === null) {
         $this->error('Argument [jsondir] is required unless --shim-only is specified.');
         $this->maybeHelp(true);
     }
     if (!is_readable($phpfile)) {
         $this->error("Error reading {$phpfile}\n", 1);
     }
     include $phpfile;
     $phpfileContents = file_get_contents($phpfile);
     if (!isset($messages)) {
         $this->error("PHP file {$phpfile} does not define \$messages array\n", 1);
     }
     $extensionStyle = true;
     if (!isset($messages['en']) || !is_array($messages['en'])) {
         if (!$this->hasOption('langcode')) {
             $this->error("PHP file {$phpfile} does not set language codes, --langcode " . "is required.\n", 1);
         }
         $extensionStyle = false;
         $langcode = $this->getOption('langcode');
         $messages = array($langcode => $messages);
     } elseif ($this->hasOption('langcode')) {
         $this->output("Warning: --langcode option set but will not be used.\n");
     }
     foreach ($messages as $langcode => $langmsgs) {
         $authors = $this->getAuthorsFromComment($this->findCommentBefore($extensionStyle ? "\$messages['{$langcode}'] =" : '$messages =', $phpfileContents));
         // Make sure the @metadata key is the first key in the output
         $langmsgs = array_merge(array('@metadata' => array('authors' => $authors)), $langmsgs);
         $jsonfile = "{$jsondir}/{$langcode}.json";
         $success = file_put_contents($jsonfile, FormatJson::encode($langmsgs, "\t", FormatJson::ALL_OK) . "\n");
         if ($success === false) {
             $this->error("FAILED to write {$jsonfile}", 1);
         }
         $this->output("{$jsonfile}\n");
     }
     if (!$this->hasOption('langcode')) {
         $shim = $this->doShim($jsondir);
         file_put_contents($phpfile, $shim);
     }
     $this->output("All done.\n");
     $this->output("Also add \$wgMessagesDirs['YourExtension'] = __DIR__ . '/i18n';\n");
 }
 /**
  * Constructs HTML representation of a single key-value pair.
  * @return string: HTML.
  */
 static function objectRow($key, $val)
 {
     $th = Xml::elementClean('th', array(), $key);
     if (is_array($val)) {
         $td = Xml::tags('td', array(), self::objectTable($val));
     } else {
         if (is_string($val)) {
             $val = '"' . $val . '"';
         } else {
             $val = FormatJson::encode($val);
         }
         $td = Xml::elementClean('td', array('class' => 'value'), $val);
     }
     return Xml::tags('tr', array(), $th . $td);
 }
function wfWikimediaMobileAddJs( &$outputPage, &$skin ) {
	global $wgOut, $wgExtensionAssetsPath, $wgWikimediaMobileVersion;

	global $wgTitle, $wgRequest, $wgWikimediaMobileUrl;
	$ns = $wgTitle->getNamespace();
	$action = FormatJson::encode( $wgRequest->getVal( 'action', 'view' ) );
	$page = FormatJson::encode( $wgTitle->getPrefixedDBkey() );
	$mainpage = Title::newMainPage();
	$mp = FormatJson::encode( $mainpage ? $mainpage->getPrefixedText() : null );
	$url = FormatJson::encode( $wgWikimediaMobileUrl );
	$wgOut->addHeadItem( 'mobileredirectvars', Html::inlineScript( "wgNamespaceNumber=$ns;wgAction=$action;wgPageName=$page;wgMainPageTitle=$mp;wgWikimediaMobileUrl=$url;" ) );
	$wgOut->addHeadItem( 'mobileredirect', Html::linkedScript(
		"$wgExtensionAssetsPath/WikimediaMobile/MobileRedirect.js?$wgWikimediaMobileVersion"
	) );
	return true;
}
 /**
  * Generate JSON for the specified site
  */
 function getJsonList()
 {
     $banners = array();
     // See if we have any preferred campaigns for this language and project
     $campaigns = CentralNoticeDB::getCampaigns($this->project, $this->language, null, 1, 1, $this->location);
     // Quick short circuit to show preferred campaigns
     if ($campaigns) {
         // Pull banners
         $banners = CentralNoticeDB::getCampaignBanners($campaigns);
     }
     // Didn't find any preferred banners so do an old style lookup
     if (!$banners) {
         $banners = CentralNoticeDB::getBannersByTarget($this->project, $this->language, $this->location);
     }
     return FormatJson::encode($banners);
 }