API:Options

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page API:Options and the translation is 100% complete.
Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎polski • ‎русский • ‎中文 • ‎日本語
Versión de MediaWiki: 1.20

Solicitud POST para cambiar las preferencias del usuario actual.

API Documentación


action=options

(main | options)
  • This module requires read rights.
  • This module requires write rights.
  • This module only accepts POST requests.
  • Source: MediaWiki
  • License: GPL-2.0-or-later

Change preferences of the current user.

Only options which are registered in core or in one of installed extensions, or options with keys prefixed with userjs- (intended to be used by user scripts), can be set.

Parameters:
reset

Resets preferences to the site defaults.

Type: boolean (details)
resetkinds

List of types of options to reset when the reset option is set.

Values (separate with | or alternative): all, registered, registered-checkmatrix, registered-multiselect, special, unused, userjs
Default: all
change

List of changes, formatted name=value (e.g. skin=vector). If no value is given (not even an equals sign), e.g., optionname|otheroption|..., the option will be reset to its default value. If any value passed contains the pipe character (|), use the alternative multiple-value separator for correct operation.

Separate values with | or alternative.
Maximum number of values is 50 (500 for clients allowed higher limits).
optionname

The name of the option that should be set to the value given by optionvalue.

optionvalue

The value for the option specified by optionname.

token

A "csrf" token retrieved from action=query&meta=tokens

This parameter is required.

Ejemplo

Hacer cualquier solicitud POST es un proceso de varios pasos:

  1. Inicia sesión, a través de uno de los métodos descritos en API:Login .
  2. Consigue un Ficha de edición
  3. Envía una solicitud POST con el token CSRF para tomar medidas en una página.

El código de muestra, abajo, cubre el paso final en detalle.

Solicitud POST

En este ejemplo, todos los parámetros se pasan en una solicitud GET por cuestión de simplicidad. Sin embargo, action=options requiere solicitudes POST; Las solicitudes GET causarán un error.

Cambiar tres opciones

Respuesta

{
    "options": "success"
}

= Código de ejemplo

Python

#!/usr/bin/python3

"""
    change_user_options.py

    MediaWiki API Demos
    Demo of `Options` module: POST request to change three options
    for current user

    MIT license
"""

import requests

S = requests.Session()

URL = "https://test.wikipedia.org/w/api.php"

# Step 1: GET request to fetch login token
PARAMS_0 = {
    "action": "query",
    "meta": "tokens",
    "type": "login",
    "format": "json"
}

R = S.get(url=URL, params=PARAMS_0)
DATA = R.json()

LOGIN_TOKEN = DATA['query']['tokens']['logintoken']

# Step 2: POST request to log in. Use of main account for login is not
# supported. Obtain credentials via Special:BotPasswords
# (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
PARAMS_1 = {
    "action": "login",
    "lgname": "bot_user_name",
    "lgpassword": "bot_password",
    "lgtoken": LOGIN_TOKEN,
    "format": "json"
}

R = S.post(URL, data=PARAMS_1)

# Step 3: GET request to fetch CSRF token
PARAMS_2 = {
    "action": "query",
    "meta": "tokens",
    "format": "json"
}

R = S.get(url=URL, params=PARAMS_2)
DATA = R.json()

CSRF_TOKEN = DATA['query']['tokens']['csrftoken']

# Step 4: POST request to change user options
# You can check out the large list of options you can change
# at https://www.mediawiki.org/wiki/API:Options
PARAMS_3 = {
    "action": "options",
    "format": "json",
    "token": CSRF_TOKEN,
    "change": "language=en|skin=vector",
    "optionname": "nickname",
    "optionvalue": "custom-signa|ture"
}

R = S.post(URL, data=PARAMS_3)
DATA = R.json()

print(DATA)

PHP

<?php

/*
    change_user_options.php

    MediaWiki API Demos
    Demo of `Options` module: POST request to change three options
    for current user
    MIT license
*/

$endPoint = "https://test.wikipedia.org/w/api.php";

$login_Token = getLoginToken(); // Step 1
loginRequest( $login_Token ); // Step 2
$csrf_Token = getCSRFToken(); // Step 3
change_options( $csrf_Token ); // Step 4

// Step 1: GET request to fetch login token
function getLoginToken() {
	global $endPoint;

	$params1 = [
		"action" => "query",
		"meta" => "tokens",
		"type" => "login",
		"format" => "json"
	];

	$url = $endPoint . "?" . http_build_query( $params1 );

	$ch = curl_init( $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	$result = json_decode( $output, true );
	return $result["query"]["tokens"]["logintoken"];
}

// Step 2: POST request to log in. Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest( $logintoken ) {
	global $endPoint;

	$params2 = [
		"action" => "login",
		"lgname" => "bot_user_name",
		"lgpassword" => "bot_password",
		"lgtoken" => $logintoken,
		"format" => "json"
	];

	$ch = curl_init();

	curl_setopt( $ch, CURLOPT_URL, $endPoint );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params2 ) );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

}

