User:Patrick Nagel/Login with snoopy post-1.15.3

From mediawiki.org

API:Login describes how to log in to a Wiki using the API. This was easy to do with Snoopy in the days before MediaWiki 1.15.3 - I used the code from meta:MediaWiki_Bulk_Page_Creator. Since this is no longer possible (for a good reason: security), here is the code I use now:

<?php
if (empty($argv[1])) {
 print("Specify the part of the URL after 'https://my.private.wiki/wiki/index.php/' as argument.\n");
 exit;
}

include "Snoopy-1.2.4/Snoopy.class.php";
$snoopy = new Snoopy;
$snoopy->curl_path="/usr/bin/curl";
$wikiroot = "https://my.private.wiki/wiki";
$api_url = $wikiroot . "/api.php";

# Login via api.php
$login_vars['action'] = "login";
$login_vars['lgname'] = "botusername";
$login_vars['lgpassword'] = "botpassword";
$login_vars['format'] = "php";
## First part
$snoopy->submit($api_url,$login_vars);
$response = unserialize($snoopy->results);
$login_vars['lgtoken'] = $response[login][token];
$snoopy->cookies["wiki_session"] = $response[login][sessionid]; // You may have to change 'wiki_session' to something else on your Wiki
## Second part, now that we have the token
$snoopy->submit($api_url,$login_vars);

# Fetch the page
$login_vars['action'] = "render";
$urlpart=$argv[1];
$snoopy->submit($wikiroot . "/index.php?title=" . $urlpart, $login_vars);
print($snoopy->results);

(the above script fetches a page from a private Wiki, with action=render - but after having logged in, you can do whatever you want, it's not limited to fetching pages)

Note that I'm not very experienced with neither Snoopy, nor the MediaWiki API, yet, so it may well be that there is a better solution. Feel free to point out improvements on the discussion page! --Patrick Nagel 03:22, 30 June 2010 (UTC)

An anonymous user points out on the discussion page, that the script can be made independent of the cookie name. --Patrick Nagel 02:36, 23 July 2010 (UTC)