本文整理汇总了PHP中FormatJson类的典型用法代码示例。如果您正苦于以下问题:PHP FormatJson类的具体用法?PHP FormatJson怎么用?PHP FormatJson使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FormatJson类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getFormatOutput
/**
* @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);
}
示例2: getFormatOutput
/**
* 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);
}
示例3: execute
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";
}
}
}
}
示例4: fetchScriptList
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;
}
示例5: execute
/**
* @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';
}
示例6: getFormatOutput
/**
* 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);
}
示例7: execute
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));
}
示例8: execute
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();
}
示例9: execute
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));
}
}
示例10: execute
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");
}
示例11: makeMemberList
/**
* @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);
}
开发者ID:wikimedia,项目名称:mediawiki-extensions-CollaborationKit,代码行数:11,代码来源:CollaborationListContentHandler.php
示例12: getUntranslatedPages
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;
}
示例13: execute
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'));
}
示例14: passCaptcha
/**
* 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'];
}
示例15: execute
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;
}