/** * @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); }
/** * 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); }
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"; } } } }
protected function fetchScriptList() { $data = ['action' => 'query', 'format' => 'json', 'list' => 'allpages', 'apnamespace' => '8', 'aplimit' => '500', 'continue' => '']; $baseUrl = $this->getArg(0); $pages = []; while (true) { $url = wfAppendQuery($baseUrl, $data); $strResult = Http::get($url, [], __METHOD__); $result = FormatJson::decode($strResult, true); $page = null; foreach ($result['query']['allpages'] as $page) { if (substr($page['title'], -3) === '.js') { strtok($page['title'], ':'); $pages[] = strtok(''); } } if ($page !== null) { $this->output("Fetched list up to {$page['title']}\n"); } if (isset($result['continue'])) { // >= 1.21 $data = array_replace($data, $result['continue']); } elseif (isset($result['query-continue']['allpages'])) { // <= 1.20 $data = array_replace($data, $result['query-continue']['allpages']); } else { break; } } return $pages; }
/** * @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'; }
/** * 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); }
public function execute() { $params = $this->extractRequestParams(); $this->requireOnlyOneParameter($params, 'vars', 'rcid', 'logid'); // "Anti-DoS" if (!$this->getUser()->isAllowed('abusefilter-modify')) { $this->dieUsageMsg('permissiondenied'); } if ($params['vars']) { $vars = FormatJson::decode($params['vars'], true); } elseif ($params['rcid']) { $dbr = wfGetDB(DB_SLAVE); $row = $dbr->selectRow('recentchanges', '*', array('rc_id' => $params['rcid']), __METHOD__); if (!$row) { $this->dieUsageMsg(array('nosuchrcid', $params['rcid'])); } $vars = AbuseFilter::getVarsFromRCRow($row); } elseif ($params['logid']) { $dbr = wfGetDB(DB_SLAVE); $row = $dbr->selectRow('abuse_filter_log', '*', array('afl_id' => $params['logid']), __METHOD__); if (!$row) { $this->dieUsage("There is no abuselog entry with the id ``{$params['logid']}''", 'nosuchlogid'); } $vars = AbuseFilter::loadVarDump($row->afl_var_dump); } if (AbuseFilter::checkSyntax($params['filter']) !== true) { $this->dieUsage('The filter has invalid syntax', 'badsyntax'); } $result = AbuseFilter::checkConditions($params['filter'], $vars); $this->getResult()->addValue(null, $this->getModuleName(), array('result' => $result)); }
public function execute() { global $wgUser; if (!$wgUser->isAllowed('surveysubmit') || $wgUser->isBlocked()) { $this->dieUsageMsg(array('badaccess-groups')); } $params = $this->extractRequestParams(); if (!(isset($params['id']) xor isset($params['name']))) { $this->dieUsage(wfMsg('survey-err-id-xor-name'), 'id-xor-name'); } if (isset($params['name'])) { $survey = Survey::newFromName($params['name'], null, false); if ($survey === false) { $this->dieUsage(wfMsgExt('survey-err-survey-name-unknown', 'parsemag', $params['name']), 'survey-name-unknown'); } } else { $survey = Survey::newFromId($params['id'], null, false); if ($survey === false) { $this->dieUsage(wfMsgExt('survey-err-survey-id-unknown', 'parsemag', $params['id']), 'survey-id-unknown'); } } $submission = new SurveySubmission(array('survey_id' => $survey->getId(), 'page_id' => 0, 'user_name' => $GLOBALS['wgUser']->getName(), 'time' => wfTimestampNow())); foreach (FormatJson::decode($params['answers']) as $answer) { $submission->addAnswer(SurveyAnswer::newFromArray((array) $answer)); } $submission->writeToDB(); }
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); }
protected function getUntranslatedPages($apiUrl, $category, $targetDomain) { $this->output("Fetching pages from {$category} not present in {$targetDomain} ..."); $pages = array(); $params = array('action' => 'query', 'format' => 'json', 'generator' => 'categorymembers', 'gcmtitle' => "Category:{$category}", 'gcmnamespace' => 0, 'gcmlimit' => 500, 'gcmsort' => 'timestamp', 'prop' => 'langlinks', 'lllang' => $targetDomain, 'lllimit' => 500, 'continue' => ''); while (true) { $url = $apiUrl . http_build_query($params); $json = Http::get($url); $data = FormatJson::decode($json, true); if (!isset($data['query'])) { $this->output("\t[FAIL]\n"); return array(); } $pagesInCategory = $data['query']['pages']; foreach ($pagesInCategory as $pageId => $page) { if (!isset($page['langlinks'])) { $pages[] = $page['title']; } } if (!isset($data['continue']) || count($pages) > 5000) { break; } else { unset($params['llcontinue']); unset($params['gcmcontinue']); $params += $data['continue']; } } $this->output("\t[OK]\n"); return $pages; }
public function execute() { global $wgUser; $result = $this->getResult(); $params = $this->extractRequestParams(); $token = array(); if ($wgUser->isAnon()) { if (!isset($params['anontoken'])) { $this->dieUsageMsg(array('missingparam', 'anontoken')); } elseif (strlen($params['anontoken']) != 32) { $this->dieUsage('The anontoken is not 32 characters', 'invalidtoken'); } $token = $params['anontoken']; } else { $token = ''; } $dbr = wfGetDB(DB_SLAVE); $dbw = wfGetDB(DB_MASTER); // Check if the incoming survey is valid $surveyCount = $dbr->selectRow('research_tools_surveys', 'rts_id', array('rts_id' => $params['survey']), __METHOD__); if ($surveyCount === false) { $this->dieUsage('The survey is unknown', 'invalidsurvey'); } // Find an existing response from this user for this survey $response = $dbr->selectRow('research_tools_survey_responses', 'rtsr_id', array('rtsr_user_text' => $wgUser->getName(), 'rtsr_user_anon_token' => $token, 'rtsr_survey' => $params['survey']), __METHOD__); if ($response !== false) { // Delete any of the previous answers (they questions may have changed) $dbw->delete('research_tools_survey_answers', array('rtsa_response' => $response->rtsr_id), __METHOD__); } // Decode JSON answer data $answers = FormatJson::decode($params['answers'], true); if (!is_array($answers)) { $this->dieUsage('Invalid answer data', 'invalidanswers'); } // Verify questions exist foreach ($answers as $question => $answer) { $question = $dbr->selectRow('research_tools_survey_questions', 'rtsq_id', array('rtsq_survey' => $params['survey'], 'rtsq_id' => $question), __METHOD__); if ($question === false) { $this->dieUsage('A question is unknown', 'invalidquestion'); } } if ($response === false) { // Insert a new response row $dbw->insert('research_tools_survey_responses', array('rtsr_time' => wfTimestamp(TS_MW), 'rtsr_user_text' => $wgUser->getName(), 'rtsr_user_anon_token' => $token, 'rtsr_survey' => $params['survey']), __METHOD__); $response = $dbw->insertId(); } else { $response = $response->rtsr_id; // Update the timestamp of the existing response row $dbw->update('research_tools_survey_responses', array('rtsr_time' => wfTimestamp(TS_MW)), array('rtsr_id' => $response), __METHOD__); } // Insert answers for the response $answerRows = array(); foreach ($answers as $question => $answer) { // Build row data $answerRows[] = array('rtsa_response' => $response, 'rtsa_question' => $question, 'rtsa_value_integer' => is_numeric($answer) ? intval($answer) : null, 'rtsa_value_text' => is_numeric($answer) ? '' : $answer); } $dbw->insert('research_tools_survey_answers', $answerRows, __METHOD__); // Add success to result $result->addValue(null, $this->getModuleName(), array('result' => 'Success')); }
/** * Check, if the user solved the captcha. * * Based on reference implementation: * https://github.com/google/recaptcha#php * * @return boolean */ function passCaptcha() { global $wgRequest, $wgReCaptchaSecretKey, $wgReCaptchaSendRemoteIP; $url = 'https://www.google.com/recaptcha/api/siteverify'; // Build data to append to request $data = array('secret' => $wgReCaptchaSecretKey, 'response' => $wgRequest->getVal('g-recaptcha-response')); if ($wgReCaptchaSendRemoteIP) { $data['remoteip'] = $wgRequest->getIP(); } $url = wfAppendQuery($url, $data); $request = MWHttpRequest::factory($url, array('method' => 'GET')); $status = $request->execute(); if (!$status->isOK()) { $this->error = 'http'; $this->logStatusError($status); return false; } $response = FormatJson::decode($request->getContent(), true); if (!$response) { $this->error = 'json'; $this->logStatusError($this->error); return false; } if (isset($response['error-codes'])) { $this->error = 'recaptcha-api'; $this->logCheckError($response['error-codes']); return false; } return $response['success']; }
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; }
/** * Tests JSON pretty-printing. * @covers JsonSchemaContent::preSaveTransform */ function testPreSaveTransform() { $transformed = new JsonSchemaContent(self::VALID_JSON_SCHEMA); $prettyJson = $transformed->preSaveTransform(new Title(), new User(), new ParserOptions())->getNativeData(); $this->assertContains("\n", $prettyJson, 'Transformed JSON is beautified.'); $this->assertEquals(FormatJson::decode($prettyJson), FormatJson::decode(self::VALID_JSON_SCHEMA), 'Beautification does not alter JSON value.'); }
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"); }
/** * @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()); }
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'); }
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')))); }
/** * 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) . ';'); }
/** @brief Perform API request and return the resulting structure. @note If $query contains 'token' => 'null', then 'token' will be set to the current value of $editToken. */ public function query($query) { $query['format'] = 'json'; if (array_key_exists('token', $query) && is_null($query['token'])) { $query['token'] = $this->editToken; } $req = $this->t->httpPost($this->apiUrl, $query); return FormatJson::decode($req->getContent(), true); }
/** * 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; }
public function parse($contents) { $messages = FormatJson::decode($contents, true); unset($messages['@metadata']); if ($this->code) { return array($this->code => $messages); } // Assuming that the array is keyed by language codes return $messages; }
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) . '.'; }
protected function parseResponse(TranslationQueryResponse $reply) { $body = $reply->getBody(); $response = FormatJson::decode($body); if (!is_object($response)) { throw new TranslationWebServiceException('Invalid json: ' . serialize($body)); } $text = preg_replace('~^<div>(.*)</div>$~', '\\1', $response->contents); $text = $this->unwrapUntranslatable($text); return trim($text); }
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); }
/** * 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); } } }
/** * Process a newJob req: */ function proccessJobReq() { if (isset($this->mParams['jobset']) && $this->mParams['jobset']) { $job = WahJobManager::getNewJob($this->mParams['jobset']); } else { $job = WahJobManager::getNewJob(); } if (!$job) { return $this->getResult()->addValue(null, $this->getModuleName(), array('nojobs' => true)); } else { $job4Client = array(); //unpack the $job_json $job4Client['job_json'] = FormatJson::decode($job->job_json); //we set the job key to job_id _ sha1 $job4Client['job_key'] = $job->job_id . '_' . sha1($job->job_json); $job4Client['job_title'] = $job->title; $job4Client['job_ns'] = $job->ns; $job4Client['job_set_id'] = $job->job_set_id; $tTitle = Title::newFromText($job->title, $job->ns); $job4Client['job_fullTitle'] = $tTitle->getFullText(); //@@todo avoid an api round trip return url here: //$job4Client['job_url'] = $file->getFullURL(); $this->getResult()->addValue(null, $this->getModuleName(), array('job' => $job4Client)); } }