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 re import match
13 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
14 from stat import S_IMODE, ST_MODE
15 from sys import stderr
16 from syslog import LOG_PID, LOG_INFO, LOG_DAEMON, closelog, openlog, syslog
17 from telnetlib import DO, DONT, ECHO, EOR, GA, IAC, LINEMODE, SB, SE, SGA, WILL, WONT
18 from time import asctime, sleep
19 from traceback import format_exception
20
21 def excepthook(excepttype, value, traceback):
22         """Handle uncaught exceptions."""
23
24         # assemble the list of errors into a single string
25         message = "".join(format_exception(excepttype, value, traceback))
26
27         # try to log it, if possible
28         try: log(message, 9)
29         except: pass
30
31         # try to write it to stderr, if possible
32         try: stderr.write(message)
33         except: pass
34
35 # redefine sys.excepthook with ours
36 import sys
37 sys.excepthook = excepthook
38
39 class Element:
40         """An element of the universe."""
41         def __init__(self, key, universe, filename=""):
42                 """Set up a new element."""
43
44                 # not owned by a user by default (used for avatars)
45                 self.owner = None
46
47                 # no contents in here by default
48                 self.contents = {}
49
50                 # keep track of our key name
51                 self.key = key
52
53                 # parse out appropriate category and subkey names, add to list
54                 if self.key.find(":") > 0:
55                         self.category, self.subkey = self.key.split(":", 1)
56                 else:
57                         self.category = "other"
58                         self.subkey = self.key
59                 if not self.category in universe.categories: self.category = "other"
60                 universe.categories[self.category][self.subkey] = self
61
62                 # get an appropriate filename for the origin
63                 if not filename: filename = universe.default_origins[self.category]
64                 if not isabs(filename): filename = abspath(filename)
65
66                 # add the file if it doesn't exist yet
67                 if not filename in universe.files: DataFile(filename, universe)
68
69                 # record a pointer to the origin file
70                 self.origin = universe.files[filename]
71
72                 # add a data section to the origin if necessary
73                 if not self.origin.data.has_section(self.key):
74                         self.origin.data.add_section(self.key)
75
76                 # add this element to the universe contents
77                 universe.contents[self.key] = self
78
79         def destroy(self):
80                 """Remove an element from the universe and destroy it."""
81                 log("Destroying: " + self.key + ".", 2)
82                 self.origin.data.remove_section(self.key)
83                 del universe.categories[self.category][self.subkey]
84                 del universe.contents[self.key]
85                 del self
86         def facets(self):
87                 """Return a list of non-inherited facets for this element."""
88                 if self.key in self.origin.data.sections():
89                         return self.origin.data.options(self.key)
90                 else: return []
91         def has_facet(self, facet):
92                 """Return whether the non-inherited facet exists."""
93                 return facet in self.facets()
94         def remove_facet(self, facet):
95                 """Remove a facet from the element."""
96                 if self.has_facet(facet):
97                         self.origin.data.remove_option(self.key, facet)
98                         self.origin.modified = True
99         def ancestry(self):
100                 """Return a list of the element's inheritance lineage."""
101                 if self.has_facet("inherit"):
102                         ancestry = self.getlist("inherit")
103                         for parent in ancestry[:]:
104                                 ancestors = universe.contents[parent].ancestry()
105                                 for ancestor in ancestors:
106                                         if ancestor not in ancestry: ancestry.append(ancestor)
107                         return ancestry
108                 else: return []
109         def get(self, facet, default=None):
110                 """Retrieve values."""
111                 if default is None: default = ""
112                 if self.origin.data.has_option(self.key, facet):
113                         return self.origin.data.get(self.key, facet)
114                 elif self.has_facet("inherit"):
115                         for ancestor in self.ancestry():
116                                 if universe.contents[ancestor].has_facet(facet):
117                                         return universe.contents[ancestor].get(facet)
118                 else: return default
119         def getboolean(self, facet, default=None):
120                 """Retrieve values as boolean type."""
121                 if default is None: default=False
122                 if self.origin.data.has_option(self.key, facet):
123                         return self.origin.data.getboolean(self.key, facet)
124                 elif self.has_facet("inherit"):
125                         for ancestor in self.ancestry():
126                                 if universe.contents[ancestor].has_facet(facet):
127                                         return universe.contents[ancestor].getboolean(facet)
128                 else: return default
129         def getint(self, facet, default=None):
130                 """Return values as int/long type."""
131                 if default is None: default = 0
132                 if self.origin.data.has_option(self.key, facet):
133                         return self.origin.data.getint(self.key, facet)
134                 elif self.has_facet("inherit"):
135                         for ancestor in self.ancestry():
136                                 if universe.contents[ancestor].has_facet(facet):
137                                         return universe.contents[ancestor].getint(facet)
138                 else: return default
139         def getfloat(self, facet, default=None):
140                 """Return values as float type."""
141                 if default is None: default = 0.0
142                 if self.origin.data.has_option(self.key, facet):
143                         return self.origin.data.getfloat(self.key, facet)
144                 elif self.has_facet("inherit"):
145                         for ancestor in self.ancestry():
146                                 if universe.contents[ancestor].has_facet(facet):
147                                         return universe.contents[ancestor].getfloat(facet)
148                 else: return default
149         def getlist(self, facet, default=None):
150                 """Return values as list type."""
151                 if default is None: default = []
152                 value = self.get(facet)
153                 if value: return makelist(value)
154                 else: return default
155         def getdict(self, facet, default=None):
156                 """Return values as dict type."""
157                 if default is None: default = {}
158                 value = self.get(facet)
159                 if value: return makedict(value)
160                 else: return default
161         def set(self, facet, value):
162                 """Set values."""
163                 if not self.has_facet(facet) or not self.get(facet) == value:
164                         if type(value) is long: value = str(value)
165                         elif not type(value) is str: value = repr(value)
166                         self.origin.data.set(self.key, facet, value)
167                         self.origin.modified = True
168         def append(self, facet, value):
169                 """Append value tp a list."""
170                 if type(value) is long: value = str(value)
171                 elif not type(value) is str: value = repr(value)
172                 newlist = self.getlist(facet)
173                 newlist.append(value)
174                 self.set(facet, newlist)
175         def send(self, message, eol="$(eol)"):
176                 """Convenience method to pass messages to an owner."""
177                 if self.owner: self.owner.send(message, eol)
178         def go_to(self, location):
179                 """Relocate the element to a specific location."""
180                 current = self.get("location")
181                 if current and self.key in universe.contents[current].contents:
182                         del universe.contents[current].contents[self.key]
183                 if location in universe.contents: self.set("location", location)
184                 universe.contents[location].contents[self.key] = self
185                 self.look_at(location)
186         def go_home(self):
187                 """Relocate the element to its default location."""
188                 self.go_to(self.get("default_location"))
189                 self.echo_to_location("You suddenly realize that " + self.get("name") + " is here.")
190         def move_direction(self, direction):
191                 """Relocate the element in a specified direction."""
192                 self.echo_to_location(self.get("name") + " exits " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
193                 self.send("You exit " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
194                 self.go_to(universe.contents[self.get("location")].link_neighbor(direction))
195                 self.echo_to_location(self.get("name") + " arrives from " + universe.categories["internal"]["directions"].getdict(direction)["enter"] + ".")
196         def look_at(self, key):
197                 """Show an element to another element."""
198                 if self.owner:
199                         element = universe.contents[key]
200                         message = ""
201                         name = element.get("name")
202                         if name: message += "$(cyn)" + name + "$(nrm)$(eol)"
203                         description = element.get("description")
204                         if description: message += description + "$(eol)"
205                         portal_list = element.portals().keys()
206                         if portal_list:
207                                 portal_list.sort()
208                                 message += "$(cyn)[ Exits: " + ", ".join(portal_list) + " ]$(nrm)$(eol)"
209                         for element in universe.contents[self.get("location")].contents.values():
210                                 if element.getboolean("is_actor") and element is not self:
211                                         message += "$(yel)" + element.get("name") + " is here.$(nrm)$(eol)"
212                         self.send(message)
213         def portals(self):
214                 """Map the portal directions for a room to neighbors."""
215                 portals = {}
216                 if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
217                         coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
218                         directions = universe.categories["internal"]["directions"]
219                         offsets = dict([(x, directions.getdict(x)["vector"]) for x in directions.facets()])
220                         for portal in self.getlist("gridlinks"):
221                                 adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
222                                 neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
223                                 if neighbor in universe.contents: portals[portal] = neighbor
224                 for facet in self.facets():
225                         if facet.startswith("link_"):
226                                 neighbor = self.get(facet)
227                                 if neighbor in universe.contents:
228                                         portal = facet.split("_")[1]
229                                         portals[portal] = neighbor
230                 return portals
231         def link_neighbor(self, direction):
232                 """Return the element linked in a given direction."""
233                 portals = self.portals()
234                 if direction in portals: return portals[direction]
235         def echo_to_location(self, message):
236                 """Show a message to other elements in the current location."""
237                 for element in universe.contents[self.get("location")].contents.values():
238                         if element is not self: element.send(message)
239
240 class DataFile:
241         """A file containing universe elements."""
242         def __init__(self, filename, universe):
243                 self.modified = False
244                 self.data = RawConfigParser()
245                 if access(filename, R_OK): self.data.read(filename)
246                 self.filename = filename
247                 universe.files[filename] = self
248                 if self.data.has_option("__control__", "include_files"):
249                         includes = makelist(self.data.get("__control__", "include_files"))
250                 else: includes = []
251                 if self.data.has_option("__control__", "default_files"):
252                         origins = makedict(self.data.get("__control__", "default_files"))
253                         for key in origins.keys():
254                                 if not key in includes: includes.append(key)
255                                 universe.default_origins[key] = origins[key]
256                                 if not key in universe.categories:
257                                         universe.categories[key] = {}
258                 if self.data.has_option("__control__", "private_files"):
259                         for item in makelist(self.data.get("__control__", "private_files")):
260                                 if not item in includes: includes.append(item)
261                                 if not item in universe.private_files:
262                                         if not isabs(item):
263                                                 item = path_join(dirname(filename), item)
264                                         universe.private_files.append(item)
265                 for section in self.data.sections():
266                         if section != "__control__":
267                                 Element(section, universe, filename)
268                 for include_file in includes:
269                         if not isabs(include_file):
270                                 include_file = path_join(dirname(filename), include_file)
271                         DataFile(include_file, universe)
272         def is_writeable(self):
273                 """Returns True if the __control__ read_only is False."""
274                 return not self.data.has_option("__control__", "read_only") or not self.data.getboolean("__control__", "read_only")
275         def save(self):
276                 """Write the data, if necessary."""
277
278                 # when modified, writeable and has content or the file exists
279                 if self.modified and self.is_writeable() and ( self.data.sections() or exists(self.filename) ):
280
281                         # make parent directories if necessary
282                         if not exists(dirname(self.filename)):
283                                 makedirs(dirname(self.filename))
284
285                         # our data file
286                         file_descriptor = file(self.filename, "w")
287
288                         # if it's marked private, chmod it appropriately
289                         if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
290                                 chmod(self.filename, 0600)
291
292                         # write it back sorted, instead of using ConfigParser
293                         sections = self.data.sections()
294                         sections.sort()
295                         for section in sections:
296                                 file_descriptor.write("[" + section + "]\n")
297                                 options = self.data.options(section)
298                                 options.sort()
299                                 for option in options:
300                                         file_descriptor.write(option + " = " + self.data.get(section, option) + "\n")
301                                 file_descriptor.write("\n")
302
303                         # flush and close the file
304                         file_descriptor.flush()
305                         file_descriptor.close()
306
307 class Universe:
308         """The universe."""
309         def __init__(self, filename=""):
310                 """Initialize the universe."""
311                 self.categories = {}
312                 self.contents = {}
313                 self.default_origins = {}
314                 self.files = {}
315                 self.private_files = []
316                 self.loglist = []
317                 self.userlist = []
318                 self.terminate_world = False
319                 self.reload_modules = False
320                 if not filename:
321                         possible_filenames = [
322                                 ".mudpyrc",
323                                 ".mudpy/mudpyrc",
324                                 ".mudpy/mudpy.conf",
325                                 "mudpy.conf",
326                                 "etc/mudpy.conf",
327                                 "/usr/local/mudpy/mudpy.conf",
328                                 "/usr/local/mudpy/etc/mudpy.conf",
329                                 "/etc/mudpy/mudpy.conf",
330                                 "/etc/mudpy.conf"
331                                 ]
332                         for filename in possible_filenames:
333                                 if access(filename, R_OK): break
334                 if not isabs(filename):
335                         filename = abspath(filename)
336                 DataFile(filename, self)
337         def save(self):
338                 """Save the universe to persistent storage."""
339                 for key in self.files: self.files[key].save()
340
341         def initialize_server_socket(self):
342                 """Create and open the listening socket."""
343
344                 # create a new ipv4 stream-type socket object
345                 self.listening_socket = socket(AF_INET, SOCK_STREAM)
346
347                 # set the socket options to allow existing open ones to be
348                 # reused (fixes a bug where the server can't bind for a minute
349                 # when restarting on linux systems)
350                 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
351
352                 # bind the socket to to our desired server ipa and port
353                 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
354
355                 # disable blocking so we can proceed whether or not we can
356                 # send/receive
357                 self.listening_socket.setblocking(0)
358
359                 # start listening on the socket
360                 self.listening_socket.listen(1)
361
362                 # note that we're now ready for user connections
363                 log("Waiting for connection(s)...")
364
365 class User:
366         """This is a connected user."""
367
368         def __init__(self):
369                 """Default values for the in-memory user variables."""
370                 self.address = ""
371                 self.last_address = ""
372                 self.connection = None
373                 self.authenticated = False
374                 self.password_tries = 0
375                 self.state = "initial"
376                 self.menu_seen = False
377                 self.error = ""
378                 self.input_queue = []
379                 self.output_queue = []
380                 self.partial_input = ""
381                 self.echoing = True
382                 self.received_newline = True
383                 self.terminator = IAC+GA
384                 self.negotiation_pause = 0
385                 self.avatar = None
386                 self.account = None
387
388         def quit(self):
389                 """Log, close the connection and remove."""
390                 if self.account: name = self.account.get("name")
391                 else: name = ""
392                 if name: message = "User " + name
393                 else: message = "An unnamed user"
394                 message += " logged out."
395                 log(message, 2)
396                 self.deactivate_avatar()
397                 self.connection.close()
398                 self.remove()
399
400         def reload(self):
401                 """Save, load a new user and relocate the connection."""
402
403                 # get out of the list
404                 self.remove()
405
406                 # create a new user object
407                 new_user = User()
408
409                 # set everything else equivalent
410                 for attribute in [
411                         "address",
412                         "last_address",
413                         "connection",
414                         "authenticated",
415                         "password_tries",
416                         "state",
417                         "menu_seen",
418                         "error",
419                         "input_queue",
420                         "output_queue",
421                         "partial_input",
422                         "echoing",
423                         "received_newline",
424                         "terminator",
425                         "negotiation_pause",
426                         "avatar",
427                         "account"
428                         ]:
429                         exec("new_user." + attribute + " = self." + attribute)
430
431                 # add it to the list
432                 universe.userlist.append(new_user)
433
434                 # get rid of the old user object
435                 del(self)
436
437         def replace_old_connections(self):
438                 """Disconnect active users with the same name."""
439
440                 # the default return value
441                 return_value = False
442
443                 # iterate over each user in the list
444                 for old_user in universe.userlist:
445
446                         # the name is the same but it's not us
447                         if old_user.account.get("name") == self.account.get("name") and old_user is not self:
448
449                                 # make a note of it
450                                 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
451                                 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
452
453                                 # close the old connection
454                                 old_user.connection.close()
455
456                                 # replace the old connection with this one
457                                 old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
458                                 old_user.connection = self.connection
459                                 old_user.last_address = old_user.address
460                                 old_user.address = self.address
461                                 old_user.echoing = self.echoing
462
463                                 # take this one out of the list and delete
464                                 self.remove()
465                                 del(self)
466                                 return_value = True
467                                 break
468
469                 # true if an old connection was replaced, false if not
470                 return return_value
471
472         def authenticate(self):
473                 """Flag the user as authenticated and disconnect duplicates."""
474                 if not self.state is "authenticated":
475                         log("User " + self.account.get("name") + " logged in.", 2)
476                         self.authenticated = True
477                         if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
478                                 self.account.set("administrator", "True")
479
480         def show_menu(self):
481                 """Send the user their current menu."""
482                 if not self.menu_seen:
483                         self.menu_choices = get_menu_choices(self)
484                         self.send(get_menu(self.state, self.error, self.echoing, self.terminator, self.menu_choices), "")
485                         self.menu_seen = True
486                         self.error = False
487                         self.adjust_echoing()
488
489         def adjust_echoing(self):
490                 """Adjust echoing to match state menu requirements."""
491                 if self.echoing and not menu_echo_on(self.state): self.echoing = False
492                 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
493
494         def remove(self):
495                 """Remove a user from the list of connected users."""
496                 universe.userlist.remove(self)
497
498         def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
499                 """Send arbitrary text to a connected user."""
500
501                 # unless raw mode is on, clean it up all nice and pretty
502                 if not raw:
503
504                         # strip extra $(eol) off if present
505                         while output.startswith("$(eol)"): output = output[6:]
506                         while output.endswith("$(eol)"): output = output[:-6]
507
508                         # we'll take out GA or EOR and add them back on the end
509                         if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
510                                 terminate = True
511                                 output = output[:-2]
512                         else: terminate = False
513
514                         # start with a newline, append the message, then end
515                         # with the optional eol string passed to this function
516                         # and the ansi escape to return to normal text
517                         if not just_prompt: output = "$(eol)$(eol)" + output
518                         output += eol + chr(27) + "[0m"
519
520                         # tack on a prompt if active
521                         if self.state == "active":
522                                 if not just_prompt: output += "$(eol)"
523                                 if add_prompt: output += "> "
524
525                         # find and replace macros in the output
526                         output = replace_macros(self, output)
527
528                         # wrap the text at 80 characters
529                         output = wrap_ansi_text(output, 80)
530
531                         # tack the terminator back on
532                         if terminate: output += self.terminator
533
534                 # drop the output into the user's output queue
535                 self.output_queue.append(output)
536
537                 # if this is urgent, flush all pending output
538                 if flush: self.flush()
539
540         def pulse(self):
541                 """All the things to do to the user per increment."""
542
543                 # if the world is terminating, disconnect
544                 if universe.terminate_world:
545                         self.state = "disconnecting"
546                         self.menu_seen = False
547
548                 # if output is paused, decrement the counter
549                 if self.state == "initial":
550                         if self.negotiation_pause: self.negotiation_pause -= 1
551                         else: self.state = "entering_account_name"
552
553                 # show the user a menu as needed
554                 elif not self.state == "active": self.show_menu()
555
556                 # flush any pending output in teh queue
557                 self.flush()
558
559                 # disconnect users with the appropriate state
560                 if self.state == "disconnecting": self.quit()
561
562                 # check for input and add it to the queue
563                 self.enqueue_input()
564
565                 # there is input waiting in the queue
566                 if self.input_queue: handle_user_input(self)
567
568         def flush(self):
569                 """Try to send the last item in the queue and remove it."""
570                 if self.output_queue:
571                         if self.received_newline:
572                                 self.received_newline = False
573                                 if self.output_queue[0].startswith("\r\n"):
574                                         self.output_queue[0] = self.output_queue[0][2:]
575                         try:
576                                 self.connection.send(self.output_queue[0])
577                                 del self.output_queue[0]
578                         except:
579                                 pass
580
581
582         def enqueue_input(self):
583                 """Process and enqueue any new input."""
584
585                 # check for some input
586                 try:
587                         input_data = self.connection.recv(1024)
588                 except:
589                         input_data = ""
590
591                 # we got something
592                 if input_data:
593
594                         # tack this on to any previous partial
595                         self.partial_input += input_data
596
597                         # reply to and remove any IAC negotiation codes
598                         self.negotiate_telnet_options()
599
600                         # separate multiple input lines
601                         new_input_lines = self.partial_input.split("\n")
602
603                         # if input doesn't end in a newline, replace the
604                         # held partial input with the last line of it
605                         if not self.partial_input.endswith("\n"):
606                                 self.partial_input = new_input_lines.pop()
607
608                         # otherwise, chop off the extra null input and reset
609                         # the held partial input
610                         else:
611                                 new_input_lines.pop()
612                                 self.partial_input = ""
613
614                         # iterate over the remaining lines
615                         for line in new_input_lines:
616
617                                 # remove a trailing carriage return
618                                 if line.endswith("\r"): line = line.rstrip("\r")
619
620                                 # log non-printable characters remaining
621                                 removed = filter(lambda x: (x < " " or x > "~"), line)
622                                 if removed:
623                                         logline = "Non-printable characters from "
624                                         if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
625                                         else: logline += "unknown user: "
626                                         logline += repr(removed)
627                                         log(logline, 4)
628
629                                 # filter out non-printables
630                                 line = filter(lambda x: " " <= x <= "~", line)
631
632                                 # strip off extra whitespace
633                                 line = line.strip()
634
635                                 # put on the end of the queue
636                                 self.input_queue.append(line)
637
638         def negotiate_telnet_options(self):
639                 """Reply to/remove partial_input telnet negotiation options."""
640
641                 # start at the begining of the input
642                 position = 0
643
644                 # make a local copy to play with
645                 text = self.partial_input
646
647                 # as long as we haven't checked it all
648                 while position < len(text):
649
650                         # jump to the first IAC you find
651                         position = text.find(IAC, position)
652
653                         # if there wasn't an IAC in the input, skip to the end
654                         if position < 0: position = len(text)
655
656                         # replace a double (literal) IAC if there's an LF later
657                         elif len(text) > position+1 and text[position+1] == IAC:
658                                 if text.find("\n", position) > 0: text = text.replace(IAC+IAC, IAC)
659                                 else: position += 1
660                                 position += 1
661
662                         # this must be an option negotiation
663                         elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
664
665                                 negotiation = text[position+1:position+3]
666
667                                 # if we turned echo off, ignore the confirmation
668                                 if not self.echoing and negotiation == DO+ECHO: pass
669
670                                 # allow LINEMODE
671                                 elif negotiation == WILL+LINEMODE: self.send(IAC+DO+LINEMODE, raw=True)
672
673                                 # if the client likes EOR instead of GA, make a note of it
674                                 elif negotiation == DO+EOR: self.terminator = IAC+EOR
675                                 elif negotiation == DONT+EOR and self.terminator == IAC+EOR:
676                                         self.terminator = IAC+GA
677
678                                 # if the client doesn't want GA, oblige
679                                 elif negotiation == DO+SGA and self.terminator == IAC+GA:
680                                         self.terminator = ""
681                                         self.send(IAC+WILL+SGA, raw=True)
682
683                                 # we don't want to allow anything else
684                                 elif text[position+1] == DO: self.send(IAC+WONT+text[position+2], raw=True)
685                                 elif text[position+1] == WILL: self.send(IAC+DONT+text[position+2], raw=True)
686
687                                 # strip the negotiation from the input
688                                 text = text.replace(text[position:position+3], "")
689
690                         # get rid of IAC SB .* IAC SE
691                         elif len(text) > position+4 and text[position:position+2] == IAC+SB:
692                                 end_subnegotiation = text.find(IAC+SE, position)
693                                 if end_subnegotiation > 0: text = text[:position] + text[end_subnegotiation+2:]
694                                 else: position += 1
695
696                         # otherwise, strip out a two-byte IAC command
697                         elif len(text) > position+2: text = text.replace(text[position:position+2], "")
698
699                         # and this means we got the begining of an IAC
700                         else: position += 1
701
702                 # replace the input with our cleaned-up text
703                 self.partial_input = text
704
705         def can_run(self, command):
706                 """Check if the user can run this command object."""
707
708                 # has to be in the commands category
709                 if command not in universe.categories["command"].values(): result = False
710
711                 # administrators can run any command
712                 elif self.account.getboolean("administrator"): result = True
713
714                 # everyone can run non-administrative commands
715                 elif not command.getboolean("administrative"): result = True
716
717                 # otherwise the command cannot be run by this user
718                 else: result = False
719
720                 # pass back the result
721                 return result
722
723         def new_avatar(self):
724                 """Instantiate a new, unconfigured avatar for this user."""
725                 counter = 0
726                 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
727                 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
728                 self.avatar.append("inherit", "archetype:avatar")
729                 self.account.append("avatars", self.avatar.key)
730
731         def delete_avatar(self, avatar):
732                 """Remove an avatar from the world and from the user's list."""
733                 if self.avatar is universe.contents[avatar]: self.avatar = None
734                 universe.contents[avatar].destroy()
735                 avatars = self.account.getlist("avatars")
736                 avatars.remove(avatar)
737                 self.account.set("avatars", avatars)
738
739         def activate_avatar_by_index(self, index):
740                 """Enter the world with a particular indexed avatar."""
741                 self.avatar = universe.contents[self.account.getlist("avatars")[index]]
742                 self.avatar.owner = self
743                 self.state = "active"
744                 self.avatar.go_home()
745
746         def deactivate_avatar(self):
747                 """Have the active avatar leave the world."""
748                 if self.avatar:
749                         current = self.avatar.get("location")
750                         self.avatar.set("default_location", current)
751                         self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
752                         del universe.contents[current].contents[self.avatar.key]
753                         self.avatar.remove_facet("location")
754                         self.avatar.owner = None
755                         self.avatar = None
756
757         def destroy(self):
758                 """Destroy the user and associated avatars."""
759                 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
760                 self.account.destroy()
761
762         def list_avatar_names(self):
763                 """List names of assigned avatars."""
764                 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
765
766 def makelist(value):
767         """Turn string into list type."""
768         if value[0] + value[-1] == "[]": return eval(value)
769         else: return [ value ]
770
771 def makedict(value):
772         """Turn string into dict type."""
773         if value[0] + value[-1] == "{}": return eval(value)
774         elif value.find(":") > 0: return eval("{" + value + "}")
775         else: return { value: None }
776
777 def broadcast(message, add_prompt=True):
778         """Send a message to all connected users."""
779         for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
780
781 def log(message, level=0):
782         """Log a message."""
783
784         # a couple references we need
785         file_name = universe.categories["internal"]["logging"].get("file")
786         max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
787         syslog_name = universe.categories["internal"]["logging"].get("syslog")
788         timestamp = asctime()[4:19]
789
790         # turn the message into a list of lines
791         lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
792
793         # send the timestamp and line to a file
794         if file_name:
795                 file_descriptor = file(file_name, "a")
796                 for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
797                 file_descriptor.flush()
798                 file_descriptor.close()
799
800         # send the timestamp and line to standard output
801         if universe.categories["internal"]["logging"].getboolean("stdout"):
802                 for line in lines: print(timestamp + " " + line)
803
804         # send the line to the system log
805         if syslog_name:
806                 openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
807                 for line in lines: syslog(line)
808                 closelog()
809
810         # display to connected administrators
811         for user in universe.userlist:
812                 if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
813                         # iterate over every line in the message
814                         full_message = ""
815                         for line in lines:
816                                 full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
817                         user.send(full_message, flush=True)
818
819         # add to the recent log list
820         for line in lines:
821                 while 0 < len(universe.loglist) >= max_log_lines: del universe.loglist[0]
822                 universe.loglist.append(timestamp + " " + line)
823
824 def wrap_ansi_text(text, width):
825         """Wrap text with arbitrary width while ignoring ANSI colors."""
826
827         # the current position in the entire text string, including all
828         # characters, printable or otherwise
829         absolute_position = 0
830
831         # the current text position relative to the begining of the line,
832         # ignoring color escape sequences
833         relative_position = 0
834
835         # whether the current character is part of a color escape sequence
836         escape = False
837
838         # iterate over each character from the begining of the text
839         for each_character in text:
840
841                 # the current character is the escape character
842                 if each_character == chr(27):
843                         escape = True
844
845                 # the current character is within an escape sequence
846                 elif escape:
847
848                         # the current character is m, which terminates the
849                         # current escape sequence
850                         if each_character == "m":
851                                 escape = False
852
853                 # the current character is a newline, so reset the relative
854                 # position (start a new line)
855                 elif each_character == "\n":
856                         relative_position = 0
857
858                 # the current character meets the requested maximum line width,
859                 # so we need to backtrack and find a space at which to wrap
860                 elif relative_position == width:
861
862                         # distance of the current character examined from the
863                         # relative position
864                         wrap_offset = 0
865
866                         # count backwards until we find a space
867                         while text[absolute_position - wrap_offset] != " ":
868                                 wrap_offset += 1
869
870                         # insert an eol in place of the space
871                         text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
872
873                         # increase the absolute position because an eol is two
874                         # characters but the space it replaced was only one
875                         absolute_position += 1
876
877                         # now we're at the begining of a new line, plus the
878                         # number of characters wrapped from the previous line
879                         relative_position = wrap_offset
880
881                 # as long as the character is not a carriage return and the
882                 # other above conditions haven't been met, count it as a
883                 # printable character
884                 elif each_character != "\r":
885                         relative_position += 1
886
887                 # increase the absolute position for every character
888                 absolute_position += 1
889
890         # return the newly-wrapped text
891         return text
892
893 def weighted_choice(data):
894         """Takes a dict weighted by value and returns a random key."""
895
896         # this will hold our expanded list of keys from the data
897         expanded = []
898
899         # create thee expanded list of keys
900         for key in data.keys():
901                 for count in range(data[key]):
902                         expanded.append(key)
903
904         # return one at random
905         return choice(expanded)
906
907 def random_name():
908         """Returns a random character name."""
909
910         # the vowels and consonants needed to create romaji syllables
911         vowels = [ "a", "i", "u", "e", "o" ]
912         consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
913
914         # this dict will hold our weighted list of syllables
915         syllables = {}
916
917         # generate the list with an even weighting
918         for consonant in consonants:
919                 for vowel in vowels:
920                         syllables[consonant + vowel] = 1
921
922         # we'll build the name into this string
923         name = ""
924
925         # create a name of random length from the syllables
926         for syllable in range(randrange(2, 6)):
927                 name += weighted_choice(syllables)
928
929         # strip any leading quotemark, capitalize and return the name
930         return name.strip("'").capitalize()
931
932 def replace_macros(user, text, is_input=False):
933         """Replaces macros in text output."""
934
935         # loop until broken
936         while True:
937
938                 # third person pronouns
939                 pronouns = {
940                         "female": { "obj": "her", "pos": "hers", "sub": "she" },
941                         "male": { "obj": "him", "pos": "his", "sub": "he" },
942                         "neuter": { "obj": "it", "pos": "its", "sub": "it" }
943                         }
944
945                 # a dict of replacement macros
946                 macros = {
947                         "$(eol)": "\r\n",
948                         "$(bld)": chr(27) + "[1m",
949                         "$(nrm)": chr(27) + "[0m",
950                         "$(blk)": chr(27) + "[30m",
951                         "$(blu)": chr(27) + "[34m",
952                         "$(cyn)": chr(27) + "[36m",
953                         "$(grn)": chr(27) + "[32m",
954                         "$(mgt)": chr(27) + "[35m",
955                         "$(red)": chr(27) + "[31m",
956                         "$(yel)": chr(27) + "[33m",
957                         }
958
959                 # add dynamic macros where possible
960                 if user.account:
961                         account_name = user.account.get("name")
962                         if account_name:
963                                 macros["$(account)"] = account_name
964                 if user.avatar:
965                         avatar_gender = user.avatar.get("gender")
966                         if avatar_gender:
967                                 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
968                                 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
969                                 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
970
971                 # find and replace per the macros dict
972                 macro_start = text.find("$(")
973                 if macro_start == -1: break
974                 macro_end = text.find(")", macro_start) + 1
975                 macro = text[macro_start:macro_end]
976                 if macro in macros.keys():
977                         text = text.replace(macro, macros[macro])
978
979                 # if we get here, log and replace it with null
980                 else:
981                         text = text.replace(macro, "")
982                         if not is_input:
983                                 log("Unexpected replacement macro " + macro + " encountered.", 6)
984
985         # replace the look-like-a-macro sequence
986         text = text.replace("$_(", "$(")
987
988         return text
989
990 def escape_macros(text):
991         """Escapes replacement macros in text."""
992         return text.replace("$(", "$_(")
993
994 def check_time(frequency):
995         """Check for a factor of the current increment count."""
996         if type(frequency) is str:
997                 frequency = universe.categories["internal"]["time"].getint(frequency)
998         if not "counters" in universe.categories["internal"]:
999                 Element("internal:counters", universe)
1000         return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
1001
1002 def on_pulse():
1003         """The things which should happen on each pulse, aside from reloads."""
1004
1005         # open the listening socket if it hasn't been already
1006         if not hasattr(universe, "listening_socket"):
1007                 universe.initialize_server_socket()
1008
1009         # assign a user if a new connection is waiting
1010         user = check_for_connection(universe.listening_socket)
1011         if user: universe.userlist.append(user)
1012
1013         # iterate over the connected users
1014         for user in universe.userlist: user.pulse()
1015
1016         # update the log every now and then
1017         if check_time("frequency_log"):
1018                 log(str(len(universe.userlist)) + " connection(s)")
1019
1020         # periodically save everything
1021         if check_time("frequency_save"):
1022                 universe.save()
1023
1024         # pause for a configurable amount of time (decimal seconds)
1025         sleep(universe.categories["internal"]["time"].getfloat("increment"))
1026
1027         # increment the elapsed increment counter
1028         universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
1029
1030 def reload_data():
1031         """Reload data into new persistent objects."""
1032         for user in universe.userlist[:]: user.reload()
1033
1034 def check_for_connection(listening_socket):
1035         """Check for a waiting connection and return a new user object."""
1036
1037         # try to accept a new connection
1038         try:
1039                 connection, address = listening_socket.accept()
1040         except:
1041                 return None
1042
1043         # note that we got one
1044         log("Connection from " + address[0], 2)
1045
1046         # disable blocking so we can proceed whether or not we can send/receive
1047         connection.setblocking(0)
1048
1049         # create a new user object
1050         user = User()
1051
1052         # associate this connection with it
1053         user.connection = connection
1054
1055         # set the user's ipa from the connection's ipa
1056         user.address = address[0]
1057
1058         # let the client know we WILL EOR
1059         user.send(IAC+WILL+EOR, raw=True)
1060         user.negotiation_pause = 2
1061
1062         # return the new user object
1063         return user
1064
1065 def get_menu(state, error=None, echoing=True, terminator="", choices=None):
1066         """Show the correct menu text to a user."""
1067
1068         # make sure we don't reuse a mutable sequence by default
1069         if choices is None: choices = {}
1070
1071         # begin with a telnet echo command sequence if needed
1072         message = get_echo_sequence(state, echoing)
1073
1074         # get the description or error text
1075         message += get_menu_description(state, error)
1076
1077         # get menu choices for the current state
1078         message += get_formatted_menu_choices(state, choices)
1079
1080         # try to get a prompt, if it was defined
1081         message += get_menu_prompt(state)
1082
1083         # throw in the default choice, if it exists
1084         message += get_formatted_default_menu_choice(state)
1085
1086         # display a message indicating if echo is off
1087         message += get_echo_message(state)
1088
1089         # tack on EOR or GA to indicate the prompt will not be followed by CRLF
1090         message += terminator
1091
1092         # return the assembly of various strings defined above
1093         return message
1094
1095 def menu_echo_on(state):
1096         """True if echo is on, false if it is off."""
1097         return universe.categories["menu"][state].getboolean("echo", True)
1098
1099 def get_echo_sequence(state, echoing):
1100         """Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
1101
1102         # if the user has echo on and the menu specifies it should be turned
1103         # off, send: iac + will + echo + null
1104         if echoing and not menu_echo_on(state): return IAC+WILL+ECHO
1105
1106         # if echo is not set to off in the menu and the user curently has echo
1107         # off, send: iac + wont + echo + null
1108         elif not echoing and menu_echo_on(state): return IAC+WONT+ECHO
1109
1110         # default is not to send an echo control sequence at all
1111         else: return ""
1112
1113 def get_echo_message(state):
1114         """Return a message indicating that echo is off."""
1115         if menu_echo_on(state): return ""
1116         else: return "(won't echo) "
1117
1118 def get_default_menu_choice(state):
1119         """Return the default choice for a menu."""
1120         return universe.categories["menu"][state].get("default")
1121
1122 def get_formatted_default_menu_choice(state):
1123         """Default menu choice foratted for inclusion in a prompt string."""
1124         default_choice = get_default_menu_choice(state)
1125         if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
1126         else: return ""
1127
1128 def get_menu_description(state, error):
1129         """Get the description or error text."""
1130
1131         # an error condition was raised by the handler
1132         if error:
1133
1134                 # try to get an error message matching the condition
1135                 # and current state
1136                 description = universe.categories["menu"][state].get("error_" + error)
1137                 if not description: description = "That is not a valid choice..."
1138                 description = "$(red)" + description + "$(nrm)"
1139
1140         # there was no error condition
1141         else:
1142
1143                 # try to get a menu description for the current state
1144                 description = universe.categories["menu"][state].get("description")
1145
1146         # return the description or error message
1147         if description: description += "$(eol)$(eol)"
1148         return description
1149
1150 def get_menu_prompt(state):
1151         """Try to get a prompt, if it was defined."""
1152         prompt = universe.categories["menu"][state].get("prompt")
1153         if prompt: prompt += " "
1154         return prompt
1155
1156 def get_menu_choices(user):
1157         """Return a dict of choice:meaning."""
1158         menu = universe.categories["menu"][user.state]
1159         create_choices = menu.get("create")
1160         if create_choices: choices = eval(create_choices)
1161         else: choices = {}
1162         ignores = []
1163         options = {}
1164         creates = {}
1165         for facet in menu.facets():
1166                 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
1167                         ignores.append(facet.split("_", 2)[1])
1168                 elif facet.startswith("create_"):
1169                         creates[facet] = facet.split("_", 2)[1]
1170                 elif facet.startswith("choice_"):
1171                         options[facet] = facet.split("_", 2)[1]
1172         for facet in creates.keys():
1173                 if not creates[facet] in ignores:
1174                         choices[creates[facet]] = eval(menu.get(facet))
1175         for facet in options.keys():
1176                 if not options[facet] in ignores:
1177                         choices[options[facet]] = menu.get(facet)
1178         return choices
1179
1180 def get_formatted_menu_choices(state, choices):
1181         """Returns a formatted string of menu choices."""
1182         choice_output = ""
1183         choice_keys = choices.keys()
1184         choice_keys.sort()
1185         for choice in choice_keys:
1186                 choice_output += "   [$(red)" + choice + "$(nrm)]  " + choices[choice] + "$(eol)"
1187         if choice_output: choice_output += "$(eol)"
1188         return choice_output
1189
1190 def get_menu_branches(state):
1191         """Return a dict of choice:branch."""
1192         branches = {}
1193         for facet in universe.categories["menu"][state].facets():
1194                 if facet.startswith("branch_"):
1195                         branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1196         return branches
1197
1198 def get_default_branch(state):
1199         """Return the default branch."""
1200         return universe.categories["menu"][state].get("branch")
1201
1202 def get_choice_branch(user, choice):
1203         """Returns the new state matching the given choice."""
1204         branches = get_menu_branches(user.state)
1205         if choice in branches.keys(): return branches[choice]
1206         elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
1207         else: return ""
1208
1209 def get_menu_actions(state):
1210         """Return a dict of choice:branch."""
1211         actions = {}
1212         for facet in universe.categories["menu"][state].facets():
1213                 if facet.startswith("action_"):
1214                         actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1215         return actions
1216
1217 def get_default_action(state):
1218         """Return the default action."""
1219         return universe.categories["menu"][state].get("action")
1220
1221 def get_choice_action(user, choice):
1222         """Run any indicated script for the given choice."""
1223         actions = get_menu_actions(user.state)
1224         if choice in actions.keys(): return actions[choice]
1225         elif choice in user.menu_choices.keys(): return get_default_action(user.state)
1226         else: return ""
1227
1228 def handle_user_input(user):
1229         """The main handler, branches to a state-specific handler."""
1230
1231         # check to make sure the state is expected, then call that handler
1232         if "handler_" + user.state in globals():
1233                 exec("handler_" + user.state + "(user)")
1234         else:
1235                 generic_menu_handler(user)
1236
1237         # since we got input, flag that the menu/prompt needs to be redisplayed
1238         user.menu_seen = False
1239
1240         # if the user's client echo is off, send a blank line for aesthetics
1241         if user.echoing: user.received_newline = True
1242
1243 def generic_menu_handler(user):
1244         """A generic menu choice handler."""
1245
1246         # get a lower-case representation of the next line of input
1247         if user.input_queue:
1248                 choice = user.input_queue.pop(0)
1249                 if choice: choice = choice.lower()
1250         else: choice = ""
1251         if not choice: choice = get_default_menu_choice(user.state)
1252         if choice in user.menu_choices:
1253                 exec(get_choice_action(user, choice))
1254                 new_state = get_choice_branch(user, choice)
1255                 if new_state: user.state = new_state
1256         else: user.error = "default"
1257
1258 def handler_entering_account_name(user):
1259         """Handle the login account name."""
1260
1261         # get the next waiting line of input
1262         input_data = user.input_queue.pop(0)
1263
1264         # did the user enter anything?
1265         if input_data:
1266                 
1267                 # keep only the first word and convert to lower-case
1268                 name = input_data.lower()
1269
1270                 # fail if there are non-alphanumeric characters
1271                 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
1272                         user.error = "bad_name"
1273
1274                 # if that account exists, time to request a password
1275                 elif name in universe.categories["account"]:
1276                         user.account = universe.categories["account"][name]
1277                         user.state = "checking_password"
1278
1279                 # otherwise, this could be a brand new user
1280                 else:
1281                         user.account = Element("account:" + name, universe)
1282                         user.account.set("name", name)
1283                         log("New user: " + name, 2)
1284                         user.state = "checking_new_account_name"
1285
1286         # if the user entered nothing for a name, then buhbye
1287         else:
1288                 user.state = "disconnecting"
1289
1290 def handler_checking_password(user):
1291         """Handle the login account password."""
1292
1293         # get the next waiting line of input
1294         input_data = user.input_queue.pop(0)
1295
1296         # does the hashed input equal the stored hash?
1297         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1298
1299                 # if so, set the username and load from cold storage
1300                 if not user.replace_old_connections():
1301                         user.authenticate()
1302                         user.state = "main_utility"
1303
1304         # if at first your hashes don't match, try, try again
1305         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1306                 user.password_tries += 1
1307                 user.error = "incorrect"
1308
1309         # we've exceeded the maximum number of password failures, so disconnect
1310         else:
1311                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1312                 user.state = "disconnecting"
1313
1314 def handler_entering_new_password(user):
1315         """Handle a new password entry."""
1316
1317         # get the next waiting line of input
1318         input_data = user.input_queue.pop(0)
1319
1320         # make sure the password is strong--at least one upper, one lower and
1321         # one digit, seven or more characters in length
1322         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)):
1323
1324                 # hash and store it, then move on to verification
1325                 user.account.set("passhash",  new_md5(user.account.get("name") + input_data).hexdigest())
1326                 user.state = "verifying_new_password"
1327
1328         # the password was weak, try again if you haven't tried too many times
1329         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1330                 user.password_tries += 1
1331                 user.error = "weak"
1332
1333         # too many tries, so adios
1334         else:
1335                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1336                 user.account.destroy()
1337                 user.state = "disconnecting"
1338
1339 def handler_verifying_new_password(user):
1340         """Handle the re-entered new password for verification."""
1341
1342         # get the next waiting line of input
1343         input_data = user.input_queue.pop(0)
1344
1345         # hash the input and match it to storage
1346         if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1347                 user.authenticate()
1348
1349                 # the hashes matched, so go active
1350                 if not user.replace_old_connections(): user.state = "main_utility"
1351
1352         # go back to entering the new password as long as you haven't tried
1353         # too many times
1354         elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1355                 user.password_tries += 1
1356                 user.error = "differs"
1357                 user.state = "entering_new_password"
1358
1359         # otherwise, sayonara
1360         else:
1361                 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1362                 user.account.destroy()
1363                 user.state = "disconnecting"
1364
1365 def handler_active(user):
1366         """Handle input for active users."""
1367
1368         # get the next waiting line of input
1369         input_data = user.input_queue.pop(0)
1370
1371         # is there input?
1372         if input_data:
1373
1374                 # split out the command (first word) and parameters (everything else)
1375                 if input_data.find(" ") > 0:
1376                         command_name, parameters = input_data.split(" ", 1)
1377                 else:
1378                         command_name = input_data
1379                         parameters = ""
1380
1381                 # lowercase the command
1382                 command_name = command_name.lower()
1383
1384                 # the command matches a command word for which we have data
1385                 if command_name in universe.categories["command"]:
1386                         command = universe.categories["command"][command_name]
1387                 else: command = None
1388
1389                 # if it's allowed, do it
1390                 if user.can_run(command): exec(command.get("action"))
1391
1392                 # otherwise, give an error
1393                 elif command_name: command_error(user, input_data)
1394
1395         # if no input, just idle back with a prompt
1396         else: user.send("", just_prompt=True)
1397         
1398 def command_halt(user, parameters):
1399         """Halt the world."""
1400
1401         # see if there's a message or use a generic one
1402         if parameters: message = "Halting: " + parameters
1403         else: message = "User " + user.account.get("name") + " halted the world."
1404
1405         # let everyone know
1406         broadcast(message, add_prompt=False)
1407         log(message, 8)
1408
1409         # set a flag to terminate the world
1410         universe.terminate_world = True
1411
1412 def command_reload(user):
1413         """Reload all code modules, configs and data."""
1414
1415         # let the user know and log
1416         user.send("Reloading all code modules, configs and data.")
1417         log("User " + user.account.get("name") + " reloaded the world.", 8)
1418
1419         # set a flag to reload
1420         universe.reload_modules = True
1421
1422 def command_quit(user):
1423         """Leave the world and go back to the main menu."""
1424         user.deactivate_avatar()
1425         user.state = "main_utility"
1426
1427 def command_help(user, parameters):
1428         """List available commands and provide help for commands."""
1429
1430         # did the user ask for help on a specific command word?
1431         if parameters:
1432
1433                 # is the command word one for which we have data?
1434                 if parameters in universe.categories["command"]:
1435                         command = universe.categories["command"][parameters]
1436                 else: command = None
1437
1438                 # only for allowed commands
1439                 if user.can_run(command):
1440
1441                         # add a description if provided
1442                         description = command.get("description")
1443                         if not description:
1444                                 description = "(no short description provided)"
1445                         if command.getboolean("administrative"): output = "$(red)"
1446                         else: output = "$(grn)"
1447                         output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1448
1449                         # add the help text if provided
1450                         help_text = command.get("help")
1451                         if not help_text:
1452                                 help_text = "No help is provided for this command."
1453                         output += help_text
1454
1455                 # no data for the requested command word
1456                 else:
1457                         output = "That is not an available command."
1458
1459         # no specific command word was indicated
1460         else:
1461
1462                 # give a sorted list of commands with descriptions if provided
1463                 output = "These are the commands available to you:$(eol)$(eol)"
1464                 sorted_commands = universe.categories["command"].keys()
1465                 sorted_commands.sort()
1466                 for item in sorted_commands:
1467                         command = universe.categories["command"][item]
1468                         if user.can_run(command):
1469                                 description = command.get("description")
1470                                 if not description:
1471                                         description = "(no short description provided)"
1472                                 if command.getboolean("administrative"): output += "   $(red)"
1473                                 else: output += "   $(grn)"
1474                                 output += item + "$(nrm) - " + description + "$(eol)"
1475                 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1476
1477         # send the accumulated output to the user
1478         user.send(output)
1479
1480 def command_move(user, parameters):
1481         """Move the avatar in a given direction."""
1482         if parameters in universe.contents[user.avatar.get("location")].portals():
1483                 user.avatar.move_direction(parameters)
1484         else: user.send("You cannot go that way.")
1485
1486 def command_look(user, parameters):
1487         """Look around."""
1488         if parameters: user.send("You can't look at or in anything yet.")
1489         else: user.avatar.look_at(user.avatar.get("location"))
1490
1491 def command_say(user, parameters):
1492         """Speak to others in the same room."""
1493
1494         # check for replacement macros
1495         if replace_macros(user, parameters, True) != parameters:
1496                 user.send("You cannot speak $_(replacement macros).")
1497
1498         # the user entered a message
1499         elif parameters:
1500
1501                 # get rid of quote marks on the ends of the message and
1502                 # capitalize the first letter
1503                 message = parameters.strip("\"'`").capitalize()
1504
1505                 # a dictionary of punctuation:action pairs
1506                 actions = {}
1507                 for facet in universe.categories["internal"]["language"].facets():
1508                         if facet.startswith("punctuation_"):
1509                                 action = facet.split("_")[1]
1510                                 for mark in universe.categories["internal"]["language"].getlist(facet):
1511                                                 actions[mark] = action
1512
1513                 # match the punctuation used, if any, to an action
1514                 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1515                 action = actions[default_punctuation]
1516                 for mark in actions.keys():
1517                         if message.endswith(mark) and mark != default_punctuation:
1518                                 action = actions[mark]
1519                                 break
1520
1521                 # if the action is default and there is no mark, add one
1522                 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1523                         message += default_punctuation
1524
1525                 # capitalize a list of words within the message
1526                 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1527                 for word in capitalize_words:
1528                         message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1529
1530                 # tell the room
1531                 user.avatar.echo_to_location(user.avatar.get("name") + " " + action + "s, \"" + message + "\"")
1532                 user.send("You " + action + ", \"" + message + "\"")
1533
1534         # there was no message
1535         else:
1536                 user.send("What do you want to say?")
1537
1538 def command_show(user, parameters):
1539         """Show program data."""
1540         message = ""
1541         if parameters.find(" ") < 1:
1542                 if parameters == "time":
1543                         message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1544                 elif parameters == "categories":
1545                         message = "These are the element categories:$(eol)"
1546                         categories = universe.categories.keys()
1547                         categories.sort()
1548                         for category in categories: message += "$(eol)   $(grn)" + category + "$(nrm)"
1549                 elif parameters == "files":
1550                         message = "These are the current files containing the universe:$(eol)"
1551                         filenames = universe.files.keys()
1552                         filenames.sort()
1553                         for filename in filenames: message += "$(eol)   $(grn)" + filename + "$(nrm)"
1554                 else: message = ""
1555         else:
1556                 arguments = parameters.split()
1557                 if arguments[0] == "category":
1558                         if arguments[1] in universe.categories:
1559                                 message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
1560                                 elements = universe.categories[arguments[1]].keys()
1561                                 elements.sort()
1562                                 for element in elements:
1563                                         message += "$(eol)   $(grn)" + universe.categories[arguments[1]][element].key + "$(nrm)"
1564                 elif arguments[0] == "element":
1565                         if arguments[1] in universe.contents:
1566                                 message = "These are the properties of the \"" + arguments[1] + "\" element:$(eol)"
1567                                 element = universe.contents[arguments[1]]
1568                                 facets = element.facets()
1569                                 facets.sort()
1570                                 for facet in facets:
1571                                         message += "$(eol)   $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
1572                 elif arguments[0] == "result":
1573                         if len(arguments) > 1:
1574                                 try:
1575                                         message = repr(eval(" ".join(arguments[1:])))
1576                                 except:
1577                                         message = "Your expression raised an exception!"
1578                 elif arguments[0] == "log":
1579                         if match("^\d+$", arguments[1]) and int(arguments[1]) > 0:
1580                                 linecount = int(arguments[1])
1581                                 if linecount > len(universe.loglist): linecount = len(universe.loglist)
1582                                 message = "There are " + str(len(universe.loglist)) + " log lines in memory."
1583                                 message += " The most recent " + str(linecount) + " lines are:$(eol)$(eol)"
1584                                 for line in universe.loglist[-linecount:]:
1585                                         message += "   " + line + "$(eol)"
1586                         else: message = "\"" + arguments[1] + "\" is not a positive integer greater than 0."
1587         if not message:
1588                 if parameters: message = "I don't know what \"" + parameters + "\" is."
1589                 else: message = "What do you want to show?"
1590         user.send(message)
1591
1592 def command_create(user, parameters):
1593         """Create an element if it does not exist."""
1594         if not parameters: message = "You must at least specify an element to create."
1595         else:
1596                 arguments = parameters.split()
1597                 if len(arguments) == 1: arguments.append("")
1598                 if len(arguments) == 2:
1599                         element, filename = arguments
1600                         if element in universe.contents: message = "The \"" + element + "\" element already exists."
1601                         else:
1602                                 message = "You create \"" + element + "\" within the universe."
1603                                 logline = user.account.get("name") + " created an element: " + element
1604                                 if filename:
1605                                         logline += " in file " + filename
1606                                         if filename not in universe.files:
1607                                                 message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
1608                                 Element(element, universe, filename)
1609                                 log(logline, 6)
1610                 elif len(arguments) > 2: message = "You can only specify an element and a filename."
1611         user.send(message)
1612
1613 def command_destroy(user, parameters):
1614         """Destroy an element if it exists."""
1615         if not parameters: message = "You must specify an element to destroy."
1616         else:
1617                 if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
1618                 else:
1619                         universe.contents[parameters].destroy()
1620                         message = "You destroy \"" + parameters + "\" within the universe."
1621                         log(user.account.get("name") + " destroyed an element: " + parameters, 6)
1622         user.send(message)
1623
1624 def command_set(user, parameters):
1625         """Set a facet of an element."""
1626         if not parameters: message = "You must specify an element, a facet and a value."
1627         else:
1628                 arguments = parameters.split(" ", 2)
1629                 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
1630                 elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
1631                 else:
1632                         element, facet, value = arguments
1633                         if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1634                         else:
1635                                 universe.contents[element].set(facet, value)
1636                                 message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1637         user.send(message)
1638
1639 def command_delete(user, parameters):
1640         """Delete a facet from an element."""
1641         if not parameters: message = "You must specify an element and a facet."
1642         else:
1643                 arguments = parameters.split(" ")
1644                 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
1645                 elif len(arguments) != 2: message = "You may only specify an element and a facet."
1646                 else:
1647                         element, facet = arguments
1648                         if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1649                         elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
1650                         else:
1651                                 universe.contents[element].remove_facet(facet)
1652                                 message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1653         user.send(message)
1654
1655 def command_error(user, input_data):
1656         """Generic error for an unrecognized command word."""
1657
1658         # 90% of the time use a generic error
1659         if randrange(10):
1660                 message = "I'm not sure what \"" + input_data + "\" means..."
1661
1662         # 10% of the time use the classic diku error
1663         else:
1664                 message = "Arglebargle, glop-glyf!?!"
1665
1666         # send the error message
1667         user.send(message)
1668
1669 # if there is no universe, create an empty one
1670 if not "universe" in locals(): universe = Universe()
1671