Advertisement
Guest User

Untitled

a guest
Jun 4th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 18.64 KB | None | 0 0
  1. import httplib, urllib, re, sys, logging
  2. import weechat, pynotify, string
  3.  
  4. weechat.register ("s2lookup", "xorc", "0.0.1", "GPL", "savage 2: looks up the stats of a player", "", "")
  5.  
  6. # script options
  7. settings = {
  8. }
  9.  
  10. urgencies = {
  11. }
  12.  
  13. # Init everything
  14. for option, default_value in settings.items ():
  15.     if weechat.config_get_plugin(option) == "":
  16.         weechat.config_set_plugin(option, default_value)
  17.  
  18. # Hook privmsg/hilights
  19. weechat.hook_print("", "irc_privmsg", "", 1, "s2lookup_show", "")
  20.  
  21. # Functions
  22. def s2lookup_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message):
  23.     """Sends highlighted message to be printed on notification"""
  24.  
  25.     filter = re.compile ('!lookup (\d+)');
  26.     match = filter.match (message);
  27.  
  28.     ms = MasterServer()
  29.  
  30.     if (match is not None):
  31.         weechat.command (bufferp , repr(ms.getStatistics (match.groups ()[0])))
  32.  
  33.     return weechat.WEECHAT_RC_OK
  34.  
  35.  
  36.  
  37.  
  38. class MasterServer:
  39.  
  40.         MASTERHOST = "masterserver.savage2.s2games.com"
  41.         MASTERURL = "/irc_updater/irc_requester.php"
  42.         headers = {}
  43.  
  44.         def __init__(self):
  45.                 self.headers = {
  46.                         "User-Agent": "PHP Script",
  47.                         "Content-Type": "application/x-www-form-urlencoded"
  48.                 }
  49.  
  50.  
  51.         def getStatistics (self, *args):
  52.                 stub = "&account_id[%s]=%s"
  53.                 lookup = ""
  54.  
  55.                 i = 0
  56.                 for id in args:
  57.                         lookup = lookup + (stub % (i, id))
  58.                         i = i + 1
  59.  
  60.                 return self.decode (self.query ("f=get_all_stats%s" % lookup))
  61.  
  62.         def decode (self, response):
  63.                 return loads(response, object_hook=phpobject)
  64.  
  65.         def query (self, params):
  66.  
  67.                 conn = httplib.HTTPConnection (self.MASTERHOST)
  68.                 conn.request ("POST", self.MASTERURL, params, self.headers)
  69.  
  70.                 response = conn.getresponse()
  71.  
  72.                 if response.status <> 200:
  73.                         return None
  74.  
  75.                 data = response.read()
  76.                 conn.close()
  77.  
  78.                 return data
  79.  
  80. r"""
  81.    phpserialize
  82.    ~~~~~~~~~~~~
  83.  
  84.    a port of the ``serialize`` and ``unserialize`` functions of
  85.    php to python.  This module implements the python serialization
  86.    interface (eg: provides `dumps`, `loads` and similar functions).
  87.  
  88.    Usage
  89.    =====
  90.  
  91.    >>> from phpserialize import *
  92.    >>> obj = dumps("Hello World")
  93.    >>> loads(obj)
  94.    'Hello World'
  95.  
  96.    Due to the fact that PHP doesn't know the concept of lists, lists
  97.    are serialized like hash-maps in PHP.  As a matter of fact the
  98.    reverse value of a serialized list is a dict:
  99.  
  100.    >>> loads(dumps(range(2)))
  101.    {0: 0, 1: 1}
  102.  
  103.    If you want to have a list again, you can use the `dict_to_list`
  104.    helper function:
  105.  
  106.    >>> dict_to_list(loads(dumps(range(2))))
  107.    [0, 1]
  108.  
  109.    It's also possible to convert into a tuple by using the `dict_to_tuple`
  110.    function:
  111.  
  112.    >>> dict_to_tuple(loads(dumps((1, 2, 3))))
  113.    (1, 2, 3)
  114.  
  115.    Another problem are unicode strings.  By default unicode strings are
  116.    encoded to 'utf-8' but not decoded on `unserialize`.  The reason for
  117.    this is that phpserialize can't guess if you have binary or text data
  118.    in the strings:
  119.  
  120.    >>> loads(dumps(u'Hello W\xf6rld'))
  121.    'Hello W\xc3\xb6rld'
  122.  
  123.    If you know that you have only text data of a known charset in the result
  124.    you can decode strings by setting `decode_strings` to True when calling
  125.    loads:
  126.  
  127.    >>> loads(dumps(u'Hello W\xf6rld'), decode_strings=True)
  128.    u'Hello W\xf6rld'
  129.  
  130.    Dictionary keys are limited to strings and integers.  `None` is converted
  131.    into an empty string and floats and booleans into integers for PHP
  132.    compatibility:
  133.  
  134.    >>> loads(dumps({None: 14, 42.23: 'foo', True: [1, 2, 3]}))
  135.    {'': 14, 1: {0: 1, 1: 2, 2: 3}, 42: 'foo'}
  136.  
  137.    It also provides functions to read from file-like objects:
  138.  
  139.    >>> from StringIO import StringIO
  140.    >>> stream = StringIO('a:2:{i:0;i:1;i:1;i:2;}')
  141.    >>> dict_to_list(load(stream))
  142.    [1, 2]
  143.  
  144.    And to write to those:
  145.  
  146.    >>> stream = StringIO()
  147.    >>> dump([1, 2], stream)
  148.    >>> stream.getvalue()
  149.    'a:2:{i:0;i:1;i:1;i:2;}'
  150.  
  151.    Like `pickle` chaining of objects is supported:
  152.  
  153.    >>> stream = StringIO()
  154.    >>> dump([1, 2], stream)
  155.    >>> dump("foo", stream)
  156.    >>> stream.seek(0)
  157.    >>> load(stream)
  158.    {0: 1, 1: 2}
  159.    >>> load(stream)
  160.    'foo'
  161.  
  162.    This feature however is not supported in PHP.  PHP will only unserialize
  163.    the first object.
  164.  
  165.    Array Serialization
  166.    ===================
  167.  
  168.    Starting with 1.2 you can provide an array hook to the unserialization
  169.    functions that are invoked with a list of pairs to return a real array
  170.    object.  By default `dict` is used as array object which however means
  171.    that the information about the order is list for associative arrays.
  172.  
  173.    For example you can pass the ordered dictionary to the unserilization
  174.    functions:
  175.  
  176.    >>> from collections import OrderedDict
  177.    >>> loads('a:2:{s:3:"foo";i:1;s:3:"bar";i:2;}',
  178.    ...       array_hook=OrderedDict)
  179.    collections.OrderedDict([('foo', 1), ('bar', 2)])
  180.  
  181.    Object Serialization
  182.    ====================
  183.  
  184.    PHP supports serialization of objects.  Starting with 1.2 of phpserialize
  185.    it is possible to both serialize and unserialize objects.  Because class
  186.    names in PHP and Python usually do not map, there is a separate
  187.    `object_hook` parameter that is responsible for creating these classes.
  188.  
  189.    For a simple test example the `phpserialize.phpobject` class can be used:
  190.  
  191.    >>> data = 'O:7:"WP_User":1:{s:8:"username";s:5:"admin";}'
  192.    >>> user = loads(data, object_hook=phpobject)
  193.    >>> user.username
  194.    'admin'
  195.    >>> user.__name__
  196.    'WP_User'
  197.  
  198.    An object hook is a function that takes the name of the class and a dict
  199.    with the instance data as arguments.  The instance data keys are in PHP
  200.    format which usually is not what you want.  To convert it into Python
  201.    identifiers you can use the `convert_member_dict` function.  For more
  202.    information about that, have a look at the next section.  Here an
  203.    example for a simple object hook:
  204.  
  205.    >>> class User(object):
  206.    ...     def __init__(self, username):
  207.    ...         self.username = username
  208.    ...
  209.    >>> def object_hook(name, d):
  210.    ...     cls = {'WP_User': User}[name]
  211.    ...     return cls(**d)
  212.    ...
  213.    >>> user = loads(data, object_hook=phpobject)
  214.    >>> user.username
  215.    'admin'
  216.  
  217.    To serialize objects you can use the `object_hook` of the dump functions
  218.    and return instances of `phpobject`:
  219.  
  220.    >>> def object_hook(obj):
  221.    ...     if isinstance(obj, User):
  222.    ...         return phpobject('WP_User', {'username': obj.username})
  223.    ...     raise LookupError('unknown object')
  224.    ...
  225.    >>> dumps(user, object_hook=object_hook)
  226.    'O:7:"WP_User":1:{s:8:"username";s:5:"admin";}'
  227.  
  228.    PHP's Object System
  229.    ===================
  230.  
  231.    The PHP object system is derived from compiled languages such as Java
  232.    and C#.  Attributes can be protected from external access by setting
  233.    them to `protected` or `private`.  This does not only serve the purpose
  234.    to encapsulate internals but also to avoid name clashes.
  235.  
  236.    In PHP each class in the inheritance chain can have a private variable
  237.    with the same name, without causing clashes.  (This is similar to the
  238.    Python `__var` name mangling system).
  239.  
  240.    This PHP class::
  241.  
  242.        class WP_UserBase {
  243.            protected $username;
  244.  
  245.            public function __construct($username) {
  246.                $this->username = $username;
  247.            }
  248.        }
  249.  
  250.        class WP_User extends WP_UserBase {
  251.            private $password;
  252.            public $flag;
  253.  
  254.            public function __construct($username, $password) {
  255.                parent::__construct($username);
  256.                $this->password = $password;
  257.                $this->flag = 0;
  258.            }
  259.        }
  260.  
  261.    Is serialized with a member data dict that looks like this:
  262.  
  263.    >>> data = {
  264.    ...     ' * username':          'the username',
  265.    ...     ' WP_User password':    'the password',
  266.    ...     'flag':                 'the flag'
  267.    ... }
  268.  
  269.    Because this access system does not exist in Python, the
  270.    `convert_member_dict` can convert this dict:
  271.  
  272.    >>> d = convert_member_dict(data)
  273.    >>> d['username']
  274.    'the username'
  275.    >>> d['password']
  276.    'the password'
  277.  
  278.    The `phpobject` class does this conversion on the fly.  What is
  279.    serialized is the special `__php_vars__` dict of the class:
  280.  
  281.    >>> user = phpobject('WP_User', data)
  282.    >>> user.username
  283.    'the username'
  284.    >>> user.username = 'admin'
  285.    >>> user.__php_vars__[' * username']
  286.    'admin'
  287.  
  288.    As you can see, reassigning attributes on a php object will try
  289.    to change a private or protected attribute with the same name.
  290.    Setting an unknown one will create a new public attribute:
  291.  
  292.    >>> user.is_admin = True
  293.    >>> user.__php_vars__['is_admin']
  294.    True
  295.  
  296.    To convert the phpobject into a dict, you can use the `_asdict`
  297.    method:
  298.  
  299.    >>> d = user._asdict()
  300.    >>> d['username']
  301.    'admin'
  302.  
  303.    Changelog
  304.    =========
  305.  
  306.    1.2
  307.        -   added support for object serialization
  308.        -   added support for array hooks.
  309.  
  310.    1.1
  311.        -   added `dict_to_list` and `dict_to_tuple`
  312.        -   added support for unicode
  313.        -   allowed chaining of objects like pickle does.
  314.  
  315.  
  316.    :copyright: 2007-2008 by Armin Ronacher.
  317.    license: BSD
  318. """
  319. from StringIO import StringIO
  320.  
  321. __author__ = 'Armin Ronacher <armin.ronacher@active-4.com>'
  322. __version__ = '1.1'
  323. __all__ = ('phpobject', 'convert_member_dict', 'dict_to_list', 'dict_to_tuple',
  324.            'load', 'loads', 'dump', 'dumps', 'serialize', 'unserialize')
  325.  
  326.  
  327. def _translate_member_name(name):
  328.     if name[:1] == ' ':
  329.         name = name.split(None, 2)[-1]
  330.     return name
  331.  
  332.  
  333. class phpobject(object):
  334.     """Simple representation for PHP objects.  This is used """
  335.     __slots__ = ('__name__', '__php_vars__')
  336.  
  337.     def __init__(self, name, d=None):
  338.         if d is None:
  339.             d = {}
  340.         object.__setattr__(self, '__name__', name)
  341.         object.__setattr__(self, '__php_vars__', d)
  342.  
  343.     def _asdict(self):
  344.         """Returns a new dictionary from the data with Python identifiers."""
  345.         return convert_member_dict(self.__php_vars__)
  346.  
  347.     def _lookup_php_var(self, name):
  348.         for key, value in self.__php_vars__.iteritems():
  349.             if _translate_member_name(key) == name:
  350.                 return key, value
  351.  
  352.     def __getattr__(self, name):
  353.         rv = self._lookup_php_var(name)
  354.         if rv is not None:
  355.             return rv[1]
  356.         raise AttributeError(name)
  357.  
  358.     def __setattr__(self, name, value):
  359.         rv = self._lookup_php_var(name)
  360.         if rv is not None:
  361.             name = rv[0]
  362.         self.__php_vars__[name] = value
  363.  
  364.     def __repr__(self):
  365.         return '<phpobject %r>' % (self.__name__,)
  366.  
  367.  
  368. def convert_member_dict(d):
  369.     """Converts the names of a member dict to Python syntax.  PHP class data
  370.    member names are not the plain identifiers but might be prefixed by the
  371.    class name if private or a star if protected.  This function converts them
  372.    into standard Python identifiers:
  373.  
  374.    >>> convert_member_dict({"username": "user1", " User password":
  375.    ...                      "default", " * is_active": True})
  376.    {'username': 'user1', 'password': 'default', 'is_active': True}
  377.    """
  378.     return dict((_translate_member_name(k), v) for k, v in d.iteritems())
  379.  
  380.  
  381. def dumps(data, charset='utf-8', errors='strict', object_hook=None):
  382.     """Return the PHP-serialized representation of the object as a string,
  383.    instead of writing it to a file like `dump` does.
  384.    """
  385.     def _serialize(obj, keypos):
  386.         if keypos:
  387.             if isinstance(obj, (int, long, float, bool)):
  388.                 return 'i:%i;' % obj
  389.             if isinstance(obj, basestring):
  390.                 if isinstance(obj, unicode):
  391.                     obj = obj.encode(charset, errors)
  392.                 return 's:%i:"%s";' % (len(obj), obj)
  393.             if obj is None:
  394.                 return 's:0:"";'
  395.             raise TypeError('can\'t serialize %r as key' % type(obj))
  396.        else:
  397.            if obj is None:
  398.                return 'N;'
  399.            if isinstance(obj, bool):
  400.                return 'b:%i;' % obj
  401.            if isinstance(obj, (int, long)):
  402.                return 'i:%s;' % obj
  403.            if isinstance(obj, float):
  404.                return 'd:%s;' % obj
  405.            if isinstance(obj, basestring):
  406.                if isinstance(obj, unicode):
  407.                    obj = obj.encode(charset, errors)
  408.                return 's:%i:"%s";' % (len(obj), obj)
  409.            if isinstance(obj, (list, tuple, dict)):
  410.                out = []
  411.                if isinstance(obj, dict):
  412.                    iterable = obj.iteritems()
  413.                else:
  414.                    iterable = enumerate(obj)
  415.                for key, value in iterable:
  416.                    out.append(_serialize(key, True))
  417.                    out.append(_serialize(value, False))
  418.                return 'a:%i:{%s}' % (len(obj), ''.join(out))
  419.            if isinstance(obj, phpobject):
  420.                return 'O%s%s' % (
  421.                    _serialize(obj.__name__, True)[1:-1],
  422.                    _serialize(obj.__php_vars__, False)[1:]
  423.                )
  424.            if object_hook is not None:
  425.                return _serialize(object_hook(obj), False)
  426.            raise TypeError('can\'t serialize %r' % type(obj))
  427.    return _serialize(data, False)
  428.  
  429.  
  430. def load(fp, charset='utf-8', errors='strict', decode_strings=False,
  431.         object_hook=None, array_hook=None):
  432.    """Read a string from the open file object `fp` and interpret it as a
  433.    data stream of PHP-serialized objects, reconstructing and returning
  434.    the original object hierarchy.
  435.  
  436.    `fp` must provide a `read()` method that takes an integer argument.  Both
  437.    method should return strings.  Thus `fp` can be a file object opened for
  438.    reading, a `StringIO` object, or any other custom object that meets this
  439.    interface.
  440.  
  441.    `load` will read exactly one object from the stream.  See the docstring of
  442.    the module for this chained behavior.
  443.  
  444.    If an object hook is given object-opcodes are supported in the serilization
  445.    format.  The function is called with the class name and a dict of the
  446.    class data members.  The data member names are in PHP format which is
  447.    usually not what you want.  The `simple_object_hook` function can convert
  448.    them to Python identifier names.
  449.  
  450.    If an `array_hook` is given that function is called with a list of pairs
  451.    for all array items.  This can for example be set to
  452.    `collections.OrderedDict` for an ordered, hashed dictionary.
  453.    """
  454.    if array_hook is None:
  455.        array_hook = dict
  456.  
  457.    def _expect(e):
  458.        v = fp.read(len(e))
  459.        if v != e:
  460.            raise ValueError('failed expectation, expected %r got %r' % (e, v))
  461.  
  462.    def _read_until(delim):
  463.        buf = []
  464.        while 1:
  465.            char = fp.read(1)
  466.            if char == delim:
  467.                break
  468.            elif not char:
  469.                raise ValueError('unexpected end of stream')
  470.            buf.append(char)
  471.        return ''.join(buf)
  472.  
  473.    def _load_array():
  474.        items = int(_read_until(':')) * 2
  475.        _expect('{')
  476.        result = []
  477.        last_item = Ellipsis
  478.        for idx in xrange(items):
  479.            item = _unserialize()
  480.            if last_item is Ellipsis:
  481.                last_item = item
  482.            else:
  483.                result.append((last_item, item))
  484.                last_item = Ellipsis
  485.        _expect('}')
  486.        return result
  487.  
  488.    def _unserialize():
  489.        type_ = fp.read(1).lower()
  490.        if type_ == 'n':
  491.            _expect(';')
  492.            return None
  493.        if type_ in 'idb':
  494.            _expect(':')
  495.            data = _read_until(';')
  496.            if type_ == 'i':
  497.                return int(data)
  498.            if type_ == 'd':
  499.                return float(data)
  500.            return int(data) != 0
  501.        if type_ == 's':
  502.            _expect(':')
  503.            length = int(_read_until(':'))
  504.            _expect('"')
  505.            data = fp.read(length)
  506.            _expect('"')
  507.            if decode_strings:
  508.                data = data.decode(charset, errors)
  509.            _expect(';')
  510.            return data
  511.        if type_ == 'a':
  512.            _expect(':')
  513.            return array_hook(_load_array())
  514.        if type_ == 'o':
  515.            if object_hook is None:
  516.                raise ValueError('object in serialization dump but '
  517.                                 'object_hook not given.')
  518.            _expect(':')
  519.            name_length = int(_read_until(':'))
  520.            _expect('"')
  521.            name = fp.read(name_length)
  522.            _expect('":')
  523.            return object_hook(name, dict(_load_array()))
  524.        raise ValueError('unexpected opcode')
  525.  
  526.    return _unserialize()
  527.  
  528.  
  529. def loads(data, charset='utf-8', errors='strict', decode_strings=False,
  530.          object_hook=None, array_hook=None):
  531.    """Read a PHP-serialized object hierarchy from a string.  Characters in the
  532.    string past the object's representation are ignored.
  533.     """
  534.    return load(StringIO(data), charset, errors, decode_strings,
  535.                object_hook, array_hook)
  536.  
  537.  
  538. def dump(data, fp, charset='utf-8', errors='strict', object_hook=None):
  539.    """Write a PHP-serialized representation of obj to the open file object
  540.     `fp`.  Unicode strings are encoded to `charset` with the error handling
  541.     of `errors`.
  542.  
  543.     `fp` must have a `write()` method that accepts a single string argument.
  544.     It can thus be a file object opened for writing, a `StringIO` object, or
  545.     any other custom object that meets this interface.
  546.  
  547.     The `object_hook` is called for each unknown object and has to either
  548.     raise an exception if it's unable to convert the object or return a
  549.    value that is serializable (such as a `phpobject`).
  550.    """
  551.    fp.write(dumps(data, charset, errors, object_hook))
  552.  
  553.  
  554. def dict_to_list(d):
  555.    """Converts an ordered dict into a list."""
  556.    # make sure it's a dict, that way dict_to_list can be used as an
  557.     # array_hook.
  558.     d = dict(d)
  559.     try:
  560.         return [d[x] for x in xrange(len(d))]
  561.     except KeyError:
  562.         raise ValueError('dict is not a sequence')
  563.  
  564.  
  565. def dict_to_tuple(d):
  566.     """Converts an ordered dict into a tuple."""
  567.     return tuple(dict_to_list(d))
  568.  
  569.  
  570. serialize = dumps
  571. unserialize = loads
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement