text:
from __future__ import absolute_import

from twisted.trial import unittest
#import unittest

from autobahn.wamp import role
from autobahn.wamp import message
from autobahn.wamp.exception import ProtocolError

class TestErrorMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error1')
      msg = e.marshal()
      self.assertEqual(len(msg), 5)
      self.assertEqual(msg[0], message.Error.MESSAGE_TYPE)
      self.assertEqual(msg[1], message.Call.MESSAGE_TYPE)
      self.assertEqual(msg[2], 123456)
      self.assertEqual(msg[3], {})
      self.assertEqual(msg[4], 'com.myapp.error1')

      e = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error1', args = [1, 2, 3], kwargs = {'foo': 23, 'bar': 'hello'})
      msg = e.marshal()
      self.assertEqual(len(msg), 7)
      self.assertEqual(msg[0], message.Error.MESSAGE_TYPE)
      self.assertEqual(msg[1], message.Call.MESSAGE_TYPE)
      self.assertEqual(msg[2], 123456)
      self.assertEqual(msg[3], {})
      self.assertEqual(msg[4], 'com.myapp.error1')
      self.assertEqual(msg[5], [1, 2, 3])
      self.assertEqual(msg[6], {'foo': 23, 'bar': 'hello'})

   def test_parse_and_marshal(self):
      wmsg = [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.error1']
      msg = message.Error.parse(wmsg)
      self.assertIsInstance(msg, message.Error)
      self.assertEqual(msg.request_type, message.Call.MESSAGE_TYPE)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.error, 'com.myapp.error1')
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.error1', [1, 2, 3], {'foo': 23, 'bar': 'hello'}]
      msg = message.Error.parse(wmsg)
      self.assertIsInstance(msg, message.Error)
      self.assertEqual(msg.request_type, message.Call.MESSAGE_TYPE)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.error, 'com.myapp.error1')
      self.assertEqual(msg.args, [1, 2, 3])
      self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'})
      self.assertEqual(msg.marshal(), wmsg)

class TestSubscribeMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Subscribe(123456, 'com.myapp.topic1')
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Subscribe.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], 'com.myapp.topic1')

      e = message.Subscribe(123456, 'com.myapp.topic1', match = message.Subscribe.MATCH_PREFIX)
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Subscribe.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'match': 'prefix'})
      self.assertEqual(msg[3], 'com.myapp.topic1')

   def test_parse_and_marshal(self):
      wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {}, 'com.myapp.topic1']
      msg = message.Subscribe.parse(wmsg)
      self.assertIsInstance(msg, message.Subscribe)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.topic, 'com.myapp.topic1')
      self.assertEqual(msg.match, message.Subscribe.MATCH_EXACT)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {'match': 'prefix'}, 'com.myapp.topic1']
      msg = message.Subscribe.parse(wmsg)
      self.assertIsInstance(msg, message.Subscribe)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.topic, 'com.myapp.topic1')
      self.assertEqual(msg.match, message.Subscribe.MATCH_PREFIX)
      self.assertEqual(msg.marshal(), wmsg)

class TestSubscribedMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Subscribed(123456, 789123)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Subscribed.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)

   def test_parse_and_marshal(self):
      wmsg = [message.Subscribed.MESSAGE_TYPE, 123456, 789123]
      msg = message.Subscribed.parse(wmsg)
      self.assertIsInstance(msg, message.Subscribed)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.subscription, 789123)
      self.assertEqual(msg.marshal(), wmsg)

class TestUnsubscribeMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Unsubscribe(123456, 789123)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Unsubscribe.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)

   def test_parse_and_marshal(self):
      wmsg = [message.Unsubscribe.MESSAGE_TYPE, 123456, 789123]
      msg = message.Unsubscribe.parse(wmsg)
      self.assertIsInstance(msg, message.Unsubscribe)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.subscription, 789123)
      self.assertEqual(msg.marshal(), wmsg)

class TestUnsubscribedMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Unsubscribed(123456)
      msg = e.marshal()
      self.assertEqual(len(msg), 2)
      self.assertEqual(msg[0], message.Unsubscribed.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)

   def test_parse_and_marshal(self):
      wmsg = [message.Unsubscribed.MESSAGE_TYPE, 123456]
      msg = message.Unsubscribed.parse(wmsg)
      self.assertIsInstance(msg, message.Unsubscribed)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.marshal(), wmsg)

class TestPublishMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Publish(123456, 'com.myapp.topic1')
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Publish.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], 'com.myapp.topic1')

      e = message.Publish(123456, 'com.myapp.topic1', args = [1, 2, 3], kwargs = {'foo': 23, 'bar': 'hello'})
      msg = e.marshal()
      self.assertEqual(len(msg), 6)
      self.assertEqual(msg[0], message.Publish.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], 'com.myapp.topic1')
      self.assertEqual(msg[4], [1, 2, 3])
      self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'})

      e = message.Publish(123456, 'com.myapp.topic1', excludeMe = False, exclude = [300], eligible = [100, 200, 300], discloseMe = True)
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Publish.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'exclude_me': False, 'disclose_me': True, 'exclude': [300], 'eligible': [100, 200, 300]})
      self.assertEqual(msg[3], 'com.myapp.topic1')

   def test_parse_and_marshal(self):
      wmsg = [message.Publish.MESSAGE_TYPE, 123456, {}, 'com.myapp.topic1']
      msg = message.Publish.parse(wmsg)
      self.assertIsInstance(msg, message.Publish)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.topic, 'com.myapp.topic1')
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.excludeMe, None)
      self.assertEqual(msg.exclude, None)
      self.assertEqual(msg.eligible, None)
      self.assertEqual(msg.discloseMe, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Publish.MESSAGE_TYPE, 123456, {}, 'com.myapp.topic1', [1, 2, 3], {'foo': 23, 'bar': 'hello'}]
      msg = message.Publish.parse(wmsg)
      self.assertIsInstance(msg, message.Publish)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.topic, 'com.myapp.topic1')
      self.assertEqual(msg.args, [1, 2, 3])
      self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'})
      self.assertEqual(msg.excludeMe, None)
      self.assertEqual(msg.exclude, None)
      self.assertEqual(msg.eligible, None)
      self.assertEqual(msg.discloseMe, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Publish.MESSAGE_TYPE, 123456, {'exclude_me': False, 'disclose_me': True, 'exclude': [300], 'eligible': [100, 200, 300]}, 'com.myapp.topic1']
      msg = message.Publish.parse(wmsg)
      self.assertIsInstance(msg, message.Publish)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.topic, 'com.myapp.topic1')
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.excludeMe, False)
      self.assertEqual(msg.exclude, [300])
      self.assertEqual(msg.eligible, [100, 200, 300])
      self.assertEqual(msg.discloseMe, True)
      self.assertEqual(msg.marshal(), wmsg)

class TestPublishedMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Published(123456, 789123)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Published.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)

   def test_parse_and_marshal(self):
      wmsg = [message.Published.MESSAGE_TYPE, 123456, 789123]
      msg = message.Published.parse(wmsg)
      self.assertIsInstance(msg, message.Published)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.publication, 789123)
      self.assertEqual(msg.marshal(), wmsg)

class TestEventMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Event(123456, 789123)
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Event.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)
      self.assertEqual(msg[3], {})

      e = message.Event(123456, 789123, args = [1, 2, 3], kwargs = {'foo': 23, 'bar': 'hello'})
      msg = e.marshal()
      self.assertEqual(len(msg), 6)
      self.assertEqual(msg[0], message.Event.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)
      self.assertEqual(msg[3], {})
      self.assertEqual(msg[4], [1, 2, 3])
      self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'})

      e = message.Event(123456, 789123, publisher = 300)
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Event.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)
      self.assertEqual(msg[3], {'publisher': 300})

   def test_parse_and_marshal(self):
      wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {}]
      msg = message.Event.parse(wmsg)
      self.assertIsInstance(msg, message.Event)
      self.assertEqual(msg.subscription, 123456)
      self.assertEqual(msg.publication, 789123)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.publisher, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}]
      msg = message.Event.parse(wmsg)
      self.assertIsInstance(msg, message.Event)
      self.assertEqual(msg.subscription, 123456)
      self.assertEqual(msg.publication, 789123)
      self.assertEqual(msg.args, [1, 2, 3])
      self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'})
      self.assertEqual(msg.publisher, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {'publisher': 300}]
      msg = message.Event.parse(wmsg)
      self.assertIsInstance(msg, message.Event)
      self.assertEqual(msg.subscription, 123456)
      self.assertEqual(msg.publication, 789123)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.publisher, 300)
      self.assertEqual(msg.marshal(), wmsg)

class TestRegisterMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Register(123456, 'com.myapp.procedure1')
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Register.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], 'com.myapp.procedure1')

      e = message.Register(123456, 'com.myapp.procedure1', pkeys = [10, 11, 12])
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Register.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'pkeys': [10, 11, 12]})
      self.assertEqual(msg[3], 'com.myapp.procedure1')

   def test_parse_and_marshal(self):
      wmsg = [message.Register.MESSAGE_TYPE, 123456, {}, 'com.myapp.procedure1']
      msg = message.Register.parse(wmsg)
      self.assertIsInstance(msg, message.Register)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.procedure, 'com.myapp.procedure1')
      self.assertEqual(msg.pkeys, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Register.MESSAGE_TYPE, 123456, {'pkeys': [10, 11, 12]}, 'com.myapp.procedure1']
      msg = message.Register.parse(wmsg)
      self.assertIsInstance(msg, message.Register)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.procedure, 'com.myapp.procedure1')
      self.assertEqual(msg.pkeys, [10, 11, 12])
      self.assertEqual(msg.marshal(), wmsg)

class TestRegisteredMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Registered(123456, 789123)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Registered.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)

   def test_parse_and_marshal(self):
      wmsg = [message.Registered.MESSAGE_TYPE, 123456, 789123]
      msg = message.Registered.parse(wmsg)
      self.assertIsInstance(msg, message.Registered)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.registration, 789123)
      self.assertEqual(msg.marshal(), wmsg)

class TestUnregisterMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Unregister(123456, 789123)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Unregister.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)

   def test_parse_and_marshal(self):
      wmsg = [message.Unregister.MESSAGE_TYPE, 123456, 789123]
      msg = message.Unregister.parse(wmsg)
      self.assertIsInstance(msg, message.Unregister)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.registration, 789123)
      self.assertEqual(msg.marshal(), wmsg)

class TestUnregisteredMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Unregistered(123456)
      msg = e.marshal()
      self.assertEqual(len(msg), 2)
      self.assertEqual(msg[0], message.Unregistered.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)

   def test_parse_and_marshal(self):
      wmsg = [message.Unregistered.MESSAGE_TYPE, 123456]
      msg = message.Unregistered.parse(wmsg)
      self.assertIsInstance(msg, message.Unregistered)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.marshal(), wmsg)

class TestCallMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Call(123456, 'com.myapp.procedure1')
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Call.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], 'com.myapp.procedure1')

      e = message.Call(123456, 'com.myapp.procedure1', args = [1, 2, 3], kwargs = {'foo': 23, 'bar': 'hello'})
      msg = e.marshal()
      self.assertEqual(len(msg), 6)
      self.assertEqual(msg[0], message.Call.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], 'com.myapp.procedure1')
      self.assertEqual(msg[4], [1, 2, 3])
      self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'})

      e = message.Call(123456, 'com.myapp.procedure1', timeout = 10000)
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Call.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'timeout': 10000})
      self.assertEqual(msg[3], 'com.myapp.procedure1')

   def test_parse_and_marshal(self):
      wmsg = [message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.procedure1']
      msg = message.Call.parse(wmsg)
      self.assertIsInstance(msg, message.Call)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.procedure, 'com.myapp.procedure1')
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.timeout, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.procedure1', [1, 2, 3], {'foo': 23, 'bar': 'hello'}]
      msg = message.Call.parse(wmsg)
      self.assertIsInstance(msg, message.Call)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.procedure, 'com.myapp.procedure1')
      self.assertEqual(msg.args, [1, 2, 3])
      self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'})
      self.assertEqual(msg.timeout, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Call.MESSAGE_TYPE, 123456, {'timeout': 10000}, 'com.myapp.procedure1']
      msg = message.Call.parse(wmsg)
      self.assertIsInstance(msg, message.Call)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.procedure, 'com.myapp.procedure1')
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.timeout, 10000)
      self.assertEqual(msg.marshal(), wmsg)

class TestCancelMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Cancel(123456)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Cancel.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})

      e = message.Cancel(123456, mode = message.Cancel.KILL)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Cancel.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'mode': message.Cancel.KILL})

   def test_parse_and_marshal(self):
      wmsg = [message.Cancel.MESSAGE_TYPE, 123456, {}]
      msg = message.Cancel.parse(wmsg)
      self.assertIsInstance(msg, message.Cancel)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.mode, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Cancel.MESSAGE_TYPE, 123456, {'mode': message.Cancel.KILL}]
      msg = message.Cancel.parse(wmsg)
      self.assertIsInstance(msg, message.Cancel)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.mode, message.Cancel.KILL)
      self.assertEqual(msg.marshal(), wmsg)

class TestResultMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Result(123456)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Result.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})

      e = message.Result(123456, args = [1, 2, 3], kwargs = {'foo': 23, 'bar': 'hello'})
      msg = e.marshal()
      self.assertEqual(len(msg), 5)
      self.assertEqual(msg[0], message.Result.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], [1, 2, 3])
      self.assertEqual(msg[4], {'foo': 23, 'bar': 'hello'})

      e = message.Result(123456, progress = True)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Result.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'progress': True})

   def test_parse_and_marshal(self):
      wmsg = [message.Result.MESSAGE_TYPE, 123456, {}]
      msg = message.Result.parse(wmsg)
      self.assertIsInstance(msg, message.Result)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.progress, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Result.MESSAGE_TYPE, 123456, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}]
      msg = message.Result.parse(wmsg)
      self.assertIsInstance(msg, message.Result)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.args, [1, 2, 3])
      self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'})
      self.assertEqual(msg.progress, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Result.MESSAGE_TYPE, 123456, {'progress': True}]
      msg = message.Result.parse(wmsg)
      self.assertIsInstance(msg, message.Result)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.progress, True)
      self.assertEqual(msg.marshal(), wmsg)

class TestInvocationMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Invocation(123456, 789123)
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Invocation.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)
      self.assertEqual(msg[3], {})

      e = message.Invocation(123456, 789123, args = [1, 2, 3], kwargs = {'foo': 23, 'bar': 'hello'})
      msg = e.marshal()
      self.assertEqual(len(msg), 6)
      self.assertEqual(msg[0], message.Invocation.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)
      self.assertEqual(msg[3], {})
      self.assertEqual(msg[4], [1, 2, 3])
      self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'})

      e = message.Invocation(123456, 789123, timeout = 10000)
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Invocation.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], 789123)
      self.assertEqual(msg[3], {'timeout': 10000})

   def test_parse_and_marshal(self):
      wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {}]
      msg = message.Invocation.parse(wmsg)
      self.assertIsInstance(msg, message.Invocation)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.registration, 789123)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.timeout, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}]
      msg = message.Invocation.parse(wmsg)
      self.assertIsInstance(msg, message.Invocation)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.registration, 789123)
      self.assertEqual(msg.args, [1, 2, 3])
      self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'})
      self.assertEqual(msg.timeout, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {'timeout': 10000}]
      msg = message.Invocation.parse(wmsg)
      self.assertIsInstance(msg, message.Invocation)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.registration, 789123)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.timeout, 10000)
      self.assertEqual(msg.marshal(), wmsg)

class TestInterruptMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Interrupt(123456)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Interrupt.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})

      e = message.Interrupt(123456, mode = message.Interrupt.KILL)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Interrupt.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'mode': message.Interrupt.KILL})

   def test_parse_and_marshal(self):
      wmsg = [message.Interrupt.MESSAGE_TYPE, 123456, {}]
      msg = message.Interrupt.parse(wmsg)
      self.assertIsInstance(msg, message.Interrupt)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.mode, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Interrupt.MESSAGE_TYPE, 123456, {'mode': message.Interrupt.KILL}]
      msg = message.Interrupt.parse(wmsg)
      self.assertIsInstance(msg, message.Interrupt)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.mode, message.Interrupt.KILL)
      self.assertEqual(msg.marshal(), wmsg)

class TestYieldMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Yield(123456)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Yield.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})

      e = message.Yield(123456, args = [1, 2, 3], kwargs = {'foo': 23, 'bar': 'hello'})
      msg = e.marshal()
      self.assertEqual(len(msg), 5)
      self.assertEqual(msg[0], message.Yield.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {})
      self.assertEqual(msg[3], [1, 2, 3])
      self.assertEqual(msg[4], {'foo': 23, 'bar': 'hello'})

      e = message.Yield(123456, progress = True)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Yield.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123456)
      self.assertEqual(msg[2], {'progress': True})

   def test_parse_and_marshal(self):
      wmsg = [message.Yield.MESSAGE_TYPE, 123456, {}]
      msg = message.Yield.parse(wmsg)
      self.assertIsInstance(msg, message.Yield)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.progress, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Yield.MESSAGE_TYPE, 123456, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}]
      msg = message.Yield.parse(wmsg)
      self.assertIsInstance(msg, message.Yield)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.args, [1, 2, 3])
      self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'})
      self.assertEqual(msg.progress, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Yield.MESSAGE_TYPE, 123456, {'progress': True}]
      msg = message.Yield.parse(wmsg)
      self.assertIsInstance(msg, message.Yield)
      self.assertEqual(msg.request, 123456)
      self.assertEqual(msg.args, None)
      self.assertEqual(msg.kwargs, None)
      self.assertEqual(msg.progress, True)
      self.assertEqual(msg.marshal(), wmsg)

class TestHelloMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Hello("realm1", [role.RoleBrokerFeatures()])
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Hello.MESSAGE_TYPE)
      self.assertEqual(msg[1], "realm1")
      self.assertEqual(msg[2], {'roles': {'broker': {}}})

      e = message.Hello("realm1", [role.RoleBrokerFeatures(subscriber_blackwhite_listing = True)])
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Hello.MESSAGE_TYPE)
      self.assertEqual(msg[1], "realm1")
      self.assertEqual(msg[2], {'roles': {'broker': {'features': {'subscriber_blackwhite_listing': True}}}})

   def test_parse_and_marshal(self):
      wmsg = [message.Hello.MESSAGE_TYPE, "realm1", {'roles': {'broker': {}}}]
      msg = message.Hello.parse(wmsg)
      self.assertIsInstance(msg, message.Hello)
      self.assertEqual(msg.realm, "realm1")
      self.assertEqual(msg.roles, [role.RoleBrokerFeatures()])
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Hello.MESSAGE_TYPE, "realm1", {'roles': {'broker': {'features': {'subscriber_blackwhite_listing': True}}}}]
      msg = message.Hello.parse(wmsg)
      self.assertIsInstance(msg, message.Hello)
      self.assertEqual(msg.realm, "realm1")
      self.assertEqual(msg.roles, [role.RoleBrokerFeatures(subscriber_blackwhite_listing = True)])
      self.assertEqual(msg.marshal(), wmsg)

   def test_str(self):
      e = message.Hello("realm1", [role.RoleBrokerFeatures()])
      self.assertIsInstance(str(e), str)

class TestGoodbyeMessage(unittest.TestCase):

   def test_ctor(self):
      reason = 'wamp.error.system_shutdown'
      reason_msg = 'The host is shutting down now.'

      e = message.Goodbye()
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Goodbye.MESSAGE_TYPE)
      self.assertEqual(msg[1], {})
      self.assertEqual(msg[2], message.Goodbye.DEFAULT_REASON)

      e = message.Goodbye(reason = reason)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Goodbye.MESSAGE_TYPE)
      self.assertEqual(msg[1], {})
      self.assertEqual(msg[2], reason)

      e = message.Goodbye(reason = reason, message = reason_msg)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Goodbye.MESSAGE_TYPE)
      self.assertEqual(msg[1], {'message': reason_msg})
      self.assertEqual(msg[2], reason)

   def test_parse_and_marshal(self):
      reason = 'wamp.error.system_shutdown'
      reason_msg = 'The host is shutting down now.'

      wmsg = [message.Goodbye.MESSAGE_TYPE]
      self.assertRaises(ProtocolError, message.Goodbye.parse, wmsg)

      wmsg = [message.Goodbye.MESSAGE_TYPE, reason]
      self.assertRaises(ProtocolError, message.Goodbye.parse, wmsg)

      wmsg = [message.Goodbye.MESSAGE_TYPE, {'message': 100}, reason]
      self.assertRaises(ProtocolError, message.Goodbye.parse, wmsg)

      wmsg = [message.Goodbye.MESSAGE_TYPE, {}, reason]
      msg = message.Goodbye.parse(wmsg)
      self.assertIsInstance(msg, message.Goodbye)
      self.assertEqual(msg.reason, reason)
      self.assertEqual(msg.message, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Goodbye.MESSAGE_TYPE, {'message': reason_msg}, reason]
      msg = message.Goodbye.parse(wmsg)
      self.assertIsInstance(msg, message.Goodbye)
      self.assertEqual(msg.reason, reason)
      self.assertEqual(msg.message, reason_msg)
      self.assertEqual(msg.marshal(), wmsg)

   def test_str(self):
      e = message.Goodbye(reason = 'wamp.error.system_shutdown', message = 'The host is shutting down now.')
      self.assertIsInstance(str(e), str)

class TestHeartbeatMessage(unittest.TestCase):

   def test_ctor(self):
      e = message.Heartbeat(123, 456)
      msg = e.marshal()
      self.assertEqual(len(msg), 3)
      self.assertEqual(msg[0], message.Heartbeat.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123)
      self.assertEqual(msg[2], 456)

      e = message.Heartbeat(123, 456, "discard me")
      msg = e.marshal()
      self.assertEqual(len(msg), 4)
      self.assertEqual(msg[0], message.Heartbeat.MESSAGE_TYPE)
      self.assertEqual(msg[1], 123)
      self.assertEqual(msg[2], 456)
      self.assertEqual(msg[3], "discard me")

   def test_parse_and_marshal(self):
      wmsg = [message.Heartbeat.MESSAGE_TYPE]
      self.assertRaises(ProtocolError, message.Heartbeat.parse, wmsg)

      wmsg = [message.Heartbeat.MESSAGE_TYPE, 100]
      self.assertRaises(ProtocolError, message.Heartbeat.parse, wmsg)

      wmsg = [message.Heartbeat.MESSAGE_TYPE, 100, "foo"]
      self.assertRaises(ProtocolError, message.Heartbeat.parse, wmsg)

      wmsg = [message.Heartbeat.MESSAGE_TYPE, 100, 0]
      self.assertRaises(ProtocolError, message.Heartbeat.parse, wmsg)

      wmsg = [message.Heartbeat.MESSAGE_TYPE, 100, 100, 100]
      self.assertRaises(ProtocolError, message.Heartbeat.parse, wmsg)

      wmsg = [message.Heartbeat.MESSAGE_TYPE, 123, 456]
      msg = message.Heartbeat.parse(wmsg)
      self.assertIsInstance(msg, message.Heartbeat)
      self.assertEqual(msg.incoming, 123)
      self.assertEqual(msg.outgoing, 456)
      self.assertEqual(msg.discard, None)
      self.assertEqual(msg.marshal(), wmsg)

      wmsg = [message.Heartbeat.MESSAGE_TYPE, 123, 456, "discard me"]
      msg = message.Heartbeat.parse(wmsg)
      self.assertIsInstance(msg, message.Heartbeat)
      self.assertEqual(msg.incoming, 123)
      self.assertEqual(msg.outgoing, 456)
      self.assertEqual(msg.discard, "discard me")
      self.assertEqual(msg.marshal(), wmsg)

   def test_str(self):
      e = message.Heartbeat(123, 456, "discard me")
      self.assertIsInstance(str(e), str)

if __name__ == '__main__':
   unittest.main()


text:
var FGitem = function(el, prnt) {
    this.el = el.find('.fg_item_content');
    this.type = this.el.data('type');
    this.src = this.el.data('src');
    this.link = this.el.data('link');
    this.name = this.el.data('name');
    this.descripton = this.el.data('descripton');
    this.prnt = prnt;
    this.init();
};

FGitem.prototype = {
    init: function() {
        var self = this;
        self.el.find('.name, .icon, .img').bind('click', function() {
            var src = self.src;
            if (self.link == 1) {
                window.open(src);
                return false;
            }
            self.prnt.wrap.fadeIn();
            if (self.type == 'doc') {
                if (src.substr(0, 4) != 'http') {
                    src = 'http://' + window.location.hostname + src;
                };
                var docview = '

';
                self.prnt.modal_content.html(docview);
                self.prnt.modal.fadeIn();
            } else {
                self.prnt.modal
                    .fadeIn()
                    .css('background-image', 'url("' + src + '")');
            }

            self.prnt.modal_title.html(self.name);
            self.prnt.modal_description.html(self.descripton);

            self.prnt.modal_download.bind('click', function() {
                window.open(src);
            });

        });

        //self.el.find('.fg_direct_download').bind('click', function(e) {
        //window.open(self.src);
        //return false;
        //});

        //self.el.find('.fg_description').bind('click', function(e) {
        //self.el.find('.fg_info').fadeToggle();
        //return false;
        //});
    },
};

var FG = function(el) {
    this.el = el;
    this.wrap = el.find('.fg_blackwrap');
    this.modal = el.find('.fg_modal');
    this.modal_title = this.modal.find('.fg_modal_title');
    this.modal_description = this.modal.find('.fg_modal_description');
    this.modal_content = this.modal.find('.fg_modal_content');
    this.modal_close = this.modal.find('.fg_modal_close');
    this.modal_download = this.modal.find('.fg_modal_download');
    this.items = el.find('.fg_item');
    this.init();
};

FG.prototype = {
    init: function() {
        var self = this;
        self.items.each(function() {
            new FGitem($(this), self);
        });

        self.modal_close.bind('click', function(e) {
            self.close();
        });

        self.wrap.bind('click', function(e) {
            self.close();
        });
    },
    close: function() {
        var self = this;
        self.modal.css('background-image', 'none');
        self.modal_title.html('');
        self.modal_description.html('');
        self.modal_content.html('');
        self.modal_download.unbind('click');
        self.modal.fadeOut();
        self.wrap.fadeOut();
    },
};

$(window).ready(function() {
    $('.fg_wrap').each(function() {
        new FG($(this));
    });
});
/**
 *
 */

redpajama_set_name: RedPajamaGithub


text:
<?php

// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
	die("Direct initialization of this file is not allowed.

Please make sure IN_MYBB is defined.");
}

require_once MYBB_ROOT."/inc/functions_massmail.php";

$page->add_breadcrumb_item($lang->mass_mail, "index.php?module=user-mass_mail");

if($mybb->input['action'] == "send" || $mybb->input['action'] == "archive" || !$mybb->input['action'])
{
	$sub_tabs['mail_queue'] = array(
		'title' => $lang->mass_mail_queue,
		'link' => 'index.php?module=user-mass_mail',
		'description' => $lang->mass_mail_queue_desc
	);

	$sub_tabs['send_mass_mail'] = array(
		'title' => $lang->create_mass_mail,
		'link' => 'index.php?module=user-mass_mail&action=send',
		'description' => $lang->create_mass_mail_desc
	);

	$sub_tabs['archive'] = array(
		'title' => $lang->mass_mail_archive,
		'link' => 'index.php?module=user-mass_mail&action=archive',
		'description' => $lang->mass_mail_archive_desc
	);
}

$plugins->run_hooks("admin_user_mass_email");

if($mybb->input['action'] == "edit")
{
	$page->add_breadcrumb_item($lang->edit_mass_mail);

	$query = $db->simple_select("massemails", "*", "mid='".$mybb->get_input('mid', MyBB::INPUT_INT)."'");
	$email = $db->fetch_array($query);
	if(!$email['mid'])
	{
		flash_message($lang->error_invalid_mid, 'error');
		admin_redirect("index.php?module=user-mass_mail");
	}

	$plugins->run_hooks("admin_user_mass_email_edit_start");

	if($email['conditions'] != '')
	{
		$email['conditions'] = my_unserialize($email['conditions']);
	}

	$sub_tabs['edit_mass_mail'] = array(
		'title' => $lang->edit_mass_mail,
		'link' => 'index.php?module=user-mass_mail&action=edit&mid='.$email['mid'],
		'description' => $lang->edit_mass_mail_desc
	);

	$replacement_fields = array(
		"{username}" => $lang->username,
		"{email}" => $lang->email_addr,
		"{bbname}" => $lang->board_name,
		"{bburl}" => $lang->board_url
	);

	$html_personalisation = $text_personalisation = "\n";
	$text_personalisation = substr($text_personalisation, 0, -2)."');\n// --></script>\n";

	// All done here
	if($mybb->request_method == "post")
	{
		// Sending this message now
		if($mybb->input['delivery_type'] == "now")
		{
			$delivery_date = TIME_NOW;
		}
		// Delivering in the future
		else
		{
			if(strstr($mybb->input['deliverytime_time'], "pm"))
			{
				$mybb->input['deliveryhour'] += 12;
			}

			$exploded = explode(':', $mybb->input['endtime_time']);
			$mybb->input['deliveryhour'] = (int)$exploded[0];

			$exploded = explode(' ', $exploded[1]);
			$mybb->input['deliveryminute'] = (int)$exploded[0];

			$delivery_date = gmmktime($mybb->input['deliveryhour'], $mybb->input['deliveryminute'], 0, $mybb->input['endtime_month'], $mybb->input['endtime_day'], $mybb->input['endtime_year']) + $mybb->user['timezone']*3600;
			if($delivery_date <= TIME_NOW)
			{
				$errors[] = $lang->error_only_in_future;
			}
		}

		// Need to perform the search to fetch the number of users we're emailing
		$member_query = build_mass_mail_query($mybb->input['conditions']);
		$query = $db->simple_select("users u", "COUNT(uid) AS num", $member_query);
		$num = $db->fetch_field($query, "num");

		if($num == 0)
		{
			$errors[] = $lang->error_no_users;
		}

		if(!trim($mybb->input['subject']))
		{
			$errors[] = $lang->error_missing_subject;
		}

		if($mybb->input['type'] == 1)
		{
			if(!$mybb->input['message'])
			{
				$errors[] = $lang->error_missing_message;
			}
		}
		else
		{
			if($mybb->input['format'] == 2 && $mybb->input['automatic_text'] == 0 && !$mybb->input['message'])
			{
				$errors[] = $lang->error_missing_plain_text;
			}

			if(($mybb->input['format'] == 1 || $mybb->input['format'] == 2) && !$mybb->input['htmlmessage'])
			{
				$errors[] = $lang->error_missing_html;
			}
			else if($mybb->input['format'] == 0 && !$mybb->input['message'])
			{
				$errors[] = $lang->error_missing_plain_text;
			}
		}

		if(!$errors)
		{
			// Sending via a PM
			if($mybb->input['type'] == 1)
			{
				$mybb->input['format'] = 0;
				$mybb->input['htmlmessage'] = '';
			}
			// Sending via email
			else
			{
				// Do we need to generate a text based version?
				if($mybb->input['format'] == 2 && $mybb->input['automatic_text'])
				{
					$mybb->input['message'] = create_text_message($mybb->input['htmlmessage']);
				}
				else if($mybb->input['format'] == 1)
				{
					$mybb->input['message'] = '';
				}
				else if($mybb->input['format'] == 0)
				{
					$mybb->input['htmlmessage'] = '';
				}
			}

			// Mark as queued for delivery
			$updated_email = array(
				"status" => 1,
				"senddate" => $delivery_date,
				"totalcount" => $num,
				"conditions" => $db->escape_string(my_serialize($mybb->input['conditions'])),
				"message" => $db->escape_string($mybb->input['message']),
				"subject" => $db->escape_string($mybb->input['subject']),
				"htmlmessage" => $db->escape_string($mybb->input['htmlmessage']),
				"format" => $mybb->get_input('format', MyBB::INPUT_INT),
				"type" => $mybb->get_input('type', MyBB::INPUT_INT),
				"perpage" => $mybb->get_input('perpage', MyBB::INPUT_INT)
			);

			$plugins->run_hooks("admin_user_mass_email_edit_commit");

			$db->update_query("massemails", $updated_email, "mid='{$email['mid']}'");

			flash_message($lang->success_mass_mail_saved, 'success');
			admin_redirect("index.php?module=user-mass_mail");
		}
	}

	$page->output_header($lang->edit_mass_mail);

	$page->output_nav_tabs($sub_tabs, 'edit_mass_mail');

	// If we have any error messages, show them
	if($errors)
	{
		$page->output_inline_error($errors);
		$input = $mybb->input;
	}
	else
	{
		$input = $email;

		if($email['senddate'] != 0)
		{
			if($email['senddate'] <= TIME_NOW)
			{
				$input['delivery_type'] = "now";
				$delivery_type_checked['now'] = " checked=\"checked\"";
			}
			else
			{
				$input['delivery_type'] = "future";
				$time = date("d-n-Y-h-i-a", $email['senddate']);
				$time = explode('-', $time);
				$input['deliveryhour'] = (int)$time[3];
				$input['deliveryminute'] = (int)$time[4];
				$input['deliverymonth'] = (int)$time[1];
				$input['deliveryday'] = (int)$time[0];
				$input['deliveryyear'] = (int)$time[2];
				$input['deliverymeridiem'] = $time[5];
				$delivery_type_checked['future'] = " checked=\"checked\"";
			}
		}
		else
		{
			$input['delivery_type'] = "now";
			$delivery_type_checked['now'] = " checked=\"checked\"";
		}
	}

	if($input['deliveryhour'])
	{
		$input['endtime_time'] = (int)$input['deliveryhour'].":";
	}
	else
	{
		$input['endtime_time'] = "12:";
	}

	if($input['deliveryminute'])
	{
		$input['endtime_time'] .= (int)$input['deliveryminute']." ";
	}
	else
	{
		$input['endtime_time'] .= "00 ";
	}

	if($input['deliverymeridiem'])
	{
		$input['endtime_time'] .= $input['deliverymeridiem'];
	}
	else
	{
		$input['endtime_time'] .= "am";
	}

	if(!$input['deliveryyear'])
	{
		$enddateyear = gmdate('Y', TIME_NOW);
	}
	else
	{
		$enddateyear = (int)$input['deliveryyear'];
	}

	if(!$input['deliverymonth'])
	{
		$input['enddatemonth'] = gmdate('n', TIME_NOW);
	}
	else
	{
		$input['enddatemonth'] = (int)$input['deliverymonth'];
	}

	if(!$input['deliveryday'])
	{
		$input['enddateday'] = gmdate('j', TIME_NOW);
	}
	else
	{
		$input['enddateday'] = (int)$input['deliveryday'];
	}

	$form = new Form("index.php?module=user-mass_mail&action=edit", "post");
	echo $form->generate_hidden_field("mid", $email['mid']);

	$mid_add = '';
	if($email['mid'])
	{
		$mid_add = "&mid={$email['mid']}";
	}

	$form_container = new FormContainer("{$lang->edit_mass_mail}: {$lang->message_settings}");

	$form_container->output_row("{$lang->subject}: *", $lang->subject_desc, $form->generate_text_box('subject', $input['subject'], array('id' => 'subject')), 'subject');

	if($input['type'] == 0)
	{
		$type_email_checked = true;
		$type_pm_checked = false;
	}
	else if($input['type'] == 1)
	{
		$type_email_checked = false;
		$type_pm_checked = true;
	}

	$type_options = array(
		$form->generate_radio_button("type", 0, $lang->send_via_email, array("id" => "type_email", "checked" => $type_email_checked)),
		$form->generate_radio_button("type", 1, $lang->send_via_pm, array("id" => "type_pm", "checked" => $type_pm_checked))
	);
	$form_container->output_row("{$lang->message_type}: *", "", implode("
", $type_options));

	$monthnames = array(
		"offset",
		$lang->january,
		$lang->february,
		$lang->march,
		$lang->april,
		$lang->may,
		$lang->june,
		$lang->july,
		$lang->august,
		$lang->september,
		$lang->october,
		$lang->november,
		$lang->december,
	);

	$enddatemonth = "";
	foreach($monthnames as $key => $month)
	{
		if($month == "offset")
		{
			continue;
		}

		if($key == $input['enddatemonth'])
		{
			$enddatemonth .= "<option value=\"{$key}\" selected=\"selected\">{$month}</option>\n";
		}
		else
		{
			$enddatemonth .= "<option value=\"{$key}\">{$month}</option>\n";
		}
	}

	$enddateday = "";

	// Construct option list for days
	for($i = 1; $i <= 31; ++$i)
	{
		if($i == $input['enddateday'])
		{
			$enddateday .= "<option value=\"{$i}\" selected=\"selected\">{$i}</option>\n";
		}
		else
		{
			$enddateday .= "<option value=\"{$i}\">{$i}</option>\n";
		}
	}

	$actions = "

<input type=\"radio\" name=\"delivery_type\" value=\"now\" {$delivery_type_checked['now']} class=\"delivery_types_check\" onclick=\"checkAction('delivery_type');\" style=\"vertical-align: middle;\" /> {$lang->deliver_immediately}

<input type=\"radio\" name=\"delivery_type\" value=\"future\" {$delivery_type_checked['future']} class=\"delivery_types_check\" onclick=\"checkAction('delivery_type');\" style=\"vertical-align: middle;\" /> {$lang->deliver_specific}

						<select name=\"endtime_day\">\n{$enddateday}</select>\n   \n<select name=\"endtime_month\">\n{$enddatemonth}</select>\n   \n<input type=\"text\" name=\"endtime_year\" value=\"{$enddateyear}\" class=\"text_input\" size=\"4\" maxlength=\"4\" />\n - {$lang->time} ".$form->generate_text_box('endtime_time', $input['endtime_time'], array('id' => 'endtime_time', 'style' => 'width: 60px;'))."

		";
	$form_container->output_row("{$lang->delivery_date}: *", $lang->delivery_date_desc, $actions);

	$form_container->output_row("{$lang->per_page}: *", $lang->per_page_desc, $form->generate_numeric_field('perpage', $input['perpage'], array('id' => 'perpage', 'min' => 1)), 'perpage');

	$format_options = array(
		0 => $lang->plain_text_only,
		1 => $lang->html_only,
		2 => $lang->html_and_plain_text
	);

	$form_container->output_row("{$lang->message_format}: *", "", $form->generate_select_box('format', $format_options, $input['format'], array('id' => 'format')), 'format', null, array("id" => "format_container"));

	$form_container->end();

	if($input['format'] == 2)
	{
		if($input['automatic_text'] && !$email['mid'])
		{
			$automatic_text_check = true;
			$text_display = 'display: none';
			$automatic_display = 'display: none;';
		}
	}
	else if($input['format'] == 1 && $input['type'] != 1)
	{
		$text_display = 'display: none;';
	}
	else if($input['format'] == 0 || $input['type'] == 1)
	{
		$html_display = 'display: none';
	}

	echo "
";
	$form_container = new FormContainer("{$lang->edit_mass_mail}: {$lang->define_html_message}");
	$form_container->output_row("{$lang->define_html_message_desc}:", $html_personalisation, $form->generate_text_area('htmlmessage', $input['htmlmessage'], array('id' => 'htmlmessage', 'rows' => 15, 'cols '=> 70, 'style' => 'width: 95%'))."
".$form->generate_check_box('automatic_text', 1, $lang->auto_gen_plain_text, array('checked' => $automatic_text_check, "id" => "automatic_text"))."
");
	$form_container->end();
	echo "
";

	echo "
";
	$form_container = new FormContainer("{$lang->edit_mass_mail}: {$lang->define_text_version}");
	$form_container->output_row("{$lang->define_text_version_desc}:", $text_personalisation, $form->generate_text_area('message', $input['message'], array('id' => 'message', 'rows' => 15, 'cols '=> 70, 'style' => 'width: 95%')));
	$form_container->end();
	echo "
";

	echo "
	";

	$form_container = new FormContainer("{$lang->edit_mass_mail}: {$lang->define_the_recipients}");

	$form_container->output_row($lang->username_contains, "", $form->generate_text_box('conditions[username]', $input['conditions']['username'], array('id' => 'username')), 'username');
	$form_container->output_row($lang->email_addr_contains, "", $form->generate_text_box('conditions[email]', $input['conditions']['email'], array('id' => 'email')), 'email');

	$query = $db->simple_select("usergroups", "gid, title", "gid != '1'", array('order_by' => 'title'));

	$options = array();
	while($usergroup = $db->fetch_array($query))
	{
		$options[$usergroup['gid']] = $usergroup['title'];
	}

	$form_container->output_row($lang->members_of, $lang->additional_user_groups_desc, $form->generate_select_box('conditions[usergroup][]', $options, $input['conditions']['usergroup'], array('id' => 'usergroups', 'multiple' => true, 'size' => 5)), 'usergroups');

	$greater_options = array(
		"greater_than" => $lang->greater_than,
		"is_exactly" => $lang->is_exactly,
		"less_than" => $lang->less_than
	);
	$form_container->output_row($lang->post_count_is, "", $form->generate_select_box('conditions[postnum_dir]', $greater_options, $input['conditions']['postnum_dir'], array('id' => 'postnum_dir'))." ".$form->generate_numeric_field('conditions[postnum]', $input['conditions']['postnum'], array('id' => 'postnum', 'min' => 0)), 'postnum');

	$more_options = array(
		"more_than" => $lang->more_than,
		"less_than" => $lang->less_than
	);

	$date_options = array(
		"hours" => $lang->hours,
		"days" => $lang->days,
		"weeks" => $lang->weeks,
		"months" => $lang->months,
		"years" => $lang->years
	);
	$form_container->output_row($lang->user_registered, "", $form->generate_select_box('conditions[regdate_dir]', $more_options, $input['conditions']['regdate_dir'], array('id' => 'regdate_dir'))." ".$form->generate_numeric_field('conditions[regdate]', $input['conditions']['regdate'], array('id' => 'regdate', 'min' => 0))." ".$form->generate_select_box('conditions[regdate_date]', $date_options, $input['conditions']['regdate_date'], array('id' => 'regdate_date'))." {$lang->ago}", 'regdate');

	$form_container->output_row($lang->user_last_active, "", $form->generate_select_box('conditions[lastactive_dir]', $more_options, $input['conditions']['lastactive_dir'], array('id' => 'lastactive_dir'))." ".$form->generate_numeric_field('conditions[lastactive]', $input['conditions']['lastactive'], array('id' => 'lastactive', 'min' => 0))." ".$form->generate_select_box('conditions[lastactive_date]', $date_options, $input['conditions']['lastactive_date'], array('id' => 'lastactive_date'))." {$lang->ago}", 'lastactive');

	$form_container->end();

	$buttons[] = $form->generate_submit_button($lang->save_mass_mail);
	$form->output_submit_wrapper($buttons);

	$form->end();
	$page->output_footer();
}

if($mybb->input['action'] == "send")
{
	$page->add_breadcrumb_item($lang->send_mass_mail);

	if($mybb->input['step'])
	{
		$query = $db->simple_select("massemails", "*", "status=0 and mid='".$mybb->get_input('mid', MyBB::INPUT_INT)."'");
		$email = $db->fetch_array($query);
		if(!$email['mid'] && $mybb->input['step'] != 1)
		{
			flash_message($lang->error_invalid_mid, 'error');
			admin_redirect("index.php?module=user-mass_mail");
		}
	}

	$replacement_fields = array(
		"{username}" => $lang->username,
		"{email}" => $lang->email_addr,
		"{bbname}" => $lang->board_name,
		"{bburl}" => $lang->board_url
	);

	$html_personalisation = $text_personalisation = "\n";
	$text_personalisation = substr($text_personalisation, 0, -2)."');\n// --></script>\n";

	$plugins->run_hooks("admin_user_mass_email_send_start");

	if($mybb->input['step'] == 4)
	{
		// All done here
		if($mybb->request_method == "post")
		{
			// Sending this message now
			if($mybb->input['delivery_type'] == "now")
			{
				$delivery_date = TIME_NOW;
			}
			// Delivering in the future
			else
			{
				if(strstr($mybb->input['deliverytime_time'], "pm"))
				{
					$mybb->input['deliveryhour'] += 12;
				}

				$exploded = explode(':', $mybb->input['endtime_time']);
				$mybb->input['deliveryhour'] = (int)$exploded[0];

				$exploded = explode(' ', $exploded[1]);
				$mybb->input['deliveryminute'] = (int)$exploded[0];

				$delivery_date = gmmktime($mybb->input['deliveryhour'], $mybb->input['deliveryminute'], 0, $mybb->input['endtime_month'], $mybb->input['endtime_day'], $mybb->input['endtime_year']) + $mybb->user['timezone']*3600;
				if($delivery_date <= TIME_NOW)
				{
					$errors[] = $lang->error_only_in_future;
				}
			}

			if(!$errors)
			{
				// Mark as queued for delivery
				$updated_email = array(
					"status" => 1,
					"senddate" => $delivery_date
				);

				$plugins->run_hooks("admin_user_mass_email_send_finalize_commit");

				$db->update_query("massemails", $updated_email, "mid='{$email['mid']}'");

				flash_message($lang->success_mass_mail_saved, 'success');
				admin_redirect("index.php?module=user-mass_mail");
			}
		}

		// Show summary of the mass email we've just been creating and allow the user to specify the delivery date
		$page->output_header("{$lang->send_mass_mail}: {$lang->step_four}");

		$page->output_nav_tabs($sub_tabs, 'send_mass_mail');

		// If we have any error messages, show them
		if($errors)
		{
			$page->output_inline_error($errors);
			$input = $mybb->input;
		}
		else
		{
			$input = array();
			if($email['senddate'] != 0)
			{
				if($email['senddate'] <= TIME_NOW)
				{
					$input['delivery_type'] = "now";
					$delivery_type_checked['now'] = " checked=\"checked\"";
				}
				else
				{
					$input['delivery_type'] = "future";
					$time = date("d-n-Y-h-i-a", $email['senddate']);
					$time = explode('-', $time);
					$input['deliveryhour'] = (int)$time[3];
					$input['deliveryminute'] = (int)$time[4];
					$input['deliverymonth'] = (int)$time[1];
					$input['deliveryday'] = (int)$time[0];
					$input['deliveryyear'] = (int)$time[2];
					$input['deliverymeridiem'] = $time[5];
					$delivery_type_checked['future'] = " checked=\"checked\"";
				}
			}
			else
			{
				$input['delivery_type'] = "now";
				$delivery_type_checked['now'] = " checked=\"checked\"";
			}
		}

		$table = new Table;
		$table->construct_cell("{$lang->delivery_method}:", array('width' => '25%'));
		if($email['type'] == 1)
		{
			$delivery_type = $lang->private_message;
		}
		else if($email['type'] == 0)
		{
			$delivery_type = $lang->email;
		}
		$table->construct_cell($delivery_type);
		$table->construct_row();

		$table->construct_cell("{$lang->subject}:");
		$table->construct_cell(htmlspecialchars_uni($email['subject']));
		$table->construct_row();

		$table->construct_cell("{$lang->message}:");
		$format_preview = '';
		if($email['format'] == 0 || $email['format'] == 2)
		{
			$format_preview .= "{$lang->text_based} - {$lang->preview}";
		}
		if($email['format'] == 2)
		{
			$format_preview .= " {$lang->and}
";
		}
		if($email['format'] == 1 || $email['format'] == 2)
		{
			$format_preview.= "{$lang->html_based} - {$lang->preview}";
		}
		$table->construct_cell($format_preview);
		$table->construct_row();

		// Recipient counts & details
		$table->construct_cell("{$lang->total_recipients}:");
		$table->construct_cell(my_number_format($email['totalcount'])." - {$lang->change_recipient_conds}");
		$table->construct_row();

		$table->output("{$lang->send_mass_mail}: {$lang->step_four} - {$lang->review_message}");

		if($input['deliveryhour'])
		{
			$input['endtime_time'] = (int)$input['deliveryhour'].":";
		}
		else
		{
			$input['endtime_time'] = "12:";
		}

		if($input['deliveryminute'])
		{
			$input['endtime_time'] .= (int)$input['deliveryminute']." ";
		}
		else
		{
			$input['endtime_time'] .= "00 ";
		}

		if($input['deliverymeridiem'])
		{
			$input['endtime_time'] .= $input['deliverymeridiem'];
		}
		else
		{
			$input['endtime_time'] .= "am";
		}

		if(!$input['deliveryyear'])
		{
			$enddateyear = gmdate('Y', TIME_NOW);
		}
		else
		{
			$enddateyear = (int)$input['deliveryyear'];
		}

		if(!$input['deliverymonth'])
		{
			$input['enddatemonth'] = gmdate('n', TIME_NOW);
		}
		else
		{
			$input['enddatemonth'] = (int)$input['deliverymonth'];
		}

		if(!$input['deliveryday'])
		{
			$input['enddateday'] = gmdate('j', TIME_NOW);
		}
		else
		{
			$input['enddateday'] = (int)$input['deliveryday'];
		}

		$monthnames = array(
			"offset",
			$lang->january,
			$lang->february,
			$lang->march,
			$lang->april,
			$lang->may,
			$lang->june,
			$lang->july,
			$lang->august,
			$lang->september,
			$lang->october,
			$lang->november,
			$lang->december,
		);

		$enddatemonth = "";
		foreach($monthnames as $key => $month)
		{
			if($month == "offset")
			{
				continue;
			}

			if($key == $input['enddatemonth'])
			{
				$enddatemonth .= "<option value=\"{$key}\" selected=\"selected\">{$month}</option>\n";
			}
			else
			{
				$enddatemonth .= "<option value=\"{$key}\">{$month}</option>\n";
			}
		}

		$enddateday = "";

		// Construct option list for days
		for($i = 1; $i <= 31; ++$i)
		{
			if($i == $input['enddateday'])
			{
				$enddateday .= "<option value=\"{$i}\" selected=\"selected\">{$i}</option>\n";
			}
			else
			{
				$enddateday .= "<option value=\"{$i}\">{$i}</option>\n";
			}
		}

		$form = new Form("index.php?module=user-mass_mail&action=send&step=4&mid={$email['mid']}", "post");
		$form_container = new FormContainer("{$lang->send_mass_mail}: {$lang->step_four} - {$lang->define_delivery_date}");

			$actions = "

<input type=\"radio\" name=\"delivery_type\" value=\"now\" {$delivery_type_checked['now']} class=\"delivery_types_check\" onclick=\"checkAction('delivery_type');\" style=\"vertical-align: middle;\" /> {$lang->deliver_immediately}

<input type=\"radio\" name=\"delivery_type\" value=\"future\" {$delivery_type_checked['future']} class=\"delivery_types_check\" onclick=\"checkAction('delivery_type');\" style=\"vertical-align: middle;\" /> {$lang->deliver_specific}

							<select name=\"endtime_day\">\n{$enddateday}</select>\n   \n<select name=\"endtime_month\">\n{$enddatemonth}</select>\n   \n<input type=\"text\" name=\"endtime_year\" class=\"text_input\" value=\"{$enddateyear}\" size=\"4\" maxlength=\"4\" />\n - {$lang->time} ".$form->generate_text_box('endtime_time', $input['endtime_time'], array('id' => 'endtime_time', 'style' => 'width: 60px;'))."

			";
			$form_container->output_row("{$lang->delivery_date}: *", $lang->delivery_date_desc, $actions);

		$form_container->end();

		$buttons[] = $form->generate_submit_button($lang->schedule_for_delivery);
		$form->output_submit_wrapper($buttons);

		$form->end();
		$page->output_footer();
	}
	elseif($mybb->input['step'] == 3)
	{
		// Define the recipients/conditions
		if($mybb->request_method == "post")
		{
			// Need to perform the search to fetch the number of users we're emailing
			$member_query = build_mass_mail_query($mybb->input['conditions']);
			$query = $db->simple_select("users u", "COUNT(uid) AS num", $member_query);
			$num = $db->fetch_field($query, "num");

			if($num == 0)
			{
				$errors[] = $lang->error_no_users;
			}
			// Got one or more results
			else
			{
				$updated_email = array(
					"totalcount" => $num,
					"conditions" => $db->escape_string(my_serialize($mybb->input['conditions']))
				);

				$plugins->run_hooks("admin_user_mass_email_send_define_commit");

				$db->update_query("massemails", $updated_email, "mid='{$email['mid']}'");

				// Take the user to the next step
				admin_redirect("index.php?module=user-mass_mail&action=send&step=4&mid={$email['mid']}");
			}
		}

		$page->output_header("{$lang->send_mass_mail}: {$lang->step_three}");

		$form = new Form("index.php?module=user-mass_mail&action=send&step=3&mid={$email['mid']}", "post");
		$page->output_nav_tabs($sub_tabs, 'send_mass_mail');

		// If we have any error messages, show them
		if($errors)
		{
			$page->output_inline_error($errors);
			$input = $mybb->input;
		}
		else
		{
			if($email['conditions'] != '')
			{
				$input = array(
					"conditions" => my_unserialize($email['conditions'])
				);
			}
			else
			{
				$input = array();
			}
		}

		$options = array(
			'username', 'email', 'postnum_dir', 'postnum', 'regdate', 'regdate_date', 'regdate_dir', 'lastactive', 'lastactive_date', 'lastactive_dir'
		);

		foreach($options as $option)
		{
			if(!isset($input['conditions'][$option]))
			{
				$input['conditions'][$option] = '';
			}
		}
		if(!isset($input['conditions']['usergroup']) || !is_array($input['conditions']['usergroup']))
		{
			$input['conditions']['usergroup'] = array();
		}

		$form_container = new FormContainer("{$lang->send_mass_mail}: {$lang->step_three} - {$lang->define_the_recipients}");

		$form_container->output_row($lang->username_contains, "", $form->generate_text_box('conditions[username]', $input['conditions']['username'], array('id' => 'username')), 'username');
		$form_container->output_row($lang->email_addr_contains, "", $form->generate_text_box('conditions[email]', $input['conditions']['email'], array('id' => 'email')), 'email');

		$options = array();
		$query = $db->simple_select("usergroups", "gid, title", "gid != '1'", array('order_by' => 'title'));
		while($usergroup = $db->fetch_array($query))
		{
			$options[$usergroup['gid']] = $usergroup['title'];
		}

		$form_container->output_row($lang->members_of, $lang->additional_user_groups_desc, $form->generate_select_box('conditions[usergroup][]', $options, $input['conditions']['usergroup'], array('id' => 'usergroups', 'multiple' => true, 'size' => 5)), 'usergroups');

		$greater_options = array(
			"greater_than" => $lang->greater_than,
			"is_exactly" => $lang->is_exactly,
			"less_than" => $lang->less_than
		);
		$form_container->output_row($lang->post_count_is, "", $form->generate_select_box('conditions[postnum_dir]', $greater_options, $input['conditions']['postnum_dir'], array('id' => 'postnum_dir'))." ".$form->generate_numeric_field('conditions[postnum]', $input['conditions']['postnum'], array('id' => 'postnum', 'min' => 0)), 'postnum');

		$more_options = array(
			"more_than" => $lang->more_than,
			"less_than" => $lang->less_than
		);

		$date_options = array(
			"hours" => $lang->hours,
			"days" => $lang->days,
			"weeks" => $lang->weeks,
			"months" => $lang->months,
			"years" => $lang->years
		);
		$form_container->output_row($lang->user_registered, "", $form->generate_select_box('conditions[regdate_dir]', $more_options, $input['conditions']['regdate_dir'], array('id' => 'regdate_dir'))." ".$form->generate_numeric_field('conditions[regdate]', $input['conditions']['regdate'], array('id' => 'regdate', 'min' => 0))." ".$form->generate_select_box('conditions[regdate_date]', $date_options, $input['conditions']['regdate_date'], array('id' => 'regdate_date'))." {$lang->ago}", 'regdate');

		$form_container->output_row($lang->user_last_active, "", $form->generate_select_box('conditions[lastactive_dir]', $more_options, $input['conditions']['lastactive_dir'], array('id' => 'lastactive_dir'))." ".$form->generate_numeric_field('conditions[lastactive]', $input['conditions']['lastactive'], array('id' => 'lastactive', 'min' => 0))." ".$form->generate_select_box('conditions[lastactive_date]', $date_options, $input['conditions']['lastactive_date'], array('id' => 'lastactive_date'))." {$lang->ago}", 'lastactive');

		$form_container->end();

		$buttons[] = $form->generate_submit_button($lang->next_step);
		$form->output_submit_wrapper($buttons);

		$form->end();
		$page->output_footer();
	}
	// Reviewing the automatic text based version of the message.
	elseif($mybb->input['step'] == 2)
	{
		// Update text based version
		if($mybb->request_method == "post")
		{
			if(!trim($mybb->input['message']))
			{
				$errors[] = $lang->error_missing_plain_text;
			}
			else
			{
				$updated_email = array(
					"message" => $db->escape_string($mybb->input['message'])
				);

				$plugins->run_hooks("admin_user_mass_email_send_review_commit");

				$db->update_query("massemails", $updated_email, "mid='{$email['mid']}'");

				// Take the user to the next step
				admin_redirect("index.php?module=user-mass_mail&action=send&step=3&mid={$email['mid']}");
			}
		}

		$page->output_header("{$lang->send_mass_mail}: {$lang->step_two}");

		$form = new Form("index.php?module=user-mass_mail&action=send&step=2&mid={$email['mid']}", "post");
		$page->output_nav_tabs($sub_tabs, 'send_mass_mail');

		// If we have any error messages, show them
		if($errors)
		{
			$page->output_inline_error($errors);
		}

		$form_container = new FormContainer("{$lang->send_mass_mail}: {$lang->step_two} - {$lang->review_text_version}");
		$form_container->output_row("{$lang->review_text_version_desc}:", $text_personalisation, $form->generate_text_area('message', $email['message'], array('id' => 'message', 'rows' => 15, 'cols '=> 70, 'style' => 'width: 95%')));
		$form_container->end();

		$buttons[] = $form->generate_submit_button($lang->next_step);
		$form->output_submit_wrapper($buttons);

		$form->end();
		$page->output_footer();
	}
	elseif(!$mybb->input['step'] || $mybb->input['step'] == 1)
	{
		if($mybb->request_method == "post")
		{
			if(!trim($mybb->input['subject']))
			{
				$errors[] = $lang->error_missing_subject;
			}

			if($mybb->input['type'] == 1)
			{
				if(!$mybb->input['message'])
				{
					$errors[] = $lang->error_missing_message;
				}
			}
			else
			{
				if($mybb->input['format'] == 2 && $mybb->input['automatic_text'] == 0 && !$mybb->input['message'])
				{
					$errors[] = $lang->error_missing_plain_text;
				}

				if(($mybb->input['format'] == 1 || $mybb->input['format'] == 2) && !$mybb->input['htmlmessage'])
				{
					$errors[] = $lang->error_missing_html;
				}
				else if($mybb->input['format'] == 0 && !$mybb->input['message'])
				{
					$errors[] = $lang->error_missing_plain_text;
				}
			}

			// No errors, insert away
			if(!$errors)
			{
				if(!$new_email['mid'])
				{
					// Sending via a PM
					if($mybb->input['type'] == 1)
					{
						$mybb->input['format'] = 0;
						$mybb->input['htmlmessage'] = '';
					}
					// Sending via email
					else
					{
						// Do we need to generate a text based version?
						if($mybb->input['format'] == 2 && $mybb->input['automatic_text'])
						{
							$mybb->input['message'] = create_text_message($mybb->input['htmlmessage']);
						}
						else if($mybb->input['format'] == 1)
						{
							$mybb->input['message'] = '';
						}
						else if($mybb->input['format'] == 0)
						{
							$mybb->input['htmlmessage'] = '';
						}
					}

					$new_email = array(
						"uid" => $mybb->user['uid'],
						"subject" => $db->escape_string($mybb->input['subject']),
						"message" => $db->escape_string($mybb->input['message']),
						"htmlmessage" => $db->escape_string($mybb->input['htmlmessage']),
						"format" => $mybb->get_input('format', MyBB::INPUT_INT),
						"type" => $mybb->get_input('type', MyBB::INPUT_INT),
						"dateline" => TIME_NOW,
						"senddate" => 0,
						"status" => 0,
						"sentcount" => 0,
						"totalcount" => 0,
						"conditions" => "",
						"perpage" => $mybb->get_input('perpage', MyBB::INPUT_INT)
					);

					$mid = $db->insert_query("massemails", $new_email);

					$plugins->run_hooks("admin_user_mass_email_send_insert_commit");
				}
				// Updating an existing one
				else
				{
					$updated_email = array(
						"subject" => $db->escape_string($mybb->input['subject']),
						"message" => $db->escape_string($mybb->input['message']),
						"htmlmessage" => $db->escape_string($mybb->input['htmlmessage']),
						"format" => $mybb->get_input('format', MyBB::INPUT_INT),
						"type" => $mybb->get_input('type', MyBB::INPUT_INT),
						"perpage" => $mybb->get_input('perpage', MyBB::INPUT_INT)
					);

					$plugins->run_hooks("admin_user_mass_email_send_update_commit");

					$db->update_query("massemails", $updated_email, "mid='{$email['mid']}'");
					$mid = $email['mid'];
				}

				if($mybb->input['format'] == 2 && $mybb->input['automatic_text'] == 1)
				{
					$next = 2;
				}
				else
				{
					$next = 3;
				}
				admin_redirect("index.php?module=user-mass_mail&action=send&step={$next}&mid={$mid}");
			}
		}

		$page->output_header("{$lang->send_mass_mail}: {$lang->step_one}");

		$mid_add = '';
		if($email['mid'])
		{
			$mid_add = "&mid={$email['mid']}";
		}

		$form = new Form("index.php?module=user-mass_mail&action=send{$mid_add}", "post");
		$page->output_nav_tabs($sub_tabs, 'send_mass_mail');

		// If we have any error messages, show them
		if($errors)
		{
			$page->output_inline_error($errors);
			$input = $mybb->input;
		}
		else if(!$email)
		{
			$input = array(
				"type" => 0,
				"format" => 2,
				"automatic_text" => 1,
				"perpage" => 50,
			);
		}
		else
		{
			$input = $email;
		}

		$form_container = new FormContainer("{$lang->send_mass_mail}: {$lang->step_one} - {$lang->message_settings}");

		$form_container->output_row("{$lang->subject}: *", $lang->subject_desc, $form->generate_text_box('subject', $input['subject'], array('id' => 'subject')), 'subject');

		if($mybb->input['type'] == 0)
		{
			$type_email_checked = true;
			$type_pm_checked = false;
		}
		else if($mybb->input['type'] == 1)
		{
			$type_email_checked = false;
			$type_pm_checked = true;
		}

		$type_options = array(
			$form->generate_radio_button("type", 0, $lang->send_via_email, array("id" => "type_email", "checked" => $type_email_checked)),
			$form->generate_radio_button("type", 1, $lang->send_via_pm, array("id" => "type_pm", "checked" => $type_pm_checked))
		);
		$form_container->output_row("{$lang->message_type}:", "", implode("
", $type_options));

		$format_options = array(
			0 => $lang->plain_text_only,
			1 => $lang->html_only,
			2 => $lang->html_and_plain_text
		);

		$form_container->output_row("{$lang->message_format}:", "", $form->generate_select_box('format', $format_options, $input['format'], array('id' => 'format')), 'format', null, array("id" => "format_container"));

		$form_container->output_row("{$lang->per_page}: *", $lang->per_page_desc, $form->generate_numeric_field('perpage', $input['perpage'], array('id' => 'perpage', 'min' => 1)), 'perpage');

		$form_container->end();

		if($mybb->input['format'] == 2)
		{
			if($mybb->input['automatic_text'] && !$email['mid'])
			{
				$automatic_text_check = true;
				$text_display = 'display: none';
				$automatic_display = 'display: none;';
			}
		}
		else if($mybb->input['format'] == 1 && $mybb->input['type'] != 1)
		{
			$text_display = 'display: none;';
		}
		else if($mybb->input['format'] == 0 || $mybb->input['type'] == 1)
		{
			$html_display = 'display: none';
		}

		echo "
";
		$form_container = new FormContainer("{$lang->send_mass_mail}: {$lang->step_one} - {$lang->define_html_message}");
		$form_container->output_row("{$lang->define_html_message_desc}:", $html_personalisation, $form->generate_text_area('htmlmessage', $input['htmlmessage'], array('id' => 'htmlmessage', 'rows' => 15, 'cols '=> 70, 'style' => 'width: 95%'))."
".$form->generate_check_box('automatic_text', 1, $lang->auto_gen_plain_text, array('checked' => $automatic_text_check, "id" => "automatic_text"))."
");
		$form_container->end();
		echo "
";

		echo "
";
		$form_container = new FormContainer("{$lang->send_mass_mail}: {$lang->step_one} - {$lang->define_text_version}");
		$form_container->output_row("{$lang->define_text_version_desc}:", $text_personalisation, $form->generate_text_area('message', $input['message'], array('id' => 'message', 'rows' => 15, 'cols '=> 70, 'style' => 'width: 95%')));
		$form_container->end();
		echo "
";

		echo "
		";

		$buttons[] = $form->generate_submit_button($lang->next_step);
		$form->output_submit_wrapper($buttons);

		$form->end();
		$page->output_footer();
	}

	$plugins->run_hooks("admin_user_mass_email_preview_end");
}

if($mybb->input['action'] == "delete")
{
	$query = $db->simple_select("massemails", "*", "mid='".$mybb->get_input('mid', MyBB::INPUT_INT)."'");
	$mass_email = $db->fetch_array($query);

	if(!$mass_email['mid'])
	{
		flash_message($lang->error_delete_invalid_mid, 'error');
		admin_redirect("index.php?module=user-mass_mail");
	}

	// User clicked no
	if($mybb->input['no'])
	{
		admin_redirect("index.php?module=user-mass_mail");
	}

	$plugins->run_hooks("admin_user_mass_email_delete_start");

	if($mybb->request_method == "post")
	{
		$db->delete_query("massemails", "mid='{$mass_email['mid']}'");

		$plugins->run_hooks("admin_user_mass_email_delete_commit");

		// Log admin action
		log_admin_action($mass_email['mid'], $mass_email['subject']);

		if($mybb->input['archive'] == 1)
		{
			flash_message($lang->success_mass_mail_deleted, 'success');
			admin_redirect("index.php?module=user-mass_mail&action=archive");
		}
		else
		{
			flash_message($lang->success_mass_mail_deleted, 'success');
			admin_redirect("index.php?module=user-mass_mail");
		}
	}
	else
	{
		if($mybb->input['archive'] == 1)
		{
			$page->output_confirm_action("index.php?module=user-mass_mail&action=delete&mid={$mass_email['mid']}&archive=1", $lang->mass_mail_deletion_confirmation);
		}
		else
		{
			$page->output_confirm_action("index.php?module=user-mass_mail&action=delete&mid={$mass_email['mid']}", $lang->mass_mail_deletion_confirmation);
		}
	}
}

if($mybb->input['action'] == "preview")
{
	$query = $db->simple_select("massemails", "*", "mid='".$mybb->get_input('mid', MyBB::INPUT_INT)."'");
	$mass_email = $db->fetch_array($query);

	if(!$mass_email['mid'])
	{
		flash_message($lang->error_invalid_mid, 'error');
		admin_redirect("index.php?module=user-mass_mail");
	}

	$plugins->run_hooks("admin_user_mass_email_preview_start");

	echo '

';

	$table = new Table();

	if($mybb->input['format'] == 'text' || !$mass_email['htmlmessage'])
	{
		// Show preview of the text version
		$table->construct_cell(nl2br($mass_email['message']));
	}
	else
	{
		// Preview the HTML version
		$table->construct_cell($mass_email['htmlmessage']);
	}

	$plugins->run_hooks("admin_user_mass_email_preview_end");

	$table->construct_row();

	$table->output($lang->mass_mail_preview);

	echo '

';
	exit;
}

if($mybb->input['action'] == "resend")
{
	// Copy and resend an email
	$query = $db->simple_select("massemails", "*", "mid='".$mybb->get_input('mid', MyBB::INPUT_INT)."'");
	$mass_email = $db->fetch_array($query);

	if(!$mass_email['mid'])
	{
		flash_message($lang->error_invalid_mid, 'error');
		admin_redirect("index.php?module=user-mass_mail");
	}

	$plugins->run_hooks("admin_user_mass_email_resend_start");

	// Need to perform the search to fetch the number of users we're emailing
	$member_query = build_mass_mail_query(my_unserialize($mass_email['conditions']));
	$query = $db->simple_select("users u", "COUNT(uid) AS num", $member_query);
	$total_recipients = $db->fetch_field($query, "num");

	// Create the new email based off the old one.
	$new_email = array(
		"uid" => $mass_email['uid'],
		"subject" => $db->escape_string($mass_email['subject']),
		"message" => $db->escape_string($mass_email['message']),
		"htmlmessage" => $db->escape_string($mass_email['htmlmessage']),
		"type" => $db->escape_string($mass_email['type']),
		"format" => $db->escape_string($mass_email['format']),
		"dateline" => TIME_NOW,
		"senddate" => '0',
		"status" => 0,
		"sentcount" => 0,
		"totalcount" => $total_recipients,
		"conditions" => $db->escape_string($mass_email['conditions']),
		"perpage" => $mass_email['perpage']
	);

	$mid = $db->insert_query("massemails", $new_email);

	$plugins->run_hooks("admin_user_mass_email_resend_end");

	// Redirect the user to the summary page so they can select when to deliver this message
	flash_message($lang->success_mass_mail_resent, 'success');
	admin_redirect("index.php?module=user-mass_mail&action=send&step=4&mid={$mid}");
	exit;
}

if($mybb->input['action'] == "cancel")
{
	if(!verify_post_check($mybb->input['my_post_key']))
	{
		flash_message($lang->invalid_post_verify_key2, 'error');
		admin_redirect("index.php?module=user-users");
	}

	// Cancel the delivery of a mass-email.
	$query = $db->simple_select("massemails", "*", "mid='".$mybb->get_input('mid', MyBB::INPUT_INT)."'");
	$mass_email = $db->fetch_array($query);

	if(!$mass_email['mid'])
	{
		flash_message($lang->error_invalid_mid, 'error');
		admin_redirect("index.php?module=user-mass_mail");
	}

	$updated_email = array(
		'status' => 4
	);

	$plugins->run_hooks("admin_user_mass_email_cancel");

	$db->update_query("massemails", $updated_email, "mid='{$mass_email['mid']}'");

	flash_message($lang->success_mass_mail_canceled, 'success');
	admin_redirect("index.php?module=user-mass_mail");
	exit;
}

if($mybb->input['action'] == "archive")
{
	// View a list of archived email messages
	$page->output_header($lang->mass_mail_archive);

	$plugins->run_hooks("admin_user_mass_email_archive_start");

	$page->output_nav_tabs($sub_tabs, 'archive');

	$table = new Table;
	$table->construct_header($lang->subject);
	$table->construct_header($lang->status, array('width' => '130', 'class' => 'align_center'));
	$table->construct_header($lang->delivery_date, array('width' => '130', 'class' => 'align_center'));
	$table->construct_header($lang->recipients, array('width' => '130', 'class' => 'align_center'));
	$table->construct_header($lang->controls, array("class" => "align_center", "colspan" => 2, "width" => 200));

	$query = $db->simple_select("massemails", "*", "status NOT IN (0, 1, 2)", array('order_by' => 'senddate'));
	while($email = $db->fetch_array($query))
	{
		$email['subject'] = htmlspecialchars_uni($email['subject']);
		if($email['senddate'] < TIME_NOW)
		{
			$table->construct_cell("{$email['subject']}");
		}
		if($email['status'] == 3)
		{
			$status = $lang->delivered;
		}
		else if($email['status'] == 4)
		{
			$status = $lang->canceled;
		}
		$table->construct_cell($status, array("class" => "align_center"));

		$delivery_date = my_date($mybb->settings['dateformat'], $email['senddate']);

		$table->construct_cell($delivery_date, array("class" => "align_center"));
		$table->construct_cell(my_number_format($email['totalcount']), array("class" => "align_center"));

		$table->construct_cell("{$lang->resend}", array("width" => 100, "class" => "align_center"));
		$table->construct_cell("post_code}&archive=1\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->mass_mail_deletion_confirmation}')\">{$lang->delete}", array("width" => 100, "class" => "align_center"));

		$table->construct_row();
	}

	if($table->num_rows() == 0)
	{
		$table->construct_cell($lang->no_archived_messages, array('colspan' => 6));
		$table->construct_row();
		$no_results = true;
	}

	$plugins->run_hooks("admin_user_mass_email_archive_end");

	$table->output($lang->mass_mail_archive);

	$page->output_footer();
}

if(!$mybb->input['action'])
{
	$page->output_header($lang->mass_mail_queue);

	$plugins->run_hooks("admin_user_mass_email_start");

	$page->output_nav_tabs($sub_tabs, 'mail_queue');

	$table = new Table;
	$table->construct_header($lang->subject);
	$table->construct_header($lang->status, array('width' => '130', 'class' => 'align_center'));
	$table->construct_header($lang->delivery_date, array('width' => '130', 'class' => 'align_center'));
	$table->construct_header($lang->recipients, array('width' => '130', 'class' => 'align_center'));
	$table->construct_header($lang->controls, array("class" => "align_center", "colspan" => 2, "width" => 200));

	$query = $db->simple_select("massemails", "*", "status IN (0, 1, 2)", array('order_by' => 'senddate'));
	while($email = $db->fetch_array($query))
	{
		$email['subject'] = htmlspecialchars_uni($email['subject']);
		if(TIME_NOW >= $email['senddate'] && $email['status'] > 1)
		{
			$table->construct_cell("{$email['subject']}");
		}
		else
		{
			$table->construct_cell("{$email['subject']}");
		}
		if($email['status'] == 0)
		{
			$status = $lang->draft;
		}
		else if($email['status'] == 1)
		{
			$status = $lang->queued;
		}
		else if($email['status'] == 2)
		{
			$progress = ceil($email['sentcount']/$email['totalcount']*100);
			if($progress > 100)
			{
				$progress = 100;
			}
			$status = "{$lang->delivering} ({$progress}%)";
		}
		$table->construct_cell($status, array("class" => "align_center"));

		if($email['status'] != 0)
		{
			$delivery_date = my_date($mybb->settings['dateformat'], $email['senddate']);
		}
		else
		{
			$delivery_date = $lang->na;
		}

		$table->construct_cell($delivery_date, array("class" => "align_center"));
		$table->construct_cell(my_number_format($email['totalcount']), array("class" => "align_center"));
		if(TIME_NOW >= $email['senddate'] && $email['status'] > 1)
		{
			$table->construct_cell("post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->mass_mail_cancel_confirmation}')\">{$lang->cancel}", array("width" => 100, "colspan" => 2, "class" => "align_center"));
		}
		else
		{
			$table->construct_cell("{$lang->edit}", array("width" => 100, "class" => "align_center"));
			$table->construct_cell("post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->mass_mail_deletion_confirmation}')\">{$lang->delete}", array("width" => 100, "class" => "align_center"));
		}
		$table->construct_row();
	}

	if($table->num_rows() == 0)
	{
		$table->construct_cell($lang->no_unsent_messages, array('colspan' => 6));
		$table->construct_row();
		$no_results = true;
	}

	$plugins->run_hooks("admin_user_mass_email_end");

	$table->output($lang->mass_mail_queue);

	$page->output_footer();
}


text:
package org.apache.commons.configuration2.builder.combined;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.BasicBuilderParameters;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.XMLBuilderParametersImpl;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.reloading.ReloadingController;
import org.apache.commons.configuration2.tree.ExpressionEngine;
import org.apache.commons.configuration2.tree.xpath.XPathExpressionEngine;
import org.easymock.EasyMock;
import org.junit.Test;

/**
 * Test class for {@code ReloadingMultiFileConfigurationBuilder}.
 *
 * @version $Id$
 */
public class TestReloadingMultiFileConfigurationBuilder extends
        AbstractMultiFileConfigurationBuilderTest
{
    /**
     * Tests whether parameters passed to the constructor are passed to the
     * super class.
     */
    @Test
    public void testInitWithParameters() throws ConfigurationException
    {
        ExpressionEngine engine = new XPathExpressionEngine();
        BasicBuilderParameters params =
                createTestBuilderParameters(new XMLBuilderParametersImpl()
                        .setExpressionEngine(engine));
        ReloadingMultiFileConfigurationBuilder<XMLConfiguration> builder =
                new ReloadingMultiFileConfigurationBuilder<XMLConfiguration>(
                        XMLConfiguration.class, params.getParameters());
        switchToConfig(1);
        XMLConfiguration config = builder.getConfiguration();
        assertSame("Expression engine not set", engine,
                config.getExpressionEngine());
    }

    /**
     * Tests whether correct managed builders are created.
     */
    @Test
    public void testCreateManagedBuilder() throws ConfigurationException
    {
        ReloadingMultiFileConfigurationBuilder<XMLConfiguration> builder =
                new ReloadingMultiFileConfigurationBuilder<XMLConfiguration>(
                        XMLConfiguration.class);
        FileBasedConfigurationBuilder<XMLConfiguration> managedBuilder =
                builder.createManagedBuilder("test.xml",
                        createTestBuilderParameters(null).getParameters());
        assertTrue(
                "Not a reloading builder",
                managedBuilder instanceof ReloadingFileBasedConfigurationBuilder);
        assertFalse("Wrong flag value", managedBuilder.isAllowFailOnInit());
    }

    /**
     * Tests whether the allowFailOnInit flag is passed to newly created managed
     * builders.
     */
    @Test
    public void testCreateManagedBuilderWithAllowFailFlag()
            throws ConfigurationException
    {
        ReloadingMultiFileConfigurationBuilder<XMLConfiguration> builder =
                new ReloadingMultiFileConfigurationBuilder<XMLConfiguration>(
                        XMLConfiguration.class, null, true);
        FileBasedConfigurationBuilder<XMLConfiguration> managedBuilder =
                builder.createManagedBuilder("test.xml",
                        createTestBuilderParameters(null).getParameters());
        assertTrue("Wrong flag value", managedBuilder.isAllowFailOnInit());
    }

    /**
     * Tests whether a reloading check works correctly.
     */
    @Test
    public void testReloadingControllerCheck() throws ConfigurationException
    {
        ReloadingMultiFileConfigurationBuilderTestImpl builder =
                new ReloadingMultiFileConfigurationBuilderTestImpl();
        switchToConfig(1);
        builder.getConfiguration();
        switchToConfig(2);
        builder.getConfiguration();
        List<ReloadingController> controllers =
                builder.getReloadingControllers();
        assertEquals("Wrong number of reloading controllers", 2,
                controllers.size());
        EasyMock.reset(controllers.toArray());
        for (ReloadingController c : controllers)
        {
            EasyMock.expect(c.checkForReloading(null)).andReturn(Boolean.FALSE);
        }
        EasyMock.replay(controllers.toArray());
        assertFalse("Wrong result", builder.getReloadingController()
                .checkForReloading(this));
        EasyMock.verify(controllers.toArray());
    }

    /**
     * Tests a reloading check which detects the need to reload.
     */
    @Test
    public void testReloadingControllerCheckReloadingRequired()
            throws ConfigurationException
    {
        ReloadingMultiFileConfigurationBuilderTestImpl builder =
                new ReloadingMultiFileConfigurationBuilderTestImpl();
        for (int i = 1; i <= 3; i++)
        {
            switchToConfig(i);
            builder.getConfiguration();
        }
        List<ReloadingController> controllers =
                builder.getReloadingControllers();
        EasyMock.reset(controllers.toArray());
        EasyMock.expect(controllers.get(0).checkForReloading(null))
                .andReturn(Boolean.FALSE).anyTimes();
        EasyMock.expect(controllers.get(1).checkForReloading(null)).andReturn(
                Boolean.TRUE);
        EasyMock.expect(controllers.get(2).checkForReloading(null))
                .andReturn(Boolean.FALSE).anyTimes();
        EasyMock.replay(controllers.toArray());
        assertTrue("Wrong result", builder.getReloadingController()
                .checkForReloading(this));
        EasyMock.verify(controllers.toArray());
    }

    /**
     * Tests whether the reloading state of the reloading controller can be
     * reset.
     */
    @Test
    public void testReloadingControllerResetReloadingState()
            throws ConfigurationException
    {
        ReloadingMultiFileConfigurationBuilderTestImpl builder =
                new ReloadingMultiFileConfigurationBuilderTestImpl();
        switchToConfig(1);
        builder.getConfiguration();
        switchToConfig(2);
        builder.getConfiguration();
        List<ReloadingController> controllers =
                builder.getReloadingControllers();
        EasyMock.reset(controllers.toArray());
        for (ReloadingController c : controllers)
        {
            EasyMock.expect(c.checkForReloading(null)).andReturn(Boolean.TRUE)
                    .anyTimes();
            c.resetReloadingState();
        }
        EasyMock.replay(controllers.toArray());
        builder.getReloadingController().checkForReloading(null);
        builder.getReloadingController().resetReloadingState();
        EasyMock.verify(controllers.toArray());
    }

    /**
     * A test implementation of the class under test which allows access to
     * reloading controllers of managed configuration builders.
     *
     * @version $Id$
     */
    private static class ReloadingMultiFileConfigurationBuilderTestImpl extends
            ReloadingMultiFileConfigurationBuilder<XMLConfiguration>
    {
        /**
         * A list with mocks for reloading controllers created by this instance.
         */
        private final List<ReloadingController> reloadingControllers;

        public ReloadingMultiFileConfigurationBuilderTestImpl()
        {
            super(XMLConfiguration.class, createTestBuilderParameters(null)
                    .getParameters());
            reloadingControllers = new ArrayList<ReloadingController>();
        }

        /**
         * Returns the list with the mock reloading controllers for the managed
         * configuration builders created by this instance.
         *
         * @return the list with mock reloading controllers
         */
        public List<ReloadingController> getReloadingControllers()
        {
            return reloadingControllers;
        }

        /**
         * {@inheritDoc} This implementation creates a specialized reloading
         * builder which is associated with a mock reloading controller.
         */
        @Override
        protected FileBasedConfigurationBuilder<XMLConfiguration> createManagedBuilder(
                String fileName, Map<String, Object> params)
                throws ConfigurationException
        {
            final ReloadingController ctrl =
                    EasyMock.createMock(ReloadingController.class);
            reloadingControllers.add(ctrl);
            return new ReloadingFileBasedConfigurationBuilder<XMLConfiguration>(
                    getResultClass(), params)
            {
                @Override
                public ReloadingController getReloadingController()
                {
                    return ctrl;
                }
            };
        }
    }
}


text:
namespace cc {

FakeRecordingSource::FakeRecordingSource() = default;

scoped_refptr<RasterSource> FakeRecordingSource::CreateRasterSource() const {
  return FakeRasterSource::CreateFromRecordingSourceWithWaitable(
      this, playback_allowed_event_);
}

}  // namespace cc


text:
'use strict';
var crypto = require('crypto');
/**
 * Asynchronously get a crypto random string of a certain length with chars 0-9 a-z A-Z.
 * @param number len
 * @param function cb - With arguments: [err, randOut, totalTimeReadable]
 */
exports = module.exports = function randomValueBase64 (len, cb) {
    var starttime = process.hrtime();
    return crypto.randomBytes(Math.ceil(len * 3 / 4), function (err, buf) {
            if (err) {
                return cb(err);
            }
            var randOut = buf
                .toString('base64')   // convert to base64 format
                .slice(0, len)        // return required number of characters
                .replace(/\+/g, '0')  // replace '+' with '0'
                .replace(/\//g, '0');  // replace '/' with '0'
            var endtime = process.hrtime(starttime);
            var totalTimeReadable = (endtime[0] > 0 ? endtime[0] + 's ' : '') + (endtime[1] / 1000000).toFixed(3) + 'ms' ;
            cb(null, randOut, totalTimeReadable);
        });
};


text:
<?php

namespace Oro\Bundle\DashboardBundle\Provider\Converters;

use Oro\Bundle\FilterBundle\Form\Type\Filter\AbstractDateFilterType;

/**
 * Converts a date range configuration of a dashboard widget
 * to a representation that can be used to filter data by previous date interval.
 */
class PreviousFilterDateRangeConverter extends FilterDateRangeConverter
{
    /**
     * {@inheritdoc}
     */
    public function getConvertedValue(array $widgetConfig, $value = null, array $config = [], array $options = [])
    {
        $result = [];

        if (($value === null && $config['converter_attributes']['default_checked'] === true) || $value) {
            if (!isset($config['converter_attributes']['dateRangeField'])) {
                throw new \Exception(
                    'Previous date range configuration parameter should have dateRangeField attribute'
                );
            }
            $currentDateRange = $options[$config['converter_attributes']['dateRangeField']];

            if (isset($currentDateRange['value'])) {
                $currentDateRange = parent::getConvertedValue(
                    $widgetConfig,
                    $currentDateRange,
                    $config,
                    $options
                );
            }

            if ($currentDateRange['type'] !== AbstractDateFilterType::TYPE_LESS_THAN
                && $currentDateRange['start']
                && $currentDateRange['end']
            ) {
                /** @var \DateTime $start */
                $start = clone $currentDateRange['start'];
                /** @var \DateTime $end */
                $end = clone $currentDateRange['end'];
                if (in_array(
                    $currentDateRange['type'],
                    [
                        AbstractDateFilterType::TYPE_THIS_MONTH,
                        AbstractDateFilterType::TYPE_THIS_QUARTER,
                        AbstractDateFilterType::TYPE_THIS_YEAR
                    ],
                    true
                )) {
                    if ($currentDateRange['type'] == AbstractDateFilterType::TYPE_THIS_MONTH) {
                        $start->modify('first day of previous month');
                        $end->modify('last day of previous month');
                    } elseif ($currentDateRange['type'] == AbstractDateFilterType::TYPE_THIS_YEAR) {
                        $start->modify('first day of previous year');
                        $end->modify('last day of previous year');
                    } elseif ($currentDateRange['type'] == AbstractDateFilterType::TYPE_THIS_QUARTER) {
                        $start->modify('first day of - 3 month');
                        $end->modify('last day of - 3 month');
                    }
                } else {
                    // shift to previous range
                    $interval = $start->diff($end);
                    $start= $start->sub($interval);
                    $end = $end->sub($interval);
                }

                $result['start'] = $start;
                $result['end']   = $end;
                $type            = AbstractDateFilterType::TYPE_BETWEEN;
                if (isset($currentDateRange['type'])) {
                    $type = $currentDateRange['type'];
                }
                $result['type'] = $type;
            }
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function getViewValue($value)
    {
        if (!empty($value)) {
            return parent::getViewValue($value);
        }

        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getFormValue(array $config, $value)
    {
        if ($value === null && $config['converter_attributes']['default_checked'] === true) {
            return true;
        }

        return parent::getFormValue($config, $value);
    }
}


text:
require "rails_helper"

RSpec.describe GamesController, type: :routing do
  describe "routing" do
    it "routes to #index" do
      expect(:get => "/games").to route_to("games#index")
    end

    it "routes to #new" do
      expect(:get => "/games/new").to route_to("games#new")
    end

    it "routes to #show" do
      expect(:get => "/games/1").to route_to("games#show", :id => "1")
    end

    it "routes to #create" do
      expect(:post => "/games").to route_to("games#create")
    end

    it "routes to #destroy" do
      expect(:delete => "/games/1").to route_to("games#destroy", :id => "1")
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace ListViewDemo
{
    [Activity(Label = "Simple Adapter")]
    public class SimpleAdapterActivity : ListActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            List<Player> players = Player.GetPlayers();
            string[] playerNames = players.Select(x => x.Name).ToArray();
            ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, playerNames);

            ListView.ItemLongClick += ListView_ItemLongClick;
        }

        protected override void OnListItemClick(ListView l, View v, int position, long id)
        {
            base.OnListItemClick(l, v, position, id);

            string name = (string)this.ListAdapter.GetItem(position);
            string text = string.Format("Clicked on {0}", name);
            Toast.MakeText(this, text, ToastLength.Short).Show();
        }

        private void ListView_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
        {
            string name = (string)this.ListAdapter.GetItem(e.Position);
            string text = string.Format("Long Clicked on {0}", name);
            Toast.MakeText(this, text, ToastLength.Short).Show();
        }
    }
}