User:X!/Main Page bot Source

The following is automatically generated by X!'s adminbot.

Bot Hierarchy

  • bot.php
  • bot2.php
  • classes.php
  • adminpass.php
  • nickpass.php
  • Images/
  • tmp/

Source code

bot.php
<?php

/* Copyright (C) 2008  Soxred93 - http://en.wikipedia.org/wiki/User:X!

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

include( "./functions.php" );


initialize();


checkEnable();


postSource();


purgeCache();


deleteImages();


process();

?>
bot2.php
<?php

/* Copyright (C) 2008  Soxred93 - http://en.wikipedia.org/wiki/User:X!

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

include( "./functions.php" );


initialize();


checkEnable();


purgeCache();


//Get to the RC feed
while(1) {
	$feed = fsockopen('irc.wikimedia.org',6667,$ircerrno,$ircerrstr,30);
	if (!$feed) {
		sleep(10);
		$feed = fsockopen('irc.wikimedia.org',6667,$ircerrno,$ircerrstr,30);
		if (!$feed) die($feederrstr.' ('.$feederrno.')');
	} 	
	$feedchannel = '#en.wikipedia';			
	fwrite($feed,'USER SoxAdminBot "1" "1" :SoxBot Wikipedia Bot.'."\n");
	fwrite($feed,'NICK SoxAdminBot'."\n");
	while (!feof($feed)) {
		$rawline = fgets($feed,1024);
		$line = str_replace(array("\n","\r","\002"),'',$rawline);
		$line = preg_replace('/\003(\d\d?(,\d\d?)?)?/','',$line);
		//echo 'FEED: '.$line."\n";
		if (!$line) { fclose($feed); break; }
		$linea= explode(' ',$line,4);

		if (strtolower($linea[0]) == 'ping') {
			fwrite($feed,'PONG '.$linea[1]."\n");
		} elseif (($linea[1] == '376') or ($linea[1] == '422')) {
			fwrite($feed,'JOIN '.$feedchannel."\n");
		} elseif ((strtolower($linea[1]) == 'privmsg') and (strtolower($linea[2]) == strtolower($feedchannel))) {
			$message = substr($linea[3],1);
			if (preg_match('/^\[\[((Talk|User|Wikipedia|Image|File|MediaWiki|Template|Help|Category|Portal|Special)(( |_)talk)?:)?([^\x5d]*)\]\] (\S*) (http:\/\/en\.wikipedia\.org\/w\/index\.php\?title=[^&]*&diff=(\d*)&oldid=(\d*)|http:\/\/en\.wikipedia\.org\/wiki\/\S+)? \* ([^*]*) \* (\(([^)]*)\))? (.*)$/S',$message,$m)) {
				$messagereceived = microtime(1);
				$change['namespace'] = $m[1];
				$change['title'] = $m[5];
				$change['flags'] = $m[6];
				$change['url'] = $m[7];
				$change['revid'] = $m[8];
				$change['old_revid'] = $m[9];
				$change['user'] = $m[10];
				$change['length'] = $m[12];
				$change['comment'] = $m[13];
				
				//echo $change['namespace'];
				if ($change['namespace'] == 'Wikipedia:' || $change['namespace'] == 'Template:') {
					echo $change['title']."\n";
					if ($change['title'] == 'Today\'s featured article/'.date('F j, Y') || 
						$change['title'] == 'Did you know' || 
						$change['title'] == 'In the news' || 
						$change['title'] == 'Selected anniversaries'.date('F j') || 
						$change['title'] == 'POTD protected/'.date('Y-m-d') ) {
						process($change['namespace'].$change['title']);
					}
					
				}
			}
		}
	}
}

?>
functions.php
<?php

include('./classes.php');

//Setup the classes
$http 	= new http;
$wpapi  = new wikipediaapi;
$wpq    = new wikipediaquery;
$wpi    = new wikipediaindex;
$user   = 'X!';

function initialize() {
	global $wpapi, $user;
	include( './adminpass.php' );//Password

	echo "Logging in...\n";

	$wpapi->login( $user,$pass );//Login
	unset( $pass ); //Security reasons
	
	return $user;
}

function checkEnable() {
	global $wpq, $user;
	echo "\nChecking if bot is enabled...\n";
	$run = $wpq->getpage( 'User:'.$user.'/Run' );
	if ( !preg_match( '/(yes|enable|true)/iS',$run ) ) {
		irc("!admin@commons - X!'s adminbot is disabled. Please make sure all images on the Main Page are protected.", '#wikimedia-commons');
		irc("!admin - X!'s adminbot is disabled. Please make sure all images on the Main Page are protected.", '#wikipedia-en-admins');
		irc("!admin - X!'s adminbot is disabled. Please make sure all images on the Main Page are protected.", '#wikipedia-en-alerts');
		die( "Bot Disabled\n" );
	}
	unset( $run );
	return true;
	
}

function postSource() {
	//Post the source code
	global $wpi, $user;
	echo "\nPosting source code...\n";
	$wpi->forcepost('User:'.$user.'/Main Page bot Source',
                'The following is automatically generated by [[User:'.$user.'|'.$user."]]'s adminbot.\n\n" .
                "==Bot Hierarchy==\n*bot.php\n*bot2.php\n*classes.php\n*adminpass.php\n*nickpass.php\n*Images/\n*tmp/\n\n" .
                "==Source code==\n" .
                "{{collapse top|bot.php}}\n<pre>".htmlentities(file_get_contents('./bot.php'))."</pre>\n{{collapse bottom}}\n" .
                "{{collapse top|bot2.php}}\n<pre>".htmlentities(file_get_contents('./bot2.php'))."</pre>\n{{collapse bottom}}\n" .
                "{{collapse top|functions.php}}\n<pre>".htmlentities(file_get_contents('./functions.php'))."</pre>\n{{collapse bottom}}\n" .
                "{{collapse top|classes.php}}\n<pre>".htmlentities(file_get_contents('./classes.php'))."</pre>\n{{collapse bottom}}" ,
                'Automated source upload.');
	//die();
}

function purgeCache() {
	global $http;
	echo "\nPurging cache...\n";
	$check = $http->get( 'http://en.wikipedia.org/w/api.php?action=purge&titles=Main_Page&format=php' );
	$check = unserialize( $check );
	print_r($check);
	if ( !isset( $check['purge'][0]['purged'] ) ) { 
		die( "An error occured while logging in.\n" ); 
	}
}

function deleteImages() {
	global $http, $wpapi, $wpq, $wpi;
	echo "\nFinding images not used anymore...\n";
	$currlist = file_get_contents('./images.txt');
	$currlist = explode("\n", $currlist);
	sleep(3);
	if ($currlist[0] != '') { 
		echo "\nImages are: ".implode(', ', $currlist)."\n";
		foreach( $currlist as $image ) {
			if ($image == '') { continue; }
			$titles = array();
			$continue = null;
			$iu = imageusage($image,$continue);
 			foreach ($iu as $data) { $titles[] = $data['title']; }
			while (isset($iu[4999])) {
				$iu = imageusage($image,$continue);
				foreach ($iu as $data) { $titles[] = $data['title']; }
			}
			print_r($titles);
			sleep(3);
			if (!in_array('Main Page', $titles) && !in_array('Wikipedia:Main Page/Tomorrow', $titles)) {
				if ( $wpq->getpageid( $image ) === -1 ) { 
					echo "\nAlready deleted...\n"; 
					remtext($image);
					continue;
				}
				$list = getTemplates($image);
				print_r($list);
				if (in_array('Template:C-uploaded', $list)) {
					echo "\nDeleting $image...\n";
					$wpi->delete($image, '{{Putt9567}} - BOT EDIT: See [[Wikipedia:Bots/Requests for approval/SoxBot 11]]: No longer on Main Page');
					unlink('./Images/'.$image);//Remove the local copy, to save space
					sleep(3);
					
					if (delrevs($image) === true) {
						echo "\nRestoring $image...\n";
						undelete($image);
					}
					remtext($image);
				}
			}
		}
	}
}

function remtext($image) {
	$file = file('./images.txt');
	echo "Removing $image from images.txt.\n";
	print_r($file);
	foreach ($file as $key => $value) {
		if ($value == $image) {
			unset($file[$key]);
		}
	}
	print_r($file);
	foreach ($file as $line) {
		file_put_contents('./images.txt', $line."\n");
	}
}

function process($title = 'Wikipedia:Main Page/Tomorrow') {
	global $wpq, $wpapi, $wpi, $http;
	
	$list = exclude(getImages( $title ));
	//print_r($list);
	foreach( $list as $image ) {
		$image = "Image:".$image;

	
		if ( $wpq->getpageid( $image ) !== -1 ) { echo "\nExists locally...\n";continue; }
		if ( checkEdit( $image ) === false ) { echo "\nEdited in last 24 hours...\n";continue; }
		if ( fullprotect( $image ) === true ) { echo "\nProtected locally on Commons...\n";continue; }
	
		echo "\nGetting url of $image...\n";
		$url = getUrl( $image );
		echo "\nDownloading $image...\n";
		downloadImage( $url, './Images/'.$image );
	
		$text = $http->get( 'http://commons.wikimedia.org/w/api.php?action=query&prop=revisions&format=php&titles='.urlencode($image).'&rvprop=content' );
		$text = unserialize( $text );
		$text = $text['query']['pages'];
	
		foreach ($text as $key => $data) {
			$text2 = $data['revisions'][0]['*'];
		}
	
		$text2 = str_ireplace("[[", "[[commons:", $text2);//Replace wikilinks with interwiki links
	
		$text = "{{Putt9567}}\n<includeonly>BOT EDIT: See [[Wikipedia:Bots/Requests for approval/SoxBot 11]].</includeonly>\n{{C-uploaded}}\n\n".$text2;
	
		echo "\nUploading $image...\n";
		$image2 = explode(':', $image);
		if ( in_array( $image, file( './images.txt' ) ) ) { echo "\nHmm, why isn't it uploaded yet?\n"; }
		$wpi->upload($image2[1], './Images/'.$image, $text);
		$wpi->protect($image, '{{Putt9567}} - BOT EDIT: See [[Wikipedia:Bots/Requests for approval/SoxBot 11]]. Protecting image on Main Page.');
	
	
		file_put_contents('./images.txt', file_get_contents('./images.txt').$image."\n");//Add it to the list of protected images
		sleep(3);
	}
}

//Checks to see if it was edited in the last 10 minutes
function checkEdit($image) {
echo "\nChecking if $image was edited in the last 24 hours...\n";
	if (lastedit($image) > strtotime('-24 hours')) {
		irc("!admin@commons - Please protect [[$image]], as it is on the Main Page.", '#wikimedia-commons');
		irc("!admin - Please upload [[$image]] from Commons, as it is on the Main Page.", '#wikipedia-en-admins');
		irc("!admin - Please upload [[$image]] from Commons, as it is on the Main Page.", '#wikipedia-en-alerts');
		
		return false;
	}
	else {
		return true;
	}
}

function lastEdit($page) {
echo "\nFinding last edit to $page...\n";
	//Returns the timestamp of the last edit to $page
	global $http, $wpapi, $wpq;
	$x = $http->get('http://commons.wikimedia.org/w/api.php?action=query&prop=revisions&titles='.urlencode($page).'&rvlimit=1&rvprop=timestamp&format=php');
	$x = unserialize($x);
	$timestamp = $x['query']['pages'][$wpq->getpageid($page)]['revisions'][0]['timestamp'];
	return strtotime($timestamp);
}

function downloadImage($url,$local) {
	//Downloads the image to upload
	$out = fopen($local, 'w'); 
	$ch = curl_init();
           
    curl_setopt($ch, CURLOPT_FILE, $out);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
               
    curl_exec($ch);
   
    curl_close($ch); 
}

function getUrl($image) {
	//Returns the url of the Commons image
	global $http, $wpapi, $wpq;
	$x = $http->get('http://commons.wikimedia.org/w/api.php?action=query&titles='.urlencode($image).'&prop=imageinfo&iiprop=url&iilimit=1&format=php');
	$x = unserialize($x);
	
	$file = $x['query']['pages'];
	foreach ($file as $img) {
		$file = $img['imageinfo'][0]['url'];
	}
	
	if (!$file) {
		die('Image not found');
	}
	return $file;
}

function imageusage($image, &$continue = null) {
	//Returns an array with all pages that use $image
	global $http, $wpapi, $wpq;
	echo "Getting image usage...\n";
	if ($continue != null) {
		$append = '&iucontinue='.urlencode($continue);
	} else {
		$append = '';
	}
	$x = $http->get($wpapi->apiurl.'?action=query&list=imageusage&iutitle='.urlencode($image).'&format=php&iulimit=5000'.$append);
	$x = unserialize($x);
	$continue = $x['query-continue']['imageusage']['iucontinue'];
	return $x['query']['imageusage'];
}

function getImages($page) {
	//Returns an array with all the images on $page
	global $http, $wpapi, $wpq;
	$x = $http->get($wpapi->apiurl.'?action=query&titles='.urlencode($page).'&prop=images&imlimit=500&format=php');
	$x = unserialize($x);
	$id = $wpq->getpageid($page);
	foreach ($x['query']['pages'][$id]['images'] as $links) {
		$images[] = str_replace('Image:','',$links['title']);
	}
	return $images;
}

function getTemplates($page) {
	//Returns an array with all the templates on $page
	echo "Getting templates...\n";
	global $http, $wpapi, $wpq;
	$x = $http->get($wpapi->apiurl.'?action=query&titles='.urlencode($page).'&prop=templates&tllimit=500&format=php');
	$x = unserialize($x);
	foreach ($x['query']['pages'][$wpq->getpageid($page)]['templates'] as $links) {
		$templates[] = $links['title'];
	}
	return $templates;
}

function irc($message,$channel) {
	include('nickpass.php');
	$nick = 'SoxBot';
	$socket = fsockopen("irc.freenode.net", 6667, $en, $es, 30);
	if (!$socket) {
		echo 'Error: '.$es.' ('.$en.')'."\n";
		return false;
	}
	fwrite($socket, 'USER '.$nick.' "toolserver.org" "Main Page" :'.$nick."\n");
	fwrite($socket, 'NICK '.$nick."\n");
	fwrite($socket, 'PASS '.$nickpass."\n");
	
	while (!feof($socket)) {
		$data = str_replace(array("\r","\n"),'',fgets($socket,512));
		$darr = explode(' ',$data);
		if (strtolower($darr[0]) == 'ping') {
			fwrite($socket, 'PONG '.$darr[1]."\n");
		} elseif (($darr[1] == '376') or ($darr[1] == '422')) {
			fwrite($socket, 'JOIN '.$channel."\n");
		} elseif ((strtolower($darr[1]) == 'mode') and ((($darr[2]{0} == ':')?substr($darr[2],1):$darr[2]) == '+v') and (strtolower(($darr[3]{0} == ':')?substr($darr[3],1):$darr[3]) == strtolower($nick))) {
			fwrite($socket, 'PRIVMSG '.$channel.' :'.$message."\n");
			fwrite($socket, 'QUIT :No longer needed.'."\n");
			fclose($socket);
		}
	}
	return true;
}

function exclude($list) {
		//Returns $list excluding anything listed on the exclude list
		global $http, $wpapi, $wpq, $user;
		$x = $wpq->getpage('User:'.$user.'/Exclude List.js'); //Get the exclude list
		$exclude = explode(chr(10), $x);
		foreach ($exclude as $e) { //Parse it
			if (!preg_match('/^#/',$e)) {
				$exclude_list[] = $e;
			}
		}
		foreach ($list as $l) {
			$add = true;
			foreach ($exclude_list as $e) {
				if ($e == $l) {
					$add = false;
					break;
				}
			}
			if ($add) {
				$cleaned_list[] = $l;
			}
		}
		return $cleaned_list;
	}

function fullprotect($page) {
	//returns true if the page is full protected
	global $wpapi, $http, $wpq;
	$x = $http->get('http://commons.wikimedia.org/w/api.php?action=query&titles='.urlencode($page).'&prop=info&inprop=protection&format=php');
	$x = unserialize($x);
	if ($x['query']['pages'][$wpq->getpageid($page)]['protection'][0]['level'] == 'sysop') {
		return true;
	}
	else {
		return false;
	}	
}

function delrevs($page) {
	global $wpapi, $http, $wpq;
	$x = $http->get('http://en.wikipedia.org/w/api.php?action=query&list=deletedrevs&titles='.urlencode($page).'&format=php');
	$x = unserialize($x);
	if (count($x['query']['deletedrevs'][0]['revisions']) > 1) {
		return true;
	}
	else {
		return false;
	}	
}

function undelete($page) {
	global $wpapi, $http, $wpq, $user;
	$x = $http->get('http://en.wikipedia.org/w/api.php?action=query&list=deletedrevs&drprop=token|user&titles='.urlencode($page).'&format=php');
	$x = unserialize($x);
	$token = htmlspecialchars($x['query']['deletedrevs'][0]['token']);
	
	$post = array();
	
	$users = $x['query']['deletedrevs'][0]['revisions'];
	$timestamps = array();
	foreach($users as $rev) {
		echo $rev['user'];
		if ($rev['user'] != $user) {
			$timestamps[] = $rev['timestamp'];
		}
	}
	
	print_r($timestamps);
	
	$post['token'] = $token;
	$post['reason'] = '{{Putt9567}} - BOT EDIT: Restoring Wikipedia specific edits.';
	$post['timestamps'] = implode("|", $timestamps);
	
	$http->post('http://en.wikipedia.org/w/api.php?action=undelete&title='.urlencode($page).'&format=php',$post);
	
}

?>
classes.php
<?PHP
        class http {
                private $ch;
                private $uid;
                public $postfollowredirs;
                public $getfollowredirs;

                function data_encode ($data, $keyprefix = "", $keypostfix = "") {
                        assert( is_array($data) );
                        $vars=null;
                        foreach($data as $key=>$value) {
                                if(is_array($value)) $vars .= $this->data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
                                else $vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
                        }
                        return $vars;
                }

                function __construct () {
                        $this->ch = curl_init();
                        $this->uid = dechex(rand(0,99999999));
                        curl_setopt($this->ch,CURLOPT_COOKIEJAR,'./tmp/cookies.dat');
                        curl_setopt($this->ch,CURLOPT_COOKIEFILE,'./tmp/cookies.dat');
                        curl_setopt($this->ch,CURLOPT_MAXCONNECTS,100);
                        curl_setopt($this->ch,CURLOPT_CLOSEPOLICY,CURLCLOSEPOLICY_LEAST_RECENTLY_USED);
                        $this->postfollowredirs = 0;
                        $this->getfollowredirs = 1;
                }

                function post ($url,$data) {
//                      echo 'POST: '.$url."\n";
                        $time = microtime(1);
                        curl_setopt($this->ch,CURLOPT_URL,$url);
                        curl_setopt($this->ch,CURLOPT_COOKIEJAR,'./tmp/cookies.dat');
                        curl_setopt($this->ch,CURLOPT_COOKIEFILE,'./tmp/cookies.dat');
                        curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,$this->postfollowredirs);
                        curl_setopt($this->ch,CURLOPT_MAXREDIRS,10);
                        curl_setopt($this->ch,CURLOPT_HEADER,0);
                        curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,1);
                        curl_setopt($this->ch,CURLOPT_TIMEOUT,30);
                        curl_setopt($this->ch,CURLOPT_CONNECTTIMEOUT,10);
                        curl_setopt($this->ch,CURLOPT_POST,1);
//                      curl_setopt($this->ch,CURLOPT_POSTFIELDS, substr($this->data_encode($data), 0, -1) );
                        curl_setopt($this->ch,CURLOPT_POSTFIELDS, $data);
                        $data = curl_exec($this->ch);
                        //var_dump($data);
                        //echo 'POST: '.$url.' ('.(microtime(1) - $time).' s) ('.strlen($data)." b)\n";
                        return $data;
                }

                function get ($url) {
                        //echo 'GET: '.$url."\n";
                        $time = microtime(1);
                        curl_setopt($this->ch,CURLOPT_URL,$url);
                        curl_setopt($this->ch,CURLOPT_COOKIEJAR,'./tmp/cookies.dat');
                        curl_setopt($this->ch,CURLOPT_COOKIEFILE,'./tmp/cookies.dat');
                        curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,$this->getfollowredirs);
                        curl_setopt($this->ch,CURLOPT_MAXREDIRS,10);
                        curl_setopt($this->ch,CURLOPT_HEADER,0);
                        curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,1);
                        curl_setopt($this->ch,CURLOPT_TIMEOUT,30);
                        curl_setopt($this->ch,CURLOPT_CONNECTTIMEOUT,10);
                        curl_setopt($this->ch,CURLOPT_HTTPGET,1);
                        $data = curl_exec($this->ch);
                        //var_dump($data);
                        //echo 'GET: '.$url.' ('.(microtime(1) - $time).' s) ('.strlen($data)." b)\n";
                        return $data;
                }

                function __destruct () {
                        curl_close($this->ch);
                        //@unlink('/tmp/cluewikibot.cookies.dat');
                }
        }

        class wikipediaquery {
                private $http;
                private $api;
                public $queryurl = 'http://en.wikipedia.org/w/query.php'; //Obsolete, but kept for compatibility purposes.

                function __construct () {
                        global $__wp__http;
                        if (!isset($__wp__http)) {
                                $__wp__http = new http;
                        }
                        $this->http = &$__wp__http;
                        $this->api = new wikipediaapi;
                }
                
                private function checkurl() {
                        $this->api->apiurl = str_replace('query.php','api.php',$this->queryurl);
                }
                
                function getpage ($page) {
                        $this->checkurl();
//                      $ret = unserialize($this->http->get($this->queryurl.'?what=content&format=php&titles='.urlencode($page)));
//                      foreach ($ret['pages'] as $page) {
//                              return $page['content']['*'];
//                      }
                        $ret = $this->api->revisions($page,1,'older',true,null,true,false,false,false);
                        return $ret[0]['*'];
                }

                function getpageid ($page) {
                        $this->checkurl();
//                      $ret = unserialize($this->http->get($this->queryurl.'?what=content&format=php&titles='.urlencode($page)));
//                      foreach ($ret['pages'] as $page) {
//                              return $page['id'];
//                      }
                        $ret = $this->api->revisions($page,1,'older',false,null,true,false,false,false);
                        return $ret['pageid'];
                        
                }

                function contribcount ($user) {
                        $this->checkurl();
//                      $ret = unserialize($this->http->get($this->queryurl.'?what=contribcounter&format=php&titles=User:'.urlencode($user)));
//                      foreach ($ret['pages'] as $page) {
//                              return $page['contribcounter']['count'];
//                      }
                        $ret = $this->api->users($user,1,null,true);
                        if ($ret !== false) return $ret[0]['editcount'];
                        return false;
                }
        }

        class wikipediaapi {
                private $http;
                public $apiurl = 'http://en.wikipedia.org/w/api.php';

                function __construct () {
                        global $__wp__http;
                        if (!isset($__wp__http)) {
                                $__wp__http = new http;
                        }
                        $this->http = &$__wp__http;
                }

                function login ($user,$pass) {
                        $data = $this->http->post($this->apiurl.'?action=login&format=php',array('lgname' => $user, 'lgpassword' => $pass));
                        print_r(unserialize($data));
//                      if ($data) echo $data."\n\n";
                }

                function getedittoken () {
                        $x = $this->http->get($this->apiurl.'?action=query&format=php&prop=info&intoken=edit&titles=Main%20Page');
                        $x = unserialize($x);
                        foreach ($x['query']['pages'] as $y) {
                                return $y['edittoken'];
                        }
                }

                function recentchanges ($count = 10,$namespace = null,$dir = 'older',$ts = null) {
                        $append = '';
                        if ($ts !== null) { $append .= '&rcstart='.urlencode($ts); }
                        $append .= '&rcdir='.urlencode($dir);
                        if ($namespace !== null) { $append .= '&rcnamespace='.urlencode($namespace); }
                        $x = $this->http->get($this->apiurl.'?action=query&list=recentchanges&rcprop=user|comment|flags|timestamp|title|ids|sizes&format=php&rclimit='.$count.$append);
                        $x = unserialize($x);
                        return $x['query']['recentchanges'];
                }

                function search ($search,$limit = 10,$offset = 0,$namespace = 0,$what = 'text',$redirs = false) {
                        $append = '';
                        if ($limit != null) $append .= '&srlimit='.urlencode($limit);
                        if ($offset != null) $append .= '&sroffset='.urlencode($offset);
                        if ($namespace != null) $append .= '&srnamespace='.urlencode($namespace);
                        if ($what != null) $append .= '&srwhat='.urlencode($what);
                        if ($redirs == true) $append .= '&srredirects=1';
                        else $append .= '&srredirects=0';
                        $x = $this->http->get($this->apiurl.'?action=query&list=search&format=php&srsearch='.urlencode($search).$append);
                        $x = unserialize($x);
                        return $x['query']['search'];
                }

                function logs ($user = null,$title = null,$limit = 50,$type = null,$start = null,$end = null,$dir = 'older') {
                        $append = '';
                        if ($user != null) $append.= '&leuser='.urlencode($user);
                        if ($title != null) $append.= '&letitle='.urlencode($title);
                        if ($limit != null) $append.= '&lelimit='.urlencode($limit);
                        if ($type != null) $append.= '&letype='.urlencode($type);
                        if ($start != null) $append.= '&lestart='.urlencode($start);
                        if ($end != null) $append.= '&leend='.urlencode($end);
                        if ($dir != null) $append.= '&ledir='.urlencode($dir);
                        $x = $this->http->get($this->apiurl.'?action=query&format=php&list=logevents&leprop=ids|title|type|user|timestamp|comment|details'.$append);
                        $x = unserialize($x);
                        return $x['query']['logevents'];
                }


                function usercontribs ($user,$count = 50,&$continue = null,$dir = 'older') {
                        if ($continue != null) {
                                $append = '&ucstart='.urlencode($continue);
                        } else {
                                $append = '';
                        }
                        $x = $this->http->get($this->apiurl.'?action=query&format=php&list=usercontribs&ucuser='.urlencode($user).'&uclimit='.urlencode($count).'&ucdir='.urlencode($dir).$append);
                        $x = unserialize($x);
                        $continue = $x['query-continue']['usercontribs']['ucstart'];
                        return $x['query']['usercontribs'];
                }

                function revisions ($page,$count = 1,$dir = 'older',$content = false,$revid = null,$wait = true,$getrbtok = false,$dieonerror = true,$redirects = false) {
                        $x = $this->http->get($this->apiurl.'?action=query&prop=revisions&titles='.urlencode($page).'&rvlimit='.urlencode($count).'&rvprop=timestamp|ids|user|comment'.(($content)?'|content':'').'&format=php&meta=userinfo&rvdir='.urlencode($dir).(($revid !== null)?'&rvstartid='.urlencode($revid):'').(($getrbtok == true)?'&rvtoken=rollback':'').(($redirects == true)?'&redirects':''));
                        $x = unserialize($x);
                        if ($revid !== null) {
                                $found = false;
                                if (!isset($x['query']['pages']) or !is_array($x['query']['pages'])) {
                                        if ($dieonerror == true) die('No such page.'."\n");
                                        else return false;
                                }
                                foreach ($x['query']['pages'] as $data) {
                                        if (!isset($data['revisions']) or !is_array($data['revisions'])) {
                                                if ($dieonerror == true) die('No such page.'."\n");
                                                else return false;
                                        }
                                        foreach ($data['revisions'] as $data2) if ($data2['revid'] == $revid) $found = true;
                                        unset($data,$data2);
                                        break;
                                }

                                if ($found == false) {
                                        if ($wait == true) {
                                                sleep(1);
                                                return $this->revisions($page,$count,$dir,$content,$revid,false,$getrbtok,$dieonerror);
                                        } else {
                                                if ($dieonerror == true) die('Revision error.'."\n");
                                        }
                                }
                        }
                        foreach ($x['query']['pages'] as $key => $data) {
                                $data['revisions']['ns'] = $data['ns'];
                                $data['revisions']['title'] = $data['title'];
                                $data['revisions']['currentuser'] = $x['query']['userinfo']['name'];
//                              $data['revisions']['currentuser'] = $x['query']['userinfo']['currentuser']['name'];
                                $data['revisions']['continue'] = $x['query-continue']['revisions']['rvstartid'];
                                $data['revisions']['pageid'] = $key;
                                return $data['revisions'];
                        }
                }

                function users ($start = null,$limit = 1,$group = null,$reqirestart = false,&$continue = null) {
                        $append = '';
                        if ($start != null) $append .= '&aufrom='.urlencode($start);
                        if ($group != null) $append .= '&augroup='.urlencode($group);
                        $x = $this->http->get($this->apiurl.'?action=query&list=allusers&format=php&auprop=blockinfo|editcount|registration|groups&aulimit='.urlencode($limit).$append);
                        $x = unserialize($x);
                        $continue = $x['query-continue']['allusers']['aufrom'];
                        if (($requirestart == true) and ($x['query']['allusers'][0]['name'] != $start)) return false;
                        return $x['query']['allusers'];
                }


                function categorymembers ($category,$count = 500,&$continue = null) {
                        if ($continue != null) {
                                $append = '&cmcontinue='.urlencode($continue);
                        } else {
                                $append = '';
                        }
                        $category = 'Category:'.str_ireplace('category:','',$category);
                        $x = $this->http->get($this->apiurl.'?action=query&list=categorymembers&cmtitle='.urlencode($category).'&format=php&cmlimit='.$count.$append);
                        $x = unserialize($x);
                        $continue = $x['query-continue']['categorymembers']['cmcontinue'];
                        return $x['query']['categorymembers'];
                }

                function listcategories (&$start = null,$limit = 50,$dir = 'ascending',$prefix = null) {
                        $append = '';
                        if ($start != null) $append .= '&acfrom='.urlencode($start);
                        if ($limit != null) $append .= '&aclimit='.urlencode($limit);
                        if ($dir != null) $append .= '&acdir='.urlencode($dir);
                        if ($prefix != null) $append .= '&acprefix='.urlencode($prefix);

                        $x = $this->http->get($this->apiurl.'?action=query&list=allcategories&acprop=size&format=php'.$append);
                        $x = unserialize($x);

                        $start = $x['query-continue']['allcategories']['acfrom'];

                        return $x['query']['allcategories'];
                }

                function backlinks ($page,$count = 500,&$continue = null,$filter = null) {
                        if ($continue != null) {
                                $append = '&blcontinue='.urlencode($continue);
                        } else {
                                $append = '';
                        }
                        if ($filter != null) {
                                $append .= '&blfilterredir='.urlencode($filter);
                        }

                        $x = $this->http->get($this->apiurl.'?action=query&list=backlinks&bltitle='.urlencode($page).'&format=php&bllimit='.$count.$append);
                        $x = unserialize($x);
                        $continue = $x['query-continue']['backlinks']['blcontinue'];
                        return $x['query']['backlinks'];
                }

                function embeddedin ($page,$count = 500,&$continue = null) {
                        if ($continue != null) {
                                $append = '&eicontinue='.urlencode($continue);
                        } else {
                                $append = '';
                        }
                        $x = $this->http->get($this->apiurl.'?action=query&list=embeddedin&eititle='.urlencode($page).'&format=php&eilimit='.$count.$append);
                        $x = unserialize($x);
                        $continue = $x['query-continue']['embeddedin']['eicontinue'];
                        return $x['query']['embeddedin'];
                }

                function listprefix ($prefix,$namespace = 0,$count = 500,&$continue = null) {
                        $append = '&apnamespace='.urlencode($namespace);
                        if ($continue != null) {
                                $append .= '&apfrom='.urlencode($continue);
                        }
                        $x = $this->http->get($this->apiurl.'?action=query&list=allpages&apprefix='.urlencode($prefix).'&format=php&aplimit='.$count.$append);
                        $x = unserialize($x);
                        $continue = $x['query-continue']['allpages']['apfrom'];
                        return $x['query']['allpages'];
                }
        }

        class wikipediaindex {
                private $http;
                public $indexurl = 'http://en.wikipedia.org/w/index.php';
                private $postinterval = 0;
                private $lastpost;
                private $edittoken;

                function __construct () {
                        global $__wp__http;
                        if (!isset($__wp__http)) {
                                $__wp__http = new http;
                        }
                        $this->http = &$__wp__http;
                }

                function post ($page,$data,$summery = '',$minor = false,$rv = null,$bot = true) {
                        global $user;
                        global $maxlag;
                        global $irc;
                        global $irctechchannel;
                        global $run;
                        global $maxlagkeepgoing;

                        $wpq = new wikipediaquery; $wpq->queryurl = str_replace('index.php','query.php',$this->indexurl);
                        $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);

                        if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();
                        if ($rv == null) $rv = $wpapi->revisions($page,1,'older',true);
                        if (!$rv[0]['*']) $rv[0]['*'] = $wpq->getpage($page);

                        //Fake the edit form.
                        $now = gmdate('YmdHis', time());
                        $token = htmlspecialchars($this->edittoken);
                        $tmp = date_parse($rv[0]['timestamp']);
                        $edittime = gmdate('YmdHis', gmmktime($tmp['hour'],$tmp['minute'],$tmp['second'],$tmp['month'],$tmp['day'],$tmp['year']));
                        $html = "<input type='hidden' value=\"{$now}\" name=\"wpStarttime\" />\n";
                        $html.= "<input type='hidden' value=\"{$edittime}\" name=\"wpEdittime\" />\n";
                        $html.= "<input type='hidden' value=\"{$token}\" name=\"wpEditToken\" />\n";
                        $html.= '<input name="wpAutoSummary" type="hidden" value="'.md5('').'" />'."\n";

                        if (preg_match('/'.preg_quote('{{nobots}}','/').'/iS',$rv[0]['*'])) { return false; }           /* Honor the bots flags */
                        if (preg_match('/'.preg_quote('{{bots|allow=none}}','/').'/iS',$rv[0]['*'])) { return false; }
                        if (preg_match('/'.preg_quote('{{bots|deny=all}}','/').'/iS',$rv[0]['*'])) { return false; }
                        if (preg_match('/'.preg_quote('{{bots|deny=','/').'(.*)'.preg_quote('}}','/').'/iS',$rv[0]['*'],$m)) { if (in_array(explode(',',$m[1]),$user)) { return false; } } /* /Honor the bots flags */
                        if (!preg_match('/'.preg_quote($user,'/').'/iS',$rv['currentuser'])) { return false; } /* We need to be logged in */
