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