Jump to content

User:Gdr/protect.py

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

See also Wikipedia:Bot policy and the Python-based tool editing tool m:Using the python wikipediabot .

#!/usr/bin/python
#
#
#              PROTECT.PY -- PROTECT AND UNPROTECT PAGES
#                           Gdr, 2005-05-12
#
#
# INTRODUCTION
#
# This module implements automatic protection and unprotection of
# wikipedia pages. It is designed to be used with the Python Wikipedia
# Robot Framework (http://sourceforge.net/projects/pywikipediabot/).
#
#
# USAGE
#
# You must use login.py to log in as a user with administrator
# privileges in order for this module to be effective. Then you can use
# it like this:
#
#   import protect
#   protect.protectPage(pagelink, 'reason for protecting')
#   protect.unprotectPage(pagelink, 'reason for unprotecting')
#
#
# LICENCES
#
# This software can be used and reproduced under the terms and
# conditions of the Python Software Foundation license under which
# recent copies of the python-2.3 interpreter can be used.
#
# 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.

import re
import wikipedia
import time

def applyAction(page, action, predata):
    """Apply 'action' to page 'name' on 'site'."""
    import httplib
    # Check whether we are not too quickly after the previous putPage, and
    # wait a bit until the interval is acceptable
    wikipedia.put_throttle()
    # Which web-site host are we submitting to?
    host = page.site().hostname()
    # Get the address of the page on that host.
    address = '/w/wiki.phtml?title=%s&action=%s'%(page.urlname(),action)

    # Get the page and scan it for the edittoken.
    text, charset = wikipedia.getUrl(host, address, page.site())
    m = re.search('value=[\'"]([0-9a-z]+)[\'"] name=[\'"]wpEditToken[\'"]',text)
    if m:
        token = m.group(1)
    else:
        m = re.search('name=[\'"]wpEditToken[\'"] value=[\'"]([0-9a-z]+)[\'"]',text)
        if m:
            token = m.group(1)
        else:
            token = "0"
    print "token = ", token

    predata.append(('wpEditToken', token))
    data = wikipedia.urlencode(tuple(predata))

    wikipedia.output(wikipedia.url2unicode("Apply %s to page %s:%s"%(action,page.site().hostname(),page.urlname()), site = page.site()))

    # Submit the prepared information
    now = time.time()
    conn = httplib.HTTPConnection(host)

    conn.putrequest("POST", address)
    conn.putheader('Content-Length', str(len(data)))
    conn.putheader("Content-type", "application/x-www-form-urlencoded")
    conn.putheader("User-agent", "PythonWikipediaBot/1.0")
    if page.site().cookies():
        conn.putheader('Cookie', page.site().cookies())
    conn.endheaders()
    conn.send(data)

    # Prepare the return values
    response = conn.getresponse()
    data = response.read()
    conn.close()
    wikipedia.put_throttle.setDelay(time.time() - now)
    return response.status, response.reason, data

def protectPage(page, reason = None, moveonly = False):
    """Protect 'page'."""
    wpmoveonly = "0"
    if moveonly:
        wpmoveonly = "1"
    return applyAction(page, 'protect',
                       [('wpReasonProtect', reason),
                        ('wpConfirmProtect', '1'),
                        ('wpMoveOnly', wpmoveonly),
                        ('wpConfirmProtectB', 'Confirm')])

def unprotectPage(page, reason):
    """Unprotect 'page'."""
    return applyAction(page, 'unprotect',
                       [('wpReasonProtect', reason),
                        ('wpConfirmProtect', '1'),
                        ('wpConfirmProtectB', 'Confirm')])