//                      if (preg_match('/'.preg_quote('You have new messages','/').'/iS',$rv[0]['*'])) { return false; } /* Check talk page */
                        if (!preg_match('/(yes|enable|true)/iS',((isset($run))?$run:$wpq->getpage('User:'.$user.'/Run')))) { return false; } /* Check /Run page */

                        $x = $this->forcepost($page,$data,$summery,$minor,$html,$maxlag,$maxlagkeepgoing,$bot); /* Go ahead and post. */
                        $this->lastpost = time();
                        return $x;
                }

                function forcepost ($page,$data,$summery = '',$minor = false,$edithtml = null,$maxlag = null,$mlkg = null,$bot = true) {
                        $post['wpSection'] = '';
                        $post['wpScrolltop'] = '';
                        if ($minor == true) { $post['wpMinoredit'] = 1; }
                        $post['wpTextbox1'] = $data;
                        $post['wpSummary'] = $summery;
                        if ($edithtml == null) {
                                $html = $this->http->get($this->indexurl.'?title='.urlencode($page).'&action=edit');
                        } else {
                                $html = $edithtml;
                        }
                        preg_match('|\<input type\=\\\'hidden\\\' value\=\"(.*)\" name\=\"wpStarttime\" /\>|U',$html,$m);
                        $post['wpStarttime'] = $m[1];
                        preg_match('|\<input type\=\\\'hidden\\\' value\=\"(.*)\" name\=\"wpEdittime\" /\>|U',$html,$m);
                        $post['wpEdittime'] = $m[1];
                        preg_match('|\<input type\=\\\'hidden\\\' value\=\"(.*)\" name\=\"wpEditToken\" /\>|U',$html,$m);
                        $post['wpEditToken'] = $m[1];
                        preg_match('|\<input name\=\"wpAutoSummary\" type\=\"hidden\" value\=\"(.*)\" /\>|U',$html,$m);
                        $post['wpAutoSummary'] = $m[1];
                        if ($maxlag != null) {
                                $x = $this->http->post($this->indexurl.'?title='.urlencode($page).'&action=submit&maxlag='.urlencode($maxlag).'&bot='.(($bot == true)?'1':'0'),$post);
                                if (preg_match('/Waiting for ([^ ]*): ([0-9.-]+) seconds lagged/S',$x,$lagged)) {
                                        global $irc;
                                        if (is_resource($irc)) {
                                                global $irctechchannel;
                                                foreach(explode(',',$irctechchannel) as $y) {
                                                        fwrite($irc,'PRIVMSG '.$y.' :'.$lagged[1].' is lagged out by '.$lagged[2].' seconds. ('.$lagged[0].')'."\n");
                                                }
                                        }
                                        sleep(10);
                                        if ($mlkg != true) { return false; }
                                        else { $x = $this->http->post($this->indexurl.'?title='.urlencode($page).'&action=submit&bot='.(($bot == true)?'1':'0'),$post); }
                                }
                                return $x;
                        } else {
                                return $this->http->post($this->indexurl.'?title='.urlencode($page).'&action=submit&bot='.(($bot == true)?'1':'0'),$post);
                        }
                }

                function diff ($title,$oldid,$id,$wait = true) {
                        $deleted = '';
                        $added = '';

                        $html = $this->http->get($this->indexurl.'?title='.urlencode($title).'&action=render&diff='.urlencode($id).'&oldid='.urlencode($oldid).'&diffonly=1');

                        if (preg_match_all('/\&amp\;(oldid\=|undo=)(\d*)\\\'\>(Revision as of|undo)/USs', $html, $m, PREG_SET_ORDER)) {
                                //print_r($m);
                                if ((($oldid != $m[0][2]) and (is_numeric($oldid))) or (($id != $m[1][2]) and (is_numeric($id)))) {
                                        if ($wait == true) {
                                                sleep(1);
                                                return $this->diff($title,$oldid,$id,false);
                                        } else {
                                                die('Revision error.'."\n");
                                        }
                                }
                        }
                        
                        if (preg_match_all('/\<td class\=(\"|\\\')diff-addedline\1\>\<div\>(.*)\<\/div\>\<\/td\>/USs', $html, $m, PREG_SET_ORDER)) {
                                //print_r($m);
                                foreach ($m as $x) {
                                        $added .= htmlspecialchars_decode(strip_tags($x[2]))."\n";
                                }
                        }

                        if (preg_match_all('/\<td class\=(\"|\\\')diff-deletedline\1\>\<div\>(.*)\<\/div\>\<\/td\>/USs', $html, $m, PREG_SET_ORDER)) {
                                //print_r($m);
                                foreach ($m as $x) {
                                        $deleted .= htmlspecialchars_decode(strip_tags($x[2]))."\n";
                                }
                        }

                        //echo $added."\n".$deleted."\n";

                        if (preg_match('/action\=rollback\&amp\;from\=.*\&amp\;token\=(.*)\"/US', $html, $m)) {
                                $rbtoken = $m[1];
                                $rbtoken = urldecode($rbtoken);
//                              echo 'rbtoken: '.$rbtoken.' -- '; print_r($m); echo "\n\n";
                                return array($added,$deleted,$rbtoken);
                        }

                        return array($added,$deleted);
                }

                function rollback ($title,$user,$reason = null,$token = null,$bot = true) {
                        if (($token == null) or (!$token)) {
                                $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                                $token = $wpapi->revisions($title,1,'older',false,null,true,true);                           
                                if ($token[0]['user'] == $user) {
                                        echo 'Token: '; print_r($token); echo "\n\n";
                                        $token = $token[0]['rollbacktoken'];
                                } else {
                                        return false;
                                }
                        }
                        $x = $this->http->get($this->indexurl.'?title='.urlencode($title).'&action=rollback&from='.urlencode($user).'&token='.urlencode($token).(($reason != null)?'&summary='.urlencode($reason):'').'&bot='.(($bot == true)?'1':'0'));
                        echo 'Rollback return: '.$x."\n";
                        if (!preg_match('/action complete/iS',$x)) return false;
                        return $x;
                }

                function move ($old,$new,$reason) {
                        $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                        if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();

                        $token = htmlspecialchars($this->edittoken);

                        $post = array
                                (
                                        'wpOldTitle'    => $old,
                                        'wpNewTitle'    => $new,
                                        'wpReason'      => $reason,
                                        'wpWatch'       => '0',
                                        'wpEditToken'   => $token,
                                        'wpMove'        => 'Move page'
                                );
                        return $this->http->post($this->indexurl.'?title=Special:Movepage&action=submit',$post);
                }

                function upload ($page,$file,$desc) {
                        $post = array
                                (
                                        'wpUploadFile'          => '@'.$file,
                                        'wpSourceType'          => 'file',
                                        'wpDestFile'            => $page,
                                        'wpUploadDescription'   => $desc,
                                        'wpLicense'             => '',
                                        'wpWatchthis'           => '0',
                                        'wpIgnoreWarning'       => '1',
                                        'wpUpload'              => 'Upload file'
                                );
                        return $this->http->post($this->indexurl.'?title=Special:Upload&action=submit',$post);
                }

                function hasemail ($user) {
                        $tmp = $this->http->get($this->indexurl.'?title=Special:EmailUser&target='.urlencode($user));
                        if (stripos($tmp,"No e-mail address") !== false) return false;
                        return true;
                }
                
                function email ($user,$subject,$body) {
                        $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                        if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();

                        $post = array
                                (
                                        'wpSubject'     => $subject,
                                        'wpText'        => $body,
                                        'wpCCMe'        => 0,
                                        'wpSend'        => 'Send',
                                        'wpEditToken'   => $this->edittoken
                                );

                        return $this->http->post($this->indexurl.'?title=Special:EmailUser&target='.urlencode($user).'&action=submit',$post);
                }
                function delete ($page,$reason=null) {
                	$wpapi = new wikipediaapi; 
                    $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                    if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();
                    $token = htmlspecialchars($this->edittoken);
                    
					$post = array('title' => $page,'token' => $token,'reason' => $reason);

					$x = $this->http->post( $wpapi->apiurl.'?action=delete&format=php',$post );
					print_r( $x );
                }
 
                function protect ($page,$reason=null,$edit='sysop',$move='sysop',$editexpire='infinite',$moveexpire='infinite') {
                        $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                        if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();
 
                        $token = htmlspecialchars($this->edittoken);
 
                        $post = array
                                (
                                        'mwProtect-reason'      => $reason,
                                        'mwProtectWatch'        => '0',
                                        'mwProtect-cascade'     => '0',
                                        'mwProtect-expiry-edit' => $editexpire,
                                        'mwProtect-expiry-move' => $moveexpire,
                                        'mw-Protect-submit'     => 'Confirm',
                                        'wpEditToken'           => $token,
                                        'mwProtect-level-edit'  => $edit,
                                        'mwProtect-level-move'  => $move
                                );
                        return $this->http->post($this->indexurl.'?title='.urlencode($page).'&action=protect',$post);
                }
 
                function salt ($page,$reason=null,$create='sysop',$expire='infinite') {
                        $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                        if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();
 
                        $token = htmlspecialchars($this->edittoken);
 
                        $post = array
                                (
                                        'mwProtect-reason'      => $reason,
                                        'mwProtectWatch'        => '0',
                                        'mwProtect-expiry'      => $expire,
                                        'mw-Protect-submit'     => 'Confirm',
                                        'wpEditToken'           => $token,
                                        'mwProtect-level-create'  => $create
                                );
                        return $this->http->post($this->indexurl.'?title='.urlencode($page).'&action=protect',$post);
                }
 
                function block ($user,$expire='infinite',$reason='[[WP:Vandalism|Vandalism]]',$anon=1,$account=1,$autoblock=1,$emailban=0) {
                        $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                        if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();
 
                        $token = htmlspecialchars($this->edittoken);
 
                        $post = array
                                (
                                        'wpBlockAddress'       => $user,
                                        'wpBlockReason'         => $reason,
                                        'wpAnonOnly'            => $anon,
                                        'wpBlockOther'         => $expire,
                                        'wpBlock'              => 'Block',
                                        'wpEditToken'           => $token,
                                        'wpCreateAccount'      => $account,
                                        'wpEnableAutoblock'    => $autoblock,
                                        'wpEmailBan'           => $emailban,
                                        'wpWatchUser'          => 0,
                                );
                        return $this->http->post($this->indexurl.'?title=Special:BlockIP&action=submit',$post);
                }
 
                function unblock ($user,$reason=null) {
                        $wpapi = new wikipediaapi; $wpapi->apiurl = str_replace('index.php','api.php',$this->indexurl);
                        if ((!$this->edittoken) or ($this->edittoken == '')) $this->edittoken = $wpapi->getedittoken();
 
                        $token = htmlspecialchars($this->edittoken);
 
                        $post = array
                                (
                                        'wpUnblockAddress'     => $user,
                                        'wpUnblockReason'      => $reason,
                                        'wpBlock'              => 'Unblock',
                                        'wpEditToken'           => $token
                                );
                        return $this->http->post($this->indexurl.'?title=Special:IPBlockList&action=submit',$post);
                }
        }
?>
Retrieved from "https://en.wikipedia.org/w/index.php?title=User:X!/Main_Page_bot_Source&oldid=244475187"