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 = str(value)
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:" + str(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:" + str(counter), universe)
407                 avatars = self.account.getlist("avatars")
408                 avatars.append(self.avatar.key)
409                 self.account.set("avatars", avatars)
410
411         def delete_avatar(self, avatar, universe):
412                 """Remove an avatar from the world and from the user's list."""
413                 if self.avatar is universe.contents[avatar]: self.avatar = None
414                 universe.contents[avatar].delete()
415                 avatars = self.account.getlist("avatars")
416                 avatars.remove(avatar)
417                 self.account.set("avatars", avatars)
418
419         def list_avatar_names(self):
420                 """List names of assigned avatars."""
421                 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
422
423 def makelist(value):
424         """Turn string into list type."""
425         if value[0] + value[-1] == "[]": return eval(value)
426         else: return [ value ]
427
428 def makedict(value):
429         """Turn string into dict type."""
430         if value[0] + value[-1] == "{}": return eval(value)
431         elif value.find(":") > 0: return eval("{" + value + "}")
432         else: return { value: None }
433
434 def broadcast(message):
435         """Send a message to all connected users."""
436         for each_user in universe.userlist: each_user.send("$(eol)" + message)
437
438 def log(message):
439         """Log a message."""
440
441         # the time in posix log timestamp format
442         timestamp = asctime()[4:19]
443
444         # send the timestamp and message to standard output
445         print(timestamp + " " + message)
446
447 def wrap_ansi_text(text, width):
448         """Wrap text with arbitrary width while ignoring ANSI colors."""
449
450         # the current position in the entire text string, including all
451         # characters, printable or otherwise
452         absolute_position = 0
453
454         # the current text position relative to the begining of the line,
455         # ignoring color escape sequences
456         relative_position = 0
457
458         # whether the current character is part of a color escape sequence
459         escape = False
460
461         # iterate over each character from the begining of the text
462         for each_character in text:
463
464                 # the current character is the escape character
465                 if each_character == chr(27):
466                         escape = True
467
468                 # the current character is within an escape sequence
469                 elif escape:
470
471                         # the current character is m, which terminates the
472                         # current escape sequence
473                         if each_character == "m":
474                                 escape = False
475
476                 # the current character is a newline, so reset the relative
477                 # position (start a new line)
478                 elif each_character == "\n":
479                         relative_position = 0
480
481                 # the current character meets the requested maximum line width,
482                 # so we need to backtrack and find a space at which to wrap
483                 elif relative_position == width:
484
485                         # distance of the current character examined from the
486                         # relative position
487                         wrap_offset = 0
488
489                         # count backwards until we find a space
490                         while text[absolute_position - wrap_offset] != " ":
491                                 wrap_offset += 1
492
493                         # insert an eol in place of the space
494                         text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
495
496                         # increase the absolute position because an eol is two
497                         # characters but the space it replaced was only one
498                         absolute_position += 1
499
500                         # now we're at the begining of a new line, plus the
501                         # number of characters wrapped from the previous line
502                         relative_position = wrap_offset
503
504                 # as long as the character is not a carriage return and the
505                 # other above conditions haven't been met, count it as a
506                 # printable character
507                 elif each_character != "\r":
508                         relative_position += 1
509
510                 # increase the absolute position for every character
511                 absolute_position += 1
512
513         # return the newly-wrapped text
514         return text
515
516 def weighted_choice(data):
517         """Takes a dict weighted by value and returns a random key."""
518
519         # this will hold our expanded list of keys from the data
520         expanded = []
521
522         # create thee expanded list of keys
523         for key in data.keys():
524                 for count in range(data[key]):
525                         expanded.append(key)
526
527         # return one at random
528         return choice(expanded)
529
530 def random_name():
531         """Returns a random character name."""
532
533         # the vowels and consonants needed to create romaji syllables
534         vowels = [ "a", "i", "u", "e", "o" ]
535         consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
536
537         # this dict will hold our weighted list of syllables
538         syllables = {}
539
540         # generate the list with an even weighting
541         for consonant in consonants:
542                 for vowel in vowels:
543                         syllables[consonant + vowel] = 1
544
545         # we'll build the name into this string
546         name = ""
547
548         # create a name of random length from the syllables
549         for syllable in range(randrange(2, 6)):
550                 name += weighted_choice(syllables)
551
552         # strip any leading quotemark, capitalize and return the name
553         return name.strip("'").capitalize()
554
555 def replace_macros(user, text, is_input=False):
556         """Replaces macros in text output."""
557
558         # loop until broken
559         while True:
560
561                 # third person pronouns
562                 pronouns = {
563                         "female": { "obj": "her", "pos": "hers", "sub": "she" },
564                         "male": { "obj": "him", "pos": "his", "sub": "he" },
565                         "neuter": { "obj": "it", "pos": "its", "sub": "it" }
566                         }
567
568                 # a dict of replacement macros
569                 macros = {
570                         "$(eol)": "\r\n",
571                         "$(bld)": chr(27) + "[1m",
572                         "$(nrm)": chr(27) + "[0m",
573                         "$(blk)": chr(27) + "[30m",
574                         "$(grn)": chr(27) + "[32m",
575                         "$(red)": chr(27) + "[31m",
576                         }
577
578                 # add dynamic macros where possible
579                 if user.account:
580                         account_name = user.account.get("name")
581                         if account_name:
582                                 macros["$(account)"] = account_name
583                 if user.avatar:
584                         avatar_gender = user.avatar.get("gender")
585                         if avatar_gender:
586                                 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
587                                 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
588                                 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
589
590                 # find and replace per the macros dict
591                 macro_start = text.find("$(")
592                 if macro_start == -1: break
593                 macro_end = text.find(")", macro_start) + 1
594                 macro = text[macro_start:macro_end]
595                 if macro in macros.keys():
596                         text = text.replace(macro, macros[macro])
597
598                 # if we get here, log and replace it with null
599                 else:
600                         text = text.replace(macro, "")
601                         if not is_input:
602                                 log("Unexpected replacement macro " + macro + " encountered.")
603
604         # replace the look-like-a-macro sequence
605         text = text.replace("$_(", "$(")
606
607         return text
608
609 def check_time(frequency):
610         """Check for a factor of the current increment count."""
611         if type(frequency) is str:
612                 frequency = universe.categories["internal"]["time"].getint(frequency)
613         if not "counters" in universe.categories["internal"]:
614                 Element("internal:counters", universe)
615         return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
616
617 def on_pulse():
618         """The things which should happen on each pulse, aside from reloads."""
619
620         # open the listening socket if it hasn't been already
621         if not hasattr(universe, "listening_socket"):
622                 universe.initialize_server_socket()
623
624         # assign a user if a new connection is waiting
625         user = check_for_connection(universe.listening_socket)
626         if user: universe.userlist.append(user)
627
628         # iterate over the connected users
629         for user in universe.userlist: user.pulse()
630
631         # update the log every now and then
632         if check_time("frequency_log"):
633                 log(str(len(universe.userlist)) + " connection(s)")
634
635         # periodically save everything
636         if check_time("frequency_save"):
637                 universe.save()
638
639         # pause for a configurable amount of time (decimal seconds)
640         sleep(universe.categories["internal"]["time"].getfloat("increment"))
641
642         # increment the elapsed increment counter
643         universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
644
645 def reload_data():
646         """Reload data into new persistent objects."""
647         for user in universe.userlist[:]: user.reload()
648
649 def check_for_connection(listening_socket):
650         """Check for a waiting connection and return a new user object."""
651
652         # try to accept a new connection
653         try:
654                 connection, address = listening_socket.accept()
655         except:
656                 return None
657
658         # note that we got one
659         log("Connection from " + address[0])
660
661         # disable blocking so we can proceed whether or not we can send/receive
662         connection.setblocking(0)
663
664         # create a new user object
665         user = User()
666
667         # associate this connection with it
668         user.connection = connection
669
670         # set the user's ipa from the connection's ipa
671         user.address = address[0]
672
673         # return the new user object
674         return user
675
676 def get_menu(state, error=None, echoing=True, choices={}):
677         """Show the correct menu text to a user."""
678
679         # begin with a telnet echo command sequence if needed
680         message = get_echo_sequence(state, echoing)
681
682         # get the description or error text
683         message += get_menu_description(state, error)
684
685         # get menu choices for the current state
686         message += get_formatted_menu_choices(state, choices)
687
688         # try to get a prompt, if it was defined
689         message += get_menu_prompt(state)
690
691         # throw in the default choice, if it exists
692         message += get_formatted_default_menu_choice(state)
693
694         # display a message indicating if echo is off
695         message += get_echo_message(state)
696
697         # return the assembly of various strings defined above
698         return message
699
700 def menu_echo_on(state):
701         """True if echo is on, false if it is off."""
702         return universe.categories["menu"][state].getboolean("echo", True)
703
704 def get_echo_sequence(state, echoing):
705         """Build the appropriate IAC ECHO sequence as needed."""
706
707         # if the user has echo on and the menu specifies it should be turned
708         # off, send: iac + will + echo + null
709         if echoing and not menu_echo_on(state): return chr(255) + chr(251) + chr(1) + chr(0)
710
711         # if echo is not set to off in the menu and the user curently has echo
712         # off, send: iac + wont + echo + null
713         elif not echoing and menu_echo_on(state): return chr(255) + chr(252) + chr(1) + chr(0)
714
715         # default is not to send an echo control sequence at all
716         else: return ""
717
718 def get_echo_message(state):
719         """Return a message indicating that echo is off."""
720         if menu_echo_on(state): return ""
721         else: return "(won't echo) "
722
723 def get_default_menu_choice(state):
724         """Return the default choice for a menu."""
725         return universe.categories["menu"][state].get("default")
726
727 def get_formatted_default_menu_choice(state):
728         """Default menu choice foratted for inclusion in a prompt string."""
729         default = get_default_menu_choice(state)
730         if default: return "[$(red)" + default + "$(nrm)] "
731         else: return ""
732
733 def get_menu_description(state, error):
734         """Get the description or error text."""
735
736         # an error condition was raised by the handler
737         if error:
738
739                 # try to get an error message matching the condition
740                 # and current state
741                 description = universe.categories["menu"][state].get("error_" + error)
742                 if not description: description = "That is not a valid choice..."
743                 description = "$(red)" + description + "$(nrm)"
744
745         # there was no error condition
746         else:
747
748                 # try to get a menu description for the current state
749                 description = universe.categories["menu"][state].get("description")
750
751         # return the description or error message
752         if description: description += "$(eol)$(eol)"
753         return description
754
755 def get_menu_prompt(state):
756         """Try to get a prompt, if it was defined."""
757         prompt = universe.categories["menu"][state].get("prompt")
758         if prompt: prompt += " "
759         return prompt
760
761 def get_menu_choices(user):
762         """Return a dict of choice:meaning."""
763         menu = universe.categories["menu"][user.state]
764         create_choices = menu.get("create")
765         if create_choices: choices = eval(create_choices)
766         else: choices = {}
767         ignores = []
768         options = {}
769         creates = {}
770         for facet in menu.facets():
771                 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
772                         ignores.append(facet.split("_", 2)[1])
773                 elif facet.startswith("create_"):
774                         creates[facet] = facet.split("_", 2)[1]
775                 elif facet.startswith("choice_"):
776                         options[facet] = facet.split("_", 2)[1]
777         for facet in creates.keys():
778                 if not creates[facet] in ignores:
779                         choices[creates[facet]] = eval(menu.get(facet))
780         for facet in options.keys():
781                 if not options[facet] in ignores:
782                         choices[options[facet]] = menu.get(facet)
783         return choices
784
785 def get_formatted_menu_choices(state, choices):
786         """Returns a formatted string of menu choices."""
787         choice_output = ""
788         choice_keys = choices.keys()
789         choice_keys.sort()
790         for choice in choice_keys:
791                 choice_output += "   [$(red)" + choice + "$(nrm)]  " + choices[choice] + "$(eol)"
792         if choice_output: choice_output += "$(eol)"
793         return choice_output
794
795 def get_menu_branches(state):
796         """Return a dict of choice:branch."""
797         branches = {}
798         for facet in universe.categories["menu"][state].facets():
799                 if facet.startswith("branch_"):
800                         branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
801         return branches
802
803 def get_default_branch(state):
804         """Return the default branch."""
805         return universe.categories["menu"][state].get("branch")
806
807 def get_choice_branch(user, choice):
808         """Returns the new state matching the given choice."""
809         branches = get_menu_branches(user.state)
810         if not choice: choice = get_default_menu_choice(user.state)
811         if choice in branches.keys(): return branches[choice]
812         elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
813         else: return ""
814
815 def get_menu_actions(state):
816         """Return a dict of choice:branch."""
817         actions = {}
818         for facet in universe.categories["menu"][state].facets():
819                 if facet.startswith("action_"):
820                         actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
821         return actions
822
823 def get_default_action(state):
824         """Return the default action."""
825         return universe.categories["menu"][state].get("action")
826
827 def get_choice_action(user, choice):
828         """Run any indicated script for the given choice."""
829         actions = get_menu_actions(user.state)
830         if not choice: choice = get_default_menu_choice(user.state)
831         if choice in actions.keys(): return actions[choice]
832         elif choice in user.menu_choices.keys(): return get_default_action(user.state)
833         else: return ""
834
835 def handle_user_input(user):
836         """The main handler, branches to a state-specific handler."""
837
838         # check to make sure the state is expected, then call that handler
839         if "handler_" + user.state in globals():
840                 exec("handler_" + user.state + "(user)")
841         else:
842                 generic_menu_handler(user)
843
844         # since we got input, flag that the menu/prompt needs to be redisplayed
845         user.menu_seen = False
846
847         # if the user's client echo is off, send a blank line for aesthetics
848         if not user.echoing: user.send("", "")
849
850 def generic_menu_handler(user):
851         """A generic menu choice handler."""
852
853         # get a lower-case representation of the next line of input
854         if user.input_queue:
855                 choice = user.input_queue.pop(0)
856                 if choice: choice = choice.lower()
857         else: choice = ""
858
859         if choice in user.menu_choices:
860                 exec(get_choice_action(user, choice))
861                 new_state = get_choice_branch(user, choice)
862                 if new_state: user.state = new_state
863         else: user.error = "default"
864
865 def handler_entering_account_name(user):
866         """Handle the login account name."""
867
868         # get the next waiting line of input
869         input_data = user.input_queue.pop(0)
870
871         # did the user enter anything?
872         if input_data:
873                 
874                 # keep only the first word and convert to lower-case
875                 name = input_data.lower()
876
877                 # fail if there are non-alphanumeric characters
878                 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
879                         user.error = "bad_name"
880
881                 # if that account exists, time to request a password
882                 elif name in universe.categories["account"]:
883                         user.account = universe.categories["account"][name]
884                         user.state = "checking_password"
885
886                 # otherwise, this could be a brand new user
887                 else:
888                         user.account = Element("account:" + name, universe)
889                         user.account.set("name", name)
890                         log("New user: " + name)
891                         user.state = "checking_new_account_name"
892
893         # if the user entered nothing for a name, then buhbye
894         else:
895                 user.state = "disconnecting"
896
897 def handler_checking_password(user):
898         """Handle the login account password."""
899
900         # get the next waiting line of input
901         input_data = user.input_queue.pop(0)
902
903         # does the hashed input equal the stored hash?
904         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
905
906                 # if so, set the username and load from cold storage
907                 if not user.replace_old_connections():
908                         user.authenticate()
909                         user.state = "main_utility"
910
911         # if at first your hashes don't match, try, try again
912         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
913                 user.password_tries += 1
914                 user.error = "incorrect"
915
916         # we've exceeded the maximum number of password failures, so disconnect
917         else:
918                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
919                 user.state = "disconnecting"
920
921 def handler_entering_new_password(user):
922         """Handle a new password entry."""
923
924         # get the next waiting line of input
925         input_data = user.input_queue.pop(0)
926
927         # make sure the password is strong--at least one upper, one lower and
928         # one digit, seven or more characters in length
929         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)):
930
931                 # hash and store it, then move on to verification
932                 user.account.set("passhash",  new_md5(user.account.get("name") + input_data).hexdigest())
933                 user.state = "verifying_new_password"
934
935         # the password was weak, try again if you haven't tried too many times
936         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
937                 user.password_tries += 1
938                 user.error = "weak"
939
940         # too many tries, so adios
941         else:
942                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
943                 user.account.delete()
944                 user.state = "disconnecting"
945
946 def handler_verifying_new_password(user):
947         """Handle the re-entered new password for verification."""
948
949         # get the next waiting line of input
950         input_data = user.input_queue.pop(0)
951
952         # hash the input and match it to storage
953         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
954                 user.authenticate()
955
956                 # the hashes matched, so go active
957                 if not user.replace_old_connections(): user.state = "main_utility"
958
959         # go back to entering the new password as long as you haven't tried
960         # too many times
961         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
962                 user.password_tries += 1
963                 user.error = "differs"
964                 user.state = "entering_new_password"
965
966         # otherwise, sayonara
967         else:
968                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
969                 user.account.delete()
970                 user.state = "disconnecting"
971
972 def handler_active(user):
973         """Handle input for active users."""
974
975         # get the next waiting line of input
976         input_data = user.input_queue.pop(0)
977
978         # split out the command (first word) and parameters (everything else)
979         if input_data.find(" ") > 0:
980                 command, parameters = input_data.split(" ", 1)
981         else:
982                 command = input_data
983                 parameters = ""
984
985         # lowercase the command
986         command = command.lower()
987
988         # the command matches a command word for which we have data
989         if command in universe.categories["command"]:
990                 exec(universe.categories["command"][command].get("action"))
991
992         # no data matching the entered command word
993         elif command: command_error(user, command, parameters)
994
995 def command_halt(user, command="", parameters=""):
996         """Halt the world."""
997
998         # see if there's a message or use a generic one
999         if parameters: message = "Halting: " + parameters
1000         else: message = "User " + user.account.get("name") + " halted the world."
1001
1002         # let everyone know
1003         broadcast(message)
1004         log(message)
1005
1006         # set a flag to terminate the world
1007         universe.terminate_world = True
1008
1009 def command_reload(user, command="", parameters=""):
1010         """Reload all code modules, configs and data."""
1011
1012         # let the user know and log
1013         user.send("Reloading all code modules, configs and data.")
1014         log("User " + user.account.get("name") + " reloaded the world.")
1015
1016         # set a flag to reload
1017         universe.reload_modules = True
1018
1019 def command_quit(user, command="", parameters=""):
1020         """Quit the world."""
1021         user.state = "main_utility"
1022
1023 def command_help(user, command="", parameters=""):
1024         """List available commands and provide help for commands."""
1025
1026         # did the user ask for help on a specific command word?
1027         if parameters:
1028
1029                 # is the command word one for which we have data?
1030                 if parameters in universe.categories["command"]:
1031
1032                         # add a description if provided
1033                         description = universe.categories["command"][parameters].get("description")
1034                         if not description:
1035                                 description = "(no short description provided)"
1036                         output = "$(grn)" + parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1037
1038                         # add the help text if provided
1039                         help_text = universe.categories["command"][parameters].get("help")
1040                         if not help_text:
1041                                 help_text = "No help is provided for this command."
1042                         output += help_text
1043
1044                 # no data for the requested command word
1045                 else:
1046                         output = "That is not an available command."
1047
1048         # no specific command word was indicated
1049         else:
1050
1051                 # give a sorted list of commands with descriptions if provided
1052                 output = "These are the commands available to you:$(eol)$(eol)"
1053                 sorted_commands = universe.categories["command"].keys()
1054                 sorted_commands.sort()
1055                 for item in sorted_commands:
1056                         description = universe.categories["command"][item].get("description")
1057                         if not description:
1058                                 description = "(no short description provided)"
1059                         output += "   $(grn)" + item + "$(nrm) - " + description + "$(eol)"
1060                 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1061
1062         # send the accumulated output to the user
1063         user.send(output)
1064
1065 def command_say(user, command="", parameters=""):
1066         """Speak to others in the same room."""
1067
1068         # check for replacement macros
1069         if replace_macros(user, parameters, True) != parameters:
1070                 user.send("You cannot speak $_(replacement macros).")
1071
1072         # the user entered a message
1073         elif parameters:
1074
1075                 # get rid of quote marks on the ends of the message and
1076                 # capitalize the first letter
1077                 message = parameters.strip("\"'`").capitalize()
1078
1079                 # a dictionary of punctuation:action pairs
1080                 actions = {}
1081                 for facet in universe.categories["internal"]["language"].facets():
1082                         if facet.startswith("punctuation_"):
1083                                 action = facet.split("_")[1]
1084                                 for mark in universe.categories["internal"]["language"].getlist(facet):
1085                                                 actions[mark] = action
1086
1087                 # match the punctuation used, if any, to an action
1088                 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1089                 action = actions[default_punctuation]
1090                 for mark in actions.keys():
1091                         if message.endswith(mark) and mark != default_punctuation:
1092                                 action = actions[mark]
1093                                 break
1094
1095                 # if the action is default and there is no mark, add one
1096                 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1097                         message += default_punctuation
1098
1099                 # capitalize a list of words within the message
1100                 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1101                 for word in capitalize_words:
1102                         message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1103
1104                 # tell the room
1105                 # TODO: we won't be using broadcast once there are actual rooms
1106                 broadcast(user.account.get("name") + " " + action + "s, \"" + message + "\"")
1107
1108         # there was no message
1109         else:
1110                 user.send("What do you want to say?")
1111
1112 def command_show(user, command="", parameters=""):
1113         """Show program data."""
1114         if parameters == "avatars":
1115                 message = "These are the avatars managed by your account:$(eol)"
1116                 avatars = user.list_avatar_names()
1117                 avatars.sort()
1118                 for avatar in avatars: message += "$(eol)   $(grn)" + avatar + "$(nrm)"
1119         elif parameters == "files":
1120                 message = "These are the current files containing the universe:$(eol)"
1121                 keys = universe.files.keys()
1122                 keys.sort()
1123                 for key in keys: message += "$(eol)   $(grn)" + key + "$(nrm)"
1124         elif parameters == "universe":
1125                 message = "These are the current elements in the universe:$(eol)"
1126                 keys = universe.contents.keys()
1127                 keys.sort()
1128                 for key in keys: message += "$(eol)   $(grn)" + key + "$(nrm)"
1129         elif parameters == "time":
1130                 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1131         elif parameters: message = "I don't know what \"" + parameters + "\" is."
1132         else: message = "What do you want to show?"
1133         user.send(message)
1134
1135 def command_error(user, command="", parameters=""):
1136         """Generic error for an unrecognized command word."""
1137
1138         # 90% of the time use a generic error
1139         if randrange(10):
1140                 message = "I'm not sure what \"" + command
1141                 if parameters:
1142                         message += " " + parameters
1143                 message += "\" means..."
1144
1145         # 10% of the time use the classic diku error
1146         else:
1147                 message = "Arglebargle, glop-glyf!?!"
1148
1149         # send the error message
1150         user.send(message)
1151
1152 # if there is no universe, create an empty one
1153 if not "universe" in locals(): universe = Universe()
1154