// Step 3: GET request to fetch CSRF token
function getCSRFToken() {
	global $endPoint;

	$params3 = [
		"action" => "query",
		"meta" => "tokens",
		"format" => "json"
	];

	$url = $endPoint . "?" . http_build_query( $params3 );

	$ch = curl_init( $url );

	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	$result = json_decode( $output, true );
	return $result["query"]["tokens"]["csrftoken"];
}

// Step 4: POST request to edit a page
function change_options( $csrftoken ) {
	global $endPoint;

	$params4 = [
		"action" => "options",
		"change" => "language=en|skin=timeless",
		"optionname" => "nickname",
		"optionvalue" => "custom-signa|ture",
		"token" => $csrftoken,
		"format" => "json"
	];

	$ch = curl_init();

	curl_setopt( $ch, CURLOPT_URL, $endPoint );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params4 ) );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, "cookie.txt" );
	curl_setopt( $ch, CURLOPT_COOKIEFILE, "cookie.txt" );

	$output = curl_exec( $ch );
	curl_close( $ch );

	echo ( $output );
}

JavaScript

/*  
    change_user_options.js
 
    MediaWiki API Demos
    Demo of `Options` module: POST request to change two options
    for current user

    MIT license
*/

var request = require('request').defaults({jar: true}),
    url = "https://test.wikipedia.org/w/api.php";

// Step 1: GET request to fetch login token
function getLoginToken() {
    var params_0 = {
        action: "query",
        meta: "tokens",
        type: "login",
        format: "json"
    };

    request.get({ url: url, qs: params_0 }, function (error, res, body) {
        if (error) {
            return;
        }
        var data = JSON.parse(body);
        loginRequest(data.query.tokens.logintoken);
    });
}

// Step 2: POST request to log in. 
// Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest(login_token) {
    var params_1 = {
        action: "login",
        lgname: "bot_username",
        lgpassword: "bot_password",
        lgtoken: login_token,
        format: "json"
    };

    request.post({ url: url, form: params_1 }, function (error, res, body) {
        if (error) {
            return;
        }
        getCsrfToken();
    });
}

// Step 3: GET request to fetch CSRF token
function getCsrfToken() {
    var params_2 = {
        action: "query",
        meta: "tokens",
        format: "json"
    };

    request.get({ url: url, qs: params_2 }, function(error, res, body) {
        if (error) {
            return;
        }
        var data = JSON.parse(body);
        change_options(data.query.tokens.csrftoken);
    });
}

// Step 4: POST request to change the user options
function change_options(csrf_token) {
    var params_3 = {
        action: "options",
        change: "language=en|skin=timeless",
        token: csrf_token,
        format: "json"
    };

    request.post({ url: url, form: params_3 }, function (error, res, body) {
        if (error) {
            return;
        }
        console.log(body);
    });
}

// Start From Step 1
getLoginToken();

MediaWiki JS

/*
	change_user_options.js

	MediaWiki API Demos
	Demo of `Options` module: POST request to change three options
    for current user

	MIT License
*/

var params = {
		action: 'options',
		change: 'language=en|skin=monobook',
		optionname: 'nickname',
		optionvalue: 'custom-signa|ture',
		format: 'json'
	},
	api = new mw.Api();

api.postWithToken( 'csrf', params ).done( function ( data ) {
	console.log( data );
} );

Opciones disponibles

La siguiente es una lista de ejemplo obtenida con /w/api.php?action=query&format=json&meta=userinfo&uiprop=options para una cuenta de Wikipedia (MW 1.24). La mayoría de las opciones enumeradas aquí están definidas por varias extensiones de MediaWiki, como Echo , VisualEditor , Extensión:WikiLove , Gadgets o EducationProgram , entre otras.
  • ccmeonemails: 0
  • cols: 80
  • date: "mdy"
  • diffonly: 0
  • disablemail: 0
  • editfont: "default"
  • editondblclick: 0
  • editsectiononrightclick: 0
  • enotifminoredits: 0
  • enotifrevealaddr: 0
  • enotifusertalkpages: 1
  • enotifwatchlistpages: 0
  • extendwatchlist: "1"
  • fancysig: "1"
  • forceeditsummary: "1"
  • gender: "male"
  • hideminor: 0
  • hidepatrolled: 0
  • imagesize: 2
  • math: 0
  • minordefault: 0
  • newpageshidepatrolled: 0
  • nickname: user signature
  • norollbackdiff: 0
  • numberheadings: 0
  • previewonfirst: 0
  • previewontop: 1
  • rcdays: "14"
  • rclimit: "100"
  • rows: 25
  • showhiddencats: false
  • shownumberswatching: 1
  • showtoolbar: 1
  • skin: "vector"
  • stubthreshold: 0
  • thumbsize: "3"
  • underline: 2
  • uselivepreview: 0
  • usenewrc: 0
  • watchcreations: 1
  • watchdefault: "1"
  • watchdeletion: 0
  • watchlistdays: "2"
  • watchlisthideanons: 0
  • watchlisthidebots: 0
  • watchlisthideliu: 0
  • watchlisthideminor: 0
  • watchlisthideown: 0
  • watchlisthidepatrolled: 0
  • watchmoves: "1"
  • wllimit: "300"
  • useeditwarning: 1
  • prefershttps: 1
  • flaggedrevssimpleui: 1
  • flaggedrevsstable: 0
  • flaggedrevseditdiffs: true
  • flaggedrevsviewdiffs: false
  • usebetatoolbar: 1
  • usebetatoolbar-cgd: 1
  • multimediaviewer-enable: true
  • visualeditor-enable: 0
  • visualeditor-betatempdisable: 0
  • visualeditor-enable-experimental: 0
  • visualeditor-enable-language: 0
  • visualeditor-hidebetawelcome: 0
  • wikilove-enabled: 1
  • mathJax: false
  • echo-subscriptions-web-page-review: true
  • echo-subscriptions-email-page-review: false
  • ep_showtoplink: false
  • ep_bulkdelorgs: false
  • ep_bulkdelcourses: true
  • ep_showdyk: true
  • echo-subscriptions-web-education-program: true
  • echo-subscriptions-email-education-program: false
  • echo-notify-show-link: true
  • echo-show-alert: true
  • echo-email-frequency: 0
  • echo-email-format: "html"
  • echo-subscriptions-email-system: true
  • echo-subscriptions-web-system: true
  • echo-subscriptions-email-user-rights: true
  • echo-subscriptions-web-user-rights: true
  • echo-subscriptions-email-other: false
  • echo-subscriptions-web-other: true
  • echo-subscriptions-email-edit-user-talk: 1
  • echo-subscriptions-web-edit-user-talk: true
  • echo-subscriptions-email-reverted: false
  • echo-subscriptions-web-reverted: true
  • echo-subscriptions-email-article-linked: false
  • echo-subscriptions-web-article-linked: false
  • echo-subscriptions-email-mention: false
  • echo-subscriptions-web-mention: true
  • echo-subscriptions-web-edit-thank: true
  • echo-subscriptions-email-edit-thank: false
  • echo-subscriptions-web-flow-discussion: true
  • echo-subscriptions-email-flow-discussion: false
  • gettingstarted-task-toolbar-show-intro: true
  • uls-preferences: ""
  • language: "en"
  • variant-gan: "gan"
  • variant-iu: "iu"
  • variant-kk: "kk"
  • variant-ku: "ku"
  • variant-shi: "shi"
  • variant-sr: "sr"
  • variant-tg: "tg"
  • variant-uz: "uz"
  • variant-zh: "zh"
  • searchNs0: true
  • searchNs1: false
  • searchNs2: "1"
  • searchNs3: false
  • searchNs4: "1"
  • searchNs5: false
  • searchNs6: "1"
  • searchNs7: false
  • searchNs8: "1"
  • searchNs9: false
  • searchNs10: "1"
  • searchNs11: false
  • searchNs12: "1"
  • searchNs13: false
  • searchNs14: "1"
  • searchNs15: false
  • searchNs100: false
  • searchNs101: false
  • searchNs108: false
  • searchNs109: false
  • searchNs118: false
  • searchNs119: false
  • searchNs446: false
  • searchNs447: false
  • searchNs710: false
  • searchNs711: false
  • searchNs828: false
  • searchNs829: false
  • gadget-teahouse: ""
  • gadget-ReferenceTooltips: 1
  • gadget-DRN-wizard: 1
  • gadget-charinsert: 1
  • gadget-refToolbar: 1
  • gadget-mySandbox: 1
  • betafeatures-vector-compact-personal-bar: "0"
  • cirrussearch-default: "0"
  • pagetriage-lastuse: timestamp
  • popups: "0"
  • timecorrection: "ZoneInfo|60|Europe/London"
  • uls-compact-links: "0"
  • usecodeeditor: "1"
  • userjs-arbitraryKeyName: arbitrary value
  • watchlisttoken: token

Errores posibles

Además de el material habitual :

Código Información
notloggedin Anonymous users cannot change preferences
nochanges No se solicitó ningún cambio.

Historial de parámetros

  • 1.21: Introducido resetkinds

Notas adicionales

  • This API is primarily intended for changing options which are registered by MediaWiki core or extensions and available on Special:Preferences.
  • You can also use the API to set arbitrary user options that can be used by user scripts or external editors. These options must begin with the prefix userjs-.
  • There are currently no limit on the number of user options you can set at once. You can store data within a user option by encoding it as a JSON string.
  • Providing only names of options without equal sign results in resetting them (e.g. hideminor|skin). In the case of an arbitrary userjs- key/value pair, the resetting results in its deletion.
  • The change parameter cannot be used to set a value which contains a pipe character |, as it is used by the API to separate options. If you need to set such a value (e.g., a user signature) use an optionname & optionvalue pair.
  • The following limits apply to all user options:
    • The byte length of the key must be <= 255.
    • The byte length of the value must be <= 65535.
    • The key must consist only of ASCII letters, numbers, hyphens and underscores (a-z, A-Z, 0-9, _, -).

Ve también