Szerkesztő:Tgr/api.js

A Wikipédiából, a szabad enciklopédiából

Megjegyzés: közzététel után frissítened kell a böngésződ gyorsítótárát, hogy lásd a változásokat.

  • Firefox / Safari: tartsd lenyomva a Shift gombot és kattints a Frissítés gombra a címsorban, vagy használd a Ctrl–F5 vagy Ctrl–R (Macen ⌘–R) billentyűkombinációt
  • Google Chrome: használd a Ctrl–Shift–R (Macen ⌘–Shift–R) billentyűkombinációt
  • Internet Explorer / Edge: tartsd nyomva a Ctrl-t, és kattints a Frissítés gombra, vagy nyomj Ctrl–F5-öt
  • Opera: Nyomj Ctrl–F5-öt
/**
 * Initiate an AJAX call
 *
 * @param String url -- URL to be called (without query parameters in case of GET request)
 * @param Object parameters -- GET or POST parameters in {param: 'value', ...} format
 * @param Function|Object callback -- callback function, or a DOM node to write results to
 * @param String method -- HTTP method, defaults to GET
 *
 * All parameters except thr URL are optional. Callback can be a DOM node, in which case its innerHTML 
 * (in the case of an <input> element, its value) will be replaced with the response text; or it can be 
 * a function in the form of callback(response, parameters, request) to be called when the request is
 * finished. The first parameter will be the response text, the second the parameter object passed to 
 * the call_ajax function, the third the full XMLHttpRequest object.
 */
function call_ajax(url, parameters, callback, method) {
  if (!method) method = "GET";
  var post_data = null;
  query = [];
  for (var p in parameters) {
    query.push(encodeURIComponent(p) + '=' + encodeURIComponent(parameters[p]));
  }
  if (method == "POST") {
    post_data = query.join('&');
  } else {
    url += '?' + query.join('&');
  }
  
  var request = sajax_init_object();
  if (!request) throw "AJAX disabled!";
  request.open(method, url, true);
  if (method == "POST") {
    request.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  }
  
  request.onreadystatechange = function() {
    if (request.readyState != 4) return;
    var response = request.responseText;
    if (typeof callback == 'function') {
      callback(response, parameters, request);
    } else if (typeof callback == 'object' && callback.tagName && response.status == 200) {
      if (callback.tagName == 'INPUT') {
        callback.value = response;
      } else {
        callback.innerHTML = response;
      }
    }
  }
  request.send(post_data);
  delete request;
}

/**
 * Call the MediaWiki API.
 * 
 * See http://www.mediawiki.org/wiki/API for more information.
 *
 * @param Object parameters -- parameters of the API call, in {param: 'value', ...} format
 * @param Function callback -- callback function
 * @param String method -- HTTP method, defaults to GET
 *
 * The callback function will be called in the format callback(response, parameters, request). The first parameter will 
 * be the response text, the second the parameter object passed to the call_ajax function, the third the full 
 * XMLHttpRequest object.
 * 
 * The format parameter of the API call defaults to 'json'; if it is left unchanged, the first 
 * parameter to the callback will be the parsed JSON object instead of the raw string.
 */
function call_api(parameters, callback, method) {
  if (false) throw "MediaWiki API is disabled!";
  parameters.format = parameters.format || 'json';
  var path = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php';
  
  var wrapper = null;
  if (callback) {
    wrapper = function(response, parameters, request) {
      if (parameters.format == 'json') {
        response = eval('('+response+')');
      }
      callback(response, parameters, request);
    };
  }
  
  call_ajax(path, parameters, wrapper, method);
}

/**
 * Change the text of a page through the MediaWiki edit API.
 *
 * This is a convenience function for simple text changes that handles the extra API call required to 
 * get an edit token.
 *
 * @param Object parameters -- parameters to the edit API call in {param: 'value', ...} format (not all parameters work or make sense)
 * @param String|Function text -- the new text or a callback function that returns it
 * @param Function|Object callback -- callback function or a DOM node to display the status
 *
 * The token, basetimestamp and starttimestamp parameters will be set automatically. The action will be 'edit' and cannot be changed.
 * format defaults to 'json'. Some of the more useful parameters: 
 *   title:    name of the page to edit (required; will be created if it does not exist)
 *   section:  number of the section to change (0 for the lead, 'new' for adding a new section)
 *   summary:  edit summary
 * See http://www.mediawiki.org/wiki/API:Edit_-_Create%26Edit_pages#Parameters for all possible parameters.
 *
 * If text parameter is a string, the text of the page (or the text of the section if specified) will be replaced by it.
 * If it is a function, it will be called with the old text of the page/section as a parameter, and the resulting string will be used.
 *
 * If the callback parameter is a function, it is used the same way as with call_api().
 * If the callback parameter is a DOM node, it will get an 'api-working' class  when call_api() is called.
 * When the call is finished, the class will change to 'api-success' or 'api-error' depending on the results.
 * In the latter case, the node will get an additional 'api-error-<errorcode>' class, and its title will be
 * changed to the description of the error.
 * Success/error display only works with the JSON format; if the format parameter passed to the MediaWiki API 
 * was not 'json', then instead of the above, the class will change to 'api-finished' irrespective of the results.
 *
 * 
 */
function call_edit_api(parameters, text, callback) {
  var get_parameters = {
    action:     'query',
    format:     'json',
    titles:      parameters.title,
    intoken:    'edit',
    prop:       'info'
  };
  if (parameters.section && parameters.section != 'new') {
    get_parameters.rvsection = parameters.section;
  }
  if (typeof text == 'function') {
    get_parameters.prop   = 'info|revisions';
    get_parameters.rvprop = 'content';
  }

  if (typeof callback == 'object' && callback.tagName) {
    var statusNode = callback;
    statusNode.className = statusNode.className.replace(/\bapi-(working|finished|success|error|error-\w+)\b/g, '');
    statusNode.className = statusNode.className.replace(/\s+$/, '');
    statusNode.className += ' api-working';
    var callback = function (response) {
      if (parameters.format == 'json') {
        if (response.error) {
          statusNode.className = statusNode.className.replace(/\bapi-working\b/, 'api-error api-error-'+response.error.code);
          statusNode.title = response.error.info;
        } else {
          statusNode.className = statusNode.className.replace(/\bapi-working\b/, 'api-success');
        }
      } else {
        statusNode.className = statusNode.className.replace(/\bapi-working\b/, 'api-finished');
      }
    }
  }
  
  var wrapper = function (response, get_parameters, request) {
    if (response.error) {
      if (callback) {
        callback(response, parameters, request);
      }
      return;
    }
  
    for (var i in response.query.pages) {
      var page = response.query.pages[i];
      break;
    }
    parameters.action         = 'edit';
    parameters.basetimestamp  = page.touched;
    parameters.starttimestamp = page.starttimestamp;
    parameters.token          = page.edittoken;
    if (typeof text == 'function') {
      var oldtext = page.revisions[0]['*'];
      parameters.text           = text(oldtext);
    } else {
      parameters.text           = text || parameters.text;
    }
    
    call_api(parameters, callback, "POST");
  }
  
  call_api(get_parameters, wrapper, "GET");
}