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