Imported from archive.
[mudpy.git] / mudpy.py
1 """Core objects for the mudpy engine."""
2
3 # Copyright (c) 2005 mudpy, Jeremy Stanley <fungi@yuggoth.org>, all rights reserved.
4 # Licensed per terms in the LICENSE file distributed with this software.
5
6 # import some things we need
7 from ConfigParser import RawConfigParser
8 from md5 import new as new_md5
9 from os import R_OK, access, chmod, makedirs, stat
10 from os.path import abspath, dirname, exists, isabs, join as path_join
11 from random import choice, randrange
12 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
13 from stat import S_IMODE, ST_MODE
14 from time import asctime, sleep
15
16 class Element:
17         """An element of the universe."""
18         def __init__(self, key, universe, origin=""):
19                 """Default values for the in-memory element variables."""
20                 self.key = key
21                 if self.key.find(":") > 0:
22                         self.category, self.subkey = self.key.split(":", 1)
23                 else:
24                         self.category = "other"
25                         self.subkey = self.key
26                 if not self.category in universe.categories: self.category = "other"
27                 universe.categories[self.category][self.subkey] = self
28                 self.origin = origin
29                 if not self.origin: self.origin = universe.default_origins[self.category]
30                 if not isabs(self.origin):
31                         self.origin = abspath(self.origin)
32                 universe.contents[self.key] = self
33                 if not self.origin in universe.files:
34                         DataFile(self.origin, universe)
35                 if not universe.files[self.origin].data.has_section(self.key):
36                         universe.files[self.origin].data.add_section(self.key)
37         def delete(self):
38                 log("Deleting: " + self.key + ".")
39                 universe.files[self.origin].data.remove_section(self.key)
40                 del universe.categories[self.category][self.subkey]
41                 del universe.contents[self.key]
42                 del self
43         def facets(self):
44                 """Return a list of facets for this element."""
45                 return universe.files[self.origin].data.options(self.key)
46         def get(self, facet, default=None):
47                 """Retrieve values."""
48                 if default is None: default = ""
49                 if universe.files[self.origin].data.has_option(self.key, facet):
50                         return universe.files[self.origin].data.get(self.key, facet)
51                 else: return default
52         def getboolean(self, facet, default=None):
53                 """Retrieve values as boolean type."""
54                 if default is None: default=False
55                 if universe.files[self.origin].data.has_option(self.key, facet):
56                         return universe.files[self.origin].data.getboolean(self.key, facet)
57                 else: return default
58         def getint(self, facet, default=None):
59                 """Return values as int/long type."""
60                 if default is None: default = 0
61                 if universe.files[self.origin].data.has_option(self.key, facet):
62                         return universe.files[self.origin].data.getint(self.key, facet)
63                 else: return default
64         def getfloat(self, facet, default=None):
65                 """Return values as float type."""
66                 if default is None: default = 0.0
67                 if universe.files[self.origin].data.has_option(self.key, facet):
68                         return universe.files[self.origin].data.getfloat(self.key, facet)
69                 else: return default
70         def getlist(self, facet, default=None):
71                 """Return values as list type."""
72                 if default is None: default = []
73                 value = self.get(facet)
74                 if value: return makelist(value)
75                 else: return default
76         def getdict(self, facet, default=None):
77                 """Return values as dict type."""
78                 if default is None: default = {}
79                 value = self.get(facet)
80                 if value: return makedict(value)
81                 else: return default
82         def set(self, facet, value):
83                 """Set values."""
84                 if type(value) is long: value = str(value)
85                 elif not type(value) is str: value = repr(value)
86                 universe.files[self.origin].data.set(self.key, facet, value)
87
88 class DataFile:
89         """A file containing universe elements."""
90         def __init__(self, filename, universe):
91                 self.data = RawConfigParser()
92                 if access(filename, R_OK): self.data.read(filename)
93                 self.filename = filename
94                 universe.files[filename] = self
95                 if self.data.has_option("control", "include_files"):
96                         includes = makelist(self.data.get("control", "include_files"))
97                 else: includes = []
98                 if self.data.has_option("control", "default_files"):
99                         origins = makedict(self.data.get("control", "default_files"))
100                         for key in origins.keys():
101                                 if not key in includes: includes.append(key)
102                                 universe.default_origins[key] = origins[key]
103                                 if not key in universe.categories:
104                                         universe.categories[key] = {}
105                 if self.data.has_option("control", "private_files"):
106                         for item in makelist(self.data.get("control", "private_files")):
107                                 if not item in includes: includes.append(item)
108                                 if not item in universe.private_files:
109                                         if not isabs(item):
110                                                 item = path_join(dirname(filename), item)
111                                         universe.private_files.append(item)
112                 for section in self.data.sections():
113                         if section != "control":
114                                 Element(section, universe, filename)
115                 for include_file in includes:
116                         if not isabs(include_file):
117                                 include_file = path_join(dirname(filename), include_file)
118                         DataFile(include_file, universe)
119         def save(self):
120                 if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("control", "read_only") and self.data.getboolean("control", "read_only") ):
121                         if not exists(dirname(self.filename)): makedirs(dirname)
122                         file_descriptor = file(self.filename, "w")
123                         if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
124                                 chmod(self.filename, 0600)
125                         self.data.write(file_descriptor)
126                         file_descriptor.flush()
127                         file_descriptor.close()
128
129 class Universe:
130         """The universe."""
131         def __init__(self, filename=""):
132                 """Initialize the universe."""
133                 self.categories = {}
134                 self.contents = {}
135                 self.default_origins = {}
136                 self.files = {}
137                 self.private_files = []
138                 self.userlist = []
139                 self.terminate_world = False
140                 self.reload_modules = False
141                 if not filename:
142                         possible_filenames = [
143                                 ".mudpyrc",
144                                 ".mudpy/mudpyrc",
145                                 ".mudpy/mudpy.conf",
146                                 "mudpy.conf",
147                                 "etc/mudpy.conf",
148                                 "/usr/local/mudpy/mudpy.conf",
149                                 "/usr/local/mudpy/etc/mudpy.conf",
150                                 "/etc/mudpy/mudpy.conf",
151                                 "/etc/mudpy.conf"
152                                 ]
153                         for filename in possible_filenames:
154                                 if access(filename, R_OK): break
155                 if not isabs(filename):
156                         filename = abspath(filename)
157                 DataFile(filename, self)
158         def save(self):
159                 """Save the universe to persistent storage."""
160                 for key in self.files: self.files[key].save()
161
162         def initialize_server_socket(self):
163                 """Create and open the listening socket."""
164
165                 # create a new ipv4 stream-type socket object
166                 self.listening_socket = socket(AF_INET, SOCK_STREAM)
167
168                 # set the socket options to allow existing open ones to be
169                 # reused (fixes a bug where the server can't bind for a minute
170                 # when restarting on linux systems)
171                 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
172
173                 # bind the socket to to our desired server ipa and port
174                 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
175
176                 # disable blocking so we can proceed whether or not we can
177                 # send/receive
178                 self.listening_socket.setblocking(0)
179
180                 # start listening on the socket
181                 self.listening_socket.listen(1)
182
183                 # note that we're now ready for user connections
184                 log("Waiting for connection(s)...")
185
186 class User:
187         """This is a connected user."""
188
189         def __init__(self):
190                 """Default values for the in-memory user variables."""
191                 self.address = ""
192                 self.last_address = ""
193                 self.connection = None
194                 self.authenticated = False
195                 self.password_tries = 0
196                 self.state = "entering_account_name"
197                 self.menu_seen = False
198                 self.error = ""
199                 self.input_queue = []
200                 self.output_queue = []
201                 self.partial_input = ""
202                 self.echoing = True
203                 self.avatar = None
204                 self.account = None
205
206         def quit(self):
207                 """Log, close the connection and remove."""
208                 if self.account: name = self.account.get("name")
209                 else: name = ""
210                 if name: message = "User " + name
211                 else: message = "An unnamed user"
212                 message += " logged out."
213                 log(message)
214                 self.connection.close()
215                 self.remove()
216
217         def reload(self):
218                 """Save, load a new user and relocate the connection."""
219
220                 # get out of the list
221                 self.remove()
222
223                 # create a new user object
224                 new_user = User()
225
226                 # set everything else equivalent
227                 for attribute in [
228                         "address",
229                         "last_address",
230                         "connection",
231                         "authenticated",
232                         "password_tries",
233                         "state",
234                         "menu_seen",
235                         "error",
236                         "input_queue",
237                         "output_queue",
238                         "partial_input",
239                         "echoing",
240                         "avatar",
241                         "account"
242                         ]:
243                         exec("new_user." + attribute + " = self." + attribute)
244
245                 # add it to the list
246                 universe.userlist.append(new_user)
247
248                 # get rid of the old user object
249                 del(self)
250
251         def replace_old_connections(self):
252                 """Disconnect active users with the same name."""
253
254                 # the default return value
255                 return_value = False
256
257                 # iterate over each user in the list
258                 for old_user in universe.userlist:
259
260                         # the name is the same but it's not us
261                         if old_user.account.get("name") == self.account.get("name") and old_user is not self:
262
263                                 # make a note of it
264                                 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".")
265                                 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)")
266                                 self.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
267
268                                 # close the old connection
269                                 old_user.connection.close()
270
271                                 # replace the old connection with this one
272                                 old_user.connection = self.connection
273                                 old_user.last_address = old_user.address
274                                 old_user.address = self.address
275                                 old_user.echoing = self.echoing
276
277                                 # take this one out of the list and delete
278                                 self.remove()
279                                 del(self)
280                                 return_value = True
281                                 break
282
283                 # true if an old connection was replaced, false if not
284                 return return_value
285
286         def authenticate(self):
287                 """Flag the user as authenticated and disconnect duplicates."""
288                 if not self.state is "authenticated":
289                         log("User " + self.account.get("name") + " logged in.")
290                         self.authenticated = True
291
292         def show_menu(self):
293                 """Send the user their current menu."""
294                 if not self.menu_seen:
295                         self.menu_choices = get_menu_choices(self)
296                         self.send(get_menu(self.state, self.error, self.echoing, self.menu_choices), "")
297                         self.menu_seen = True
298                         self.error = False
299                         self.adjust_echoing()
300
301         def adjust_echoing(self):
302                 """Adjust echoing to match state menu requirements."""
303                 if self.echoing and not menu_echo_on(self.state): self.echoing = False
304                 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
305
306         def remove(self):
307                 """Remove a user from the list of connected users."""
308                 universe.userlist.remove(self)
309
310         def send(self, output, eol="$(eol)"):
311                 """Send arbitrary text to a connected user."""
312
313                 # only when there is actual output
314                 #if output:
315
316                 # start with a newline, append the message, then end
317                 # with the optional eol string passed to this function
318                 # and the ansi escape to return to normal text
319                 output = "\r\n" + output + eol + chr(27) + "[0m"
320
321                 # find and replace macros in the output
322                 output = replace_macros(self, output)
323
324                 # wrap the text at 80 characters
325                 # TODO: prompt user for preferred wrap width
326                 output = wrap_ansi_text(output, 80)
327
328                 # drop the formatted output into the output queue
329                 self.output_queue.append(output)
330
331                 # try to send the last item in the queue, remove it and
332                 # flag that menu display is not needed
333                 try:
334                         self.connection.send(self.output_queue[0])
335                         self.output_queue.remove(self.output_queue[0])
336                         self.menu_seen = False
337
338                 # but if we can't, that's okay too
339                 except:
340                         pass
341
342         def pulse(self):
343                 """All the things to do to the user per increment."""
344
345                 # if the world is terminating, disconnect
346                 if universe.terminate_world:
347                         self.state = "disconnecting"
348                         self.menu_seen = False
349
350                 # show the user a menu as needed
351                 self.show_menu()
352
353                 # disconnect users with the appropriate state
354                 if self.state == "disconnecting":
355                         self.quit()
356
357                 # the user is unique and not flagged to disconnect
358                 else:
359                 
360                         # check for input and add it to the queue
361                         self.enqueue_input()
362
363                         # there is input waiting in the queue
364                         if self.input_queue: handle_user_input(self)
365
366         def enqueue_input(self):
367                 """Process and enqueue any new input."""
368
369                 # check for some input
370                 try:
371                         input_data = self.connection.recv(1024)
372                 except:
373                         input_data = ""
374
375                 # we got something
376                 if input_data:
377
378                         # tack this on to any previous partial
379                         self.partial_input += input_data
380
381                         # separate multiple input lines
382                         new_input_lines = self.partial_input.split("\n")
383
384                         # if input doesn't end in a newline, replace the
385                         # held partial input with the last line of it
386                         if not self.partial_input.endswith("\n"):
387                                 self.partial_input = new_input_lines.pop()
388
389                         # otherwise, chop off the extra null input and reset
390                         # the held partial input
391                         else:
392                                 new_input_lines.pop()
393                                 self.partial_input = ""
394
395                         # iterate over the remaining lines
396                         for line in new_input_lines:
397
398                                 # filter out non-printables
399                                 line = filter(lambda x: x>=' ' and x<='~', line)
400
401                                 # strip off extra whitespace
402                                 line = line.strip()
403
404                                 # put on the end of the queue
405                                 self.input_queue.append(line)
406
407         def new_avatar(self):
408                 """Instantiate a new, unconfigured avatar for this user."""
409                 counter = 0
410                 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
411                 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
412                 avatars = self.account.getlist("avatars")
413                 avatars.append(self.avatar.key)
414                 self.account.set("avatars", avatars)
415
416         def delete_avatar(self, avatar):
417                 """Remove an avatar from the world and from the user's list."""
418                 if self.avatar is universe.contents[avatar]: self.avatar = None
419                 universe.contents[avatar].delete()
420                 avatars = self.account.getlist("avatars")
421                 avatars.remove(avatar)
422                 self.account.set("avatars", avatars)
423
424         def delete(self):
425                 """Delete the user and associated avatars."""
426                 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
427                 self.account.delete()
428
429         def list_avatar_names(self):
430                 """List names of assigned avatars."""
431                 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
432
433 def makelist(value):
434         """Turn string into list type."""
435         if value[0] + value[-1] == "[]": return eval(value)
436         else: return [ value ]
437
438 def makedict(value):
439         """Turn string into dict type."""
440         if value[0] + value[-1] == "{}": return eval(value)
441         elif value.find(":") > 0: return eval("{" + value + "}")
442         else: return { value: None }
443
444 def broadcast(message):
445         """Send a message to all connected users."""
446         for each_user in universe.userlist: each_user.send("$(eol)" + message)
447
448 def log(message):
449         """Log a message."""
450
451         # the time in posix log timestamp format
452         timestamp = asctime()[4:19]
453
454         # send the timestamp and message to standard output
455         print(timestamp + " " + message)
456
457 def wrap_ansi_text(text, width):
458         """Wrap text with arbitrary width while ignoring ANSI colors."""
459
460         # the current position in the entire text string, including all
461         # characters, printable or otherwise
462         absolute_position = 0
463
464         # the current text position relative to the begining of the line,
465         # ignoring color escape sequences
466         relative_position = 0
467
468         # whether the current character is part of a color escape sequence
469         escape = False
470
471         # iterate over each character from the begining of the text
472         for each_character in text:
473
474                 # the current character is the escape character
475                 if each_character == chr(27):
476                         escape = True
477
478                 # the current character is within an escape sequence
479                 elif escape:
480
481                         # the current character is m, which terminates the
482                         # current escape sequence
483                         if each_character == "m":
484                                 escape = False
485
486                 # the current character is a newline, so reset the relative
487                 # position (start a new line)
488                 elif each_character == "\n":
489                         relative_position = 0
490
491                 # the current character meets the requested maximum line width,
492                 # so we need to backtrack and find a space at which to wrap
493                 elif relative_position == width:
494
495                         # distance of the current character examined from the
496                         # relative position
497                         wrap_offset = 0
498
499                         # count backwards until we find a space
500                         while text[absolute_position - wrap_offset] != " ":
501                                 wrap_offset += 1
502
503                         # insert an eol in place of the space
504                         text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
505
506                         # increase the absolute position because an eol is two
507                         # characters but the space it replaced was only one
508                         absolute_position += 1
509
510                         # now we're at the begining of a new line, plus the
511                         # number of characters wrapped from the previous line
512                         relative_position = wrap_offset
513
514                 # as long as the character is not a carriage return and the
515                 # other above conditions haven't been met, count it as a
516                 # printable character
517                 elif each_character != "\r":
518                         relative_position += 1
519
520                 # increase the absolute position for every character
521                 absolute_position += 1
522
523         # return the newly-wrapped text
524         return text
525
526 def weighted_choice(data):
527         """Takes a dict weighted by value and returns a random key."""
528
529         # this will hold our expanded list of keys from the data
530         expanded = []
531
532         # create thee expanded list of keys
533         for key in data.keys():
534                 for count in range(data[key]):
535                         expanded.append(key)
536
537         # return one at random
538         return choice(expanded)
539
540 def random_name():
541         """Returns a random character name."""
542
543         # the vowels and consonants needed to create romaji syllables
544         vowels = [ "a", "i", "u", "e", "o" ]
545         consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
546
547         # this dict will hold our weighted list of syllables
548         syllables = {}
549
550         # generate the list with an even weighting
551         for consonant in consonants:
552                 for vowel in vowels:
553                         syllables[consonant + vowel] = 1
554
555         # we'll build the name into this string
556         name = ""
557
558         # create a name of random length from the syllables
559         for syllable in range(randrange(2, 6)):
560                 name += weighted_choice(syllables)
561
562         # strip any leading quotemark, capitalize and return the name
563         return name.strip("'").capitalize()
564
565 def replace_macros(user, text, is_input=False):
566         """Replaces macros in text output."""
567
568         # loop until broken
569         while True:
570
571                 # third person pronouns
572                 pronouns = {
573                         "female": { "obj": "her", "pos": "hers", "sub": "she" },
574                         "male": { "obj": "him", "pos": "his", "sub": "he" },
575                         "neuter": { "obj": "it", "pos": "its", "sub": "it" }
576                         }
577
578                 # a dict of replacement macros
579                 macros = {
580                         "$(eol)": "\r\n",
581                         "$(bld)": chr(27) + "[1m",
582                         "$(nrm)": chr(27) + "[0m",
583                         "$(blk)": chr(27) + "[30m",
584                         "$(grn)": chr(27) + "[32m",
585                         "$(red)": chr(27) + "[31m",
586                         }
587
588                 # add dynamic macros where possible
589                 if user.account:
590                         account_name = user.account.get("name")
591                         if account_name:
592                                 macros["$(account)"] = account_name
593                 if user.avatar:
594                         avatar_gender = user.avatar.get("gender")
595                         if avatar_gender:
596                                 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
597                                 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
598                                 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
599
600                 # find and replace per the macros dict
601                 macro_start = text.find("$(")
602                 if macro_start == -1: break
603                 macro_end = text.find(")", macro_start) + 1
604                 macro = text[macro_start:macro_end]
605                 if macro in macros.keys():
606                         text = text.replace(macro, macros[macro])
607
608                 # if we get here, log and replace it with null
609                 else:
610                         text = text.replace(macro, "")
611                         if not is_input:
612                                 log("Unexpected replacement macro " + macro + " encountered.")
613
614         # replace the look-like-a-macro sequence
615         text = text.replace("$_(", "$(")
616
617         return text
618
619 def check_time(frequency):
620         """Check for a factor of the current increment count."""
621         if type(frequency) is str:
622                 frequency = universe.categories["internal"]["time"].getint(frequency)
623         if not "counters" in universe.categories["internal"]:
624                 Element("internal:counters", universe)
625         return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
626
627 def on_pulse():
628         """The things which should happen on each pulse, aside from reloads."""
629
630         # open the listening socket if it hasn't been already
631         if not hasattr(universe, "listening_socket"):
632                 universe.initialize_server_socket()
633
634         # assign a user if a new connection is waiting
635         user = check_for_connection(universe.listening_socket)
636         if user: universe.userlist.append(user)
637
638         # iterate over the connected users
639         for user in universe.userlist: user.pulse()
640
641         # update the log every now and then
642         if check_time("frequency_log"):
643                 log(str(len(universe.userlist)) + " connection(s)")
644
645         # periodically save everything
646         if check_time("frequency_save"):
647                 universe.save()
648
649         # pause for a configurable amount of time (decimal seconds)
650         sleep(universe.categories["internal"]["time"].getfloat("increment"))
651
652         # increment the elapsed increment counter
653         universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
654
655 def reload_data():
656         """Reload data into new persistent objects."""
657         for user in universe.userlist[:]: user.reload()
658
659 def check_for_connection(listening_socket):
660         """Check for a waiting connection and return a new user object."""
661
662         # try to accept a new connection
663         try:
664                 connection, address = listening_socket.accept()
665         except:
666                 return None
667
668         # note that we got one
669         log("Connection from " + address[0])
670
671         # disable blocking so we can proceed whether or not we can send/receive
672         connection.setblocking(0)
673
674         # create a new user object
675         user = User()
676
677         # associate this connection with it
678         user.connection = connection
679
680         # set the user's ipa from the connection's ipa
681         user.address = address[0]
682
683         # return the new user object
684         return user
685
686 def get_menu(state, error=None, echoing=True, choices={}):
687         """Show the correct menu text to a user."""
688
689         # begin with a telnet echo command sequence if needed
690         message = get_echo_sequence(state, echoing)
691
692         # get the description or error text
693         message += get_menu_description(state, error)
694
695         # get menu choices for the current state
696         message += get_formatted_menu_choices(state, choices)
697
698         # try to get a prompt, if it was defined
699         message += get_menu_prompt(state)
700
701         # throw in the default choice, if it exists
702         message += get_formatted_default_menu_choice(state)
703
704         # display a message indicating if echo is off
705         message += get_echo_message(state)
706
707         # return the assembly of various strings defined above
708         return message
709
710 def menu_echo_on(state):
711         """True if echo is on, false if it is off."""
712         return universe.categories["menu"][state].getboolean("echo", True)
713
714 def get_echo_sequence(state, echoing):
715         """Build the appropriate IAC ECHO sequence as needed."""
716
717         # if the user has echo on and the menu specifies it should be turned
718         # off, send: iac + will + echo + null
719         if echoing and not menu_echo_on(state): return chr(255) + chr(251) + chr(1) + chr(0)
720
721         # if echo is not set to off in the menu and the user curently has echo
722         # off, send: iac + wont + echo + null
723         elif not echoing and menu_echo_on(state): return chr(255) + chr(252) + chr(1) + chr(0)
724
725         # default is not to send an echo control sequence at all
726         else: return ""
727
728 def get_echo_message(state):
729         """Return a message indicating that echo is off."""
730         if menu_echo_on(state): return ""
731         else: return "(won't echo) "
732
733 def get_default_menu_choice(state):
734         """Return the default choice for a menu."""
735         return universe.categories["menu"][state].get("default")
736
737 def get_formatted_default_menu_choice(state):
738         """Default menu choice foratted for inclusion in a prompt string."""
739         default_choice = get_default_menu_choice(state)
740         if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
741         else: return ""
742
743 def get_menu_description(state, error):
744         """Get the description or error text."""
745
746         # an error condition was raised by the handler
747         if error:
748
749                 # try to get an error message matching the condition
750                 # and current state
751                 description = universe.categories["menu"][state].get("error_" + error)
752                 if not description: description = "That is not a valid choice..."
753                 description = "$(red)" + description + "$(nrm)"
754
755         # there was no error condition
756         else:
757
758                 # try to get a menu description for the current state
759                 description = universe.categories["menu"][state].get("description")
760
761         # return the description or error message
762         if description: description += "$(eol)$(eol)"
763         return description
764
765 def get_menu_prompt(state):
766         """Try to get a prompt, if it was defined."""
767         prompt = universe.categories["menu"][state].get("prompt")
768         if prompt: prompt += " "
769         return prompt
770
771 def get_menu_choices(user):
772         """Return a dict of choice:meaning."""
773         menu = universe.categories["menu"][user.state]
774         create_choices = menu.get("create")
775         if create_choices: choices = eval(create_choices)
776         else: choices = {}
777         ignores = []
778         options = {}
779         creates = {}
780         for facet in menu.facets():
781                 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
782                         ignores.append(facet.split("_", 2)[1])
783                 elif facet.startswith("create_"):
784                         creates[facet] = facet.split("_", 2)[1]
785                 elif facet.startswith("choice_"):
786                         options[facet] = facet.split("_", 2)[1]
787         for facet in creates.keys():
788                 if not creates[facet] in ignores:
789                         choices[creates[facet]] = eval(menu.get(facet))
790         for facet in options.keys():
791                 if not options[facet] in ignores:
792                         choices[options[facet]] = menu.get(facet)
793         return choices
794
795 def get_formatted_menu_choices(state, choices):
796         """Returns a formatted string of menu choices."""
797         choice_output = ""
798         choice_keys = choices.keys()
799         choice_keys.sort()
800         for choice in choice_keys:
801                 choice_output += "   [$(red)" + choice + "$(nrm)]  " + choices[choice] + "$(eol)"
802         if choice_output: choice_output += "$(eol)"
803         return choice_output
804
805 def get_menu_branches(state):
806         """Return a dict of choice:branch."""
807         branches = {}
808         for facet in universe.categories["menu"][state].facets():
809                 if facet.startswith("branch_"):
810                         branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
811         return branches
812
813 def get_default_branch(state):
814         """Return the default branch."""
815         return universe.categories["menu"][state].get("branch")
816
817 def get_choice_branch(user, choice):
818         """Returns the new state matching the given choice."""
819         branches = get_menu_branches(user.state)
820         if choice in branches.keys(): return branches[choice]
821         elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
822         else: return ""
823
824 def get_menu_actions(state):
825         """Return a dict of choice:branch."""
826         actions = {}
827         for facet in universe.categories["menu"][state].facets():
828                 if facet.startswith("action_"):
829                         actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
830         return actions
831
832 def get_default_action(state):
833         """Return the default action."""
834         return universe.categories["menu"][state].get("action")
835
836 def get_choice_action(user, choice):
837         """Run any indicated script for the given choice."""
838         actions = get_menu_actions(user.state)
839         if choice in actions.keys(): return actions[choice]
840         elif choice in user.menu_choices.keys(): return get_default_action(user.state)
841         else: return ""
842
843 def handle_user_input(user):
844         """The main handler, branches to a state-specific handler."""
845
846         # check to make sure the state is expected, then call that handler
847         if "handler_" + user.state in globals():
848                 exec("handler_" + user.state + "(user)")
849         else:
850                 generic_menu_handler(user)
851
852         # since we got input, flag that the menu/prompt needs to be redisplayed
853         user.menu_seen = False
854
855         # if the user's client echo is off, send a blank line for aesthetics
856         if not user.echoing: user.send("", "")
857
858 def generic_menu_handler(user):
859         """A generic menu choice handler."""
860
861         # get a lower-case representation of the next line of input
862         if user.input_queue:
863                 choice = user.input_queue.pop(0)
864                 if choice: choice = choice.lower()
865         else: choice = ""
866         if not choice: choice = get_default_menu_choice(user.state)
867         if choice in user.menu_choices:
868                 exec(get_choice_action(user, choice))
869                 new_state = get_choice_branch(user, choice)
870                 if new_state: user.state = new_state
871         else: user.error = "default"
872
873 def handler_entering_account_name(user):
874         """Handle the login account name."""
875
876         # get the next waiting line of input
877         input_data = user.input_queue.pop(0)
878
879         # did the user enter anything?
880         if input_data:
881                 
882                 # keep only the first word and convert to lower-case
883                 name = input_data.lower()
884
885                 # fail if there are non-alphanumeric characters
886                 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
887                         user.error = "bad_name"
888
889                 # if that account exists, time to request a password
890                 elif name in universe.categories["account"]:
891                         user.account = universe.categories["account"][name]
892                         user.state = "checking_password"
893
894                 # otherwise, this could be a brand new user
895                 else:
896                         user.account = Element("account:" + name, universe)
897                         user.account.set("name", name)
898                         log("New user: " + name)
899                         user.state = "checking_new_account_name"
900
901         # if the user entered nothing for a name, then buhbye
902         else:
903                 user.state = "disconnecting"
904
905 def handler_checking_password(user):
906         """Handle the login account password."""
907
908         # get the next waiting line of input
909         input_data = user.input_queue.pop(0)
910
911         # does the hashed input equal the stored hash?
912         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
913
914                 # if so, set the username and load from cold storage
915                 if not user.replace_old_connections():
916                         user.authenticate()
917                         user.state = "main_utility"
918
919         # if at first your hashes don't match, try, try again
920         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
921                 user.password_tries += 1
922                 user.error = "incorrect"
923
924         # we've exceeded the maximum number of password failures, so disconnect
925         else:
926                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
927                 user.state = "disconnecting"
928
929 def handler_entering_new_password(user):
930         """Handle a new password entry."""
931
932         # get the next waiting line of input
933         input_data = user.input_queue.pop(0)
934
935         # make sure the password is strong--at least one upper, one lower and
936         # one digit, seven or more characters in length
937         if len(input_data) > 6 and len(filter(lambda x: x>="0" and x<="9", input_data)) and len(filter(lambda x: x>="A" and x<="Z", input_data)) and len(filter(lambda x: x>="a" and x<="z", input_data)):
938
939                 # hash and store it, then move on to verification
940                 user.account.set("passhash",  new_md5(user.account.get("name") + input_data).hexdigest())
941                 user.state = "verifying_new_password"
942
943         # the password was weak, try again if you haven't tried too many times
944         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
945                 user.password_tries += 1
946                 user.error = "weak"
947
948         # too many tries, so adios
949         else:
950                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
951                 user.account.delete()
952                 user.state = "disconnecting"
953
954 def handler_verifying_new_password(user):
955         """Handle the re-entered new password for verification."""
956
957         # get the next waiting line of input
958         input_data = user.input_queue.pop(0)
959
960         # hash the input and match it to storage
961         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
962                 user.authenticate()
963
964                 # the hashes matched, so go active
965                 if not user.replace_old_connections(): user.state = "main_utility"
966
967         # go back to entering the new password as long as you haven't tried
968         # too many times
969         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
970                 user.password_tries += 1
971                 user.error = "differs"
972                 user.state = "entering_new_password"
973
974         # otherwise, sayonara
975         else:
976                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
977                 user.account.delete()
978                 user.state = "disconnecting"
979
980 def handler_active(user):
981         """Handle input for active users."""
982
983         # get the next waiting line of input
984         input_data = user.input_queue.pop(0)
985
986         # split out the command (first word) and parameters (everything else)
987         if input_data.find(" ") > 0:
988                 command, parameters = input_data.split(" ", 1)
989         else:
990                 command = input_data
991                 parameters = ""
992
993         # lowercase the command
994         command = command.lower()
995
996         # the command matches a command word for which we have data
997         if command in universe.categories["command"]:
998                 exec(universe.categories["command"][command].get("action"))
999
1000         # no data matching the entered command word
1001         elif command: command_error(user, command, parameters)
1002
1003 def command_halt(user, command="", parameters=""):
1004         """Halt the world."""
1005
1006         # see if there's a message or use a generic one
1007         if parameters: message = "Halting: " + parameters
1008         else: message = "User " + user.account.get("name") + " halted the world."
1009
1010         # let everyone know
1011         broadcast(message)
1012         log(message)
1013
1014         # set a flag to terminate the world
1015         universe.terminate_world = True
1016
1017 def command_reload(user, command="", parameters=""):
1018         """Reload all code modules, configs and data."""
1019
1020         # let the user know and log
1021         user.send("Reloading all code modules, configs and data.")
1022         log("User " + user.account.get("name") + " reloaded the world.")
1023
1024         # set a flag to reload
1025         universe.reload_modules = True
1026
1027 def command_quit(user, command="", parameters=""):
1028         """Quit the world."""
1029         user.state = "main_utility"
1030
1031 def command_help(user, command="", parameters=""):
1032         """List available commands and provide help for commands."""
1033
1034         # did the user ask for help on a specific command word?
1035         if parameters:
1036
1037                 # is the command word one for which we have data?
1038                 if parameters in universe.categories["command"]:
1039
1040                         # add a description if provided
1041                         description = universe.categories["command"][parameters].get("description")
1042                         if not description:
1043                                 description = "(no short description provided)"
1044                         output = "$(grn)" + parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1045
1046                         # add the help text if provided
1047                         help_text = universe.categories["command"][parameters].get("help")
1048                         if not help_text:
1049                                 help_text = "No help is provided for this command."
1050                         output += help_text
1051
1052                 # no data for the requested command word
1053                 else:
1054                         output = "That is not an available command."
1055
1056         # no specific command word was indicated
1057         else:
1058
1059                 # give a sorted list of commands with descriptions if provided
1060                 output = "These are the commands available to you:$(eol)$(eol)"
1061                 sorted_commands = universe.categories["command"].keys()
1062                 sorted_commands.sort()
1063                 for item in sorted_commands:
1064                         description = universe.categories["command"][item].get("description")
1065                         if not description:
1066                                 description = "(no short description provided)"
1067                         output += "   $(grn)" + item + "$(nrm) - " + description + "$(eol)"
1068                 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1069
1070         # send the accumulated output to the user
1071         user.send(output)
1072
1073 def command_say(user, command="", parameters=""):
1074         """Speak to others in the same room."""
1075
1076         # check for replacement macros
1077         if replace_macros(user, parameters, True) != parameters:
1078                 user.send("You cannot speak $_(replacement macros).")
1079
1080         # the user entered a message
1081         elif parameters:
1082
1083                 # get rid of quote marks on the ends of the message and
1084                 # capitalize the first letter
1085                 message = parameters.strip("\"'`").capitalize()
1086
1087                 # a dictionary of punctuation:action pairs
1088                 actions = {}
1089                 for facet in universe.categories["internal"]["language"].facets():
1090                         if facet.startswith("punctuation_"):
1091                                 action = facet.split("_")[1]
1092                                 for mark in universe.categories["internal"]["language"].getlist(facet):
1093                                                 actions[mark] = action
1094
1095                 # match the punctuation used, if any, to an action
1096                 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1097                 action = actions[default_punctuation]
1098                 for mark in actions.keys():
1099                         if message.endswith(mark) and mark != default_punctuation:
1100                                 action = actions[mark]
1101                                 break
1102
1103                 # if the action is default and there is no mark, add one
1104                 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1105                         message += default_punctuation
1106
1107                 # capitalize a list of words within the message
1108                 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1109                 for word in capitalize_words:
1110                         message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1111
1112                 # tell the room
1113                 # TODO: we won't be using broadcast once there are actual rooms
1114                 broadcast(user.account.get("name") + " " + action + "s, \"" + message + "\"")
1115
1116         # there was no message
1117         else:
1118                 user.send("What do you want to say?")
1119
1120 def command_show(user, command="", parameters=""):
1121         """Show program data."""
1122         if parameters == "avatars":
1123                 message = "These are the avatars managed by your account:$(eol)"
1124                 avatars = user.list_avatar_names()
1125                 avatars.sort()
1126                 for avatar in avatars: message += "$(eol)   $(grn)" + avatar + "$(nrm)"
1127         elif parameters == "files":
1128                 message = "These are the current files containing the universe:$(eol)"
1129                 keys = universe.files.keys()
1130                 keys.sort()
1131                 for key in keys: message += "$(eol)   $(grn)" + key + "$(nrm)"
1132         elif parameters == "universe":
1133                 message = "These are the current elements in the universe:$(eol)"
1134                 keys = universe.contents.keys()
1135                 keys.sort()
1136                 for key in keys: message += "$(eol)   $(grn)" + key + "$(nrm)"
1137         elif parameters == "time":
1138                 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1139         elif parameters: message = "I don't know what \"" + parameters + "\" is."
1140         else: message = "What do you want to show?"
1141         user.send(message)
1142
1143 def command_error(user, command="", parameters=""):
1144         """Generic error for an unrecognized command word."""
1145
1146         # 90% of the time use a generic error
1147         if randrange(10):
1148                 message = "I'm not sure what \"" + command
1149                 if parameters:
1150                         message += " " + parameters
1151                 message += "\" means..."
1152
1153         # 10% of the time use the classic diku error
1154         else:
1155                 message = "Arglebargle, glop-glyf!?!"
1156
1157         # send the error message
1158         user.send(message)
1159
1160 # if there is no universe, create an empty one
1161 if not "universe" in locals(): universe = Universe()
1162