Imported from archive.
[mudpy.git] / mudpy.py
index 4c3cdf5..d1c434f 100644 (file)
--- a/mudpy.py
+++ b/mudpy.py
@@ -12,17 +12,48 @@ from random import choice, randrange
 from re import match
 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
 from stat import S_IMODE, ST_MODE
+from sys import stderr
 from syslog import LOG_PID, LOG_INFO, LOG_DAEMON, closelog, openlog, syslog
 from telnetlib import DO, DONT, ECHO, EOR, GA, IAC, LINEMODE, SB, SE, SGA, WILL, WONT
 from time import asctime, sleep
+from traceback import format_exception
+
+def excepthook(excepttype, value, traceback):
+       """Handle uncaught exceptions."""
+
+       # assemble the list of errors into a single string
+       message = "".join(format_exception(excepttype, value, traceback))
+
+       # try to log it, if possible
+       try: log(message, 9)
+       except: pass
+
+       # try to write it to stderr, if possible
+       try: stderr.write(message)
+       except: pass
+
+# redefine sys.excepthook with ours
+import sys
+sys.excepthook = excepthook
 
 class Element:
        """An element of the universe."""
-       def __init__(self, key, universe, origin=""):
-               """Default values for the in-memory element variables."""
+       def __init__(self, key, universe, filename=None):
+               """Set up a new element."""
+
+               # not owned by a user by default (used for avatars)
                self.owner = None
+
+               # no contents in here by default
                self.contents = {}
+
+               # an event queue for the element
+               self.events = {}
+
+               # keep track of our key name
                self.key = key
+
+               # parse out appropriate category and subkey names, add to list
                if self.key.find(":") > 0:
                        self.category, self.subkey = self.key.split(":", 1)
                else:
@@ -30,35 +61,43 @@ class Element:
                        self.subkey = self.key
                if not self.category in universe.categories: self.category = "other"
                universe.categories[self.category][self.subkey] = self
-               self.origin = origin
-               if not self.origin: self.origin = universe.default_origins[self.category]
-               if not isabs(self.origin):
-                       self.origin = abspath(self.origin)
+
+               # get an appropriate filename for the origin
+               if not filename: filename = universe.default_origins[self.category]
+               if not isabs(filename): filename = abspath(filename)
+
+               # add the file if it doesn't exist yet
+               if not filename in universe.files: DataFile(filename, universe)
+
+               # record a pointer to the origin file
+               self.origin = universe.files[filename]
+
+               # add a data section to the origin if necessary
+               if not self.origin.data.has_section(self.key):
+                       self.origin.data.add_section(self.key)
+
+               # add this element to the universe contents
                universe.contents[self.key] = self
-               if not self.origin in universe.files:
-                       DataFile(self.origin, universe)
-               if not universe.files[self.origin].data.has_section(self.key):
-                       universe.files[self.origin].data.add_section(self.key)
+
        def destroy(self):
                """Remove an element from the universe and destroy it."""
-               log("Destroying: " + self.key + ".")
-               universe.files[self.origin].data.remove_section(self.key)
+               self.origin.data.remove_section(self.key)
                del universe.categories[self.category][self.subkey]
                del universe.contents[self.key]
                del self
-       def delete(self, facet):
-               """Delete a facet from the element."""
-               if universe.files[self.origin].data.has_option(self.key, facet):
-                       universe.files[self.origin].data.remove_option(self.key, facet)
        def facets(self):
                """Return a list of non-inherited facets for this element."""
-               return universe.files[self.origin].data.options(self.key)
+               if self.key in self.origin.data.sections():
+                       return self.origin.data.options(self.key)
+               else: return []
        def has_facet(self, facet):
                """Return whether the non-inherited facet exists."""
                return facet in self.facets()
        def remove_facet(self, facet):
                """Remove a facet from the element."""
-               if self.has_facet(facet): universe.files[self.origin].data.remove_option(self.key, facet)
+               if self.has_facet(facet):
+                       self.origin.data.remove_option(self.key, facet)
+                       self.origin.modified = True
        def ancestry(self):
                """Return a list of the element's inheritance lineage."""
                if self.has_facet("inherit"):
@@ -72,8 +111,8 @@ class Element:
        def get(self, facet, default=None):
                """Retrieve values."""
                if default is None: default = ""
-               if universe.files[self.origin].data.has_option(self.key, facet):
-                       return universe.files[self.origin].data.get(self.key, facet)
+               if self.origin.data.has_option(self.key, facet):
+                       return self.origin.data.get(self.key, facet)
                elif self.has_facet("inherit"):
                        for ancestor in self.ancestry():
                                if universe.contents[ancestor].has_facet(facet):
@@ -82,8 +121,8 @@ class Element:
        def getboolean(self, facet, default=None):
                """Retrieve values as boolean type."""
                if default is None: default=False
-               if universe.files[self.origin].data.has_option(self.key, facet):
-                       return universe.files[self.origin].data.getboolean(self.key, facet)
+               if self.origin.data.has_option(self.key, facet):
+                       return self.origin.data.getboolean(self.key, facet)
                elif self.has_facet("inherit"):
                        for ancestor in self.ancestry():
                                if universe.contents[ancestor].has_facet(facet):
@@ -92,8 +131,8 @@ class Element:
        def getint(self, facet, default=None):
                """Return values as int/long type."""
                if default is None: default = 0
-               if universe.files[self.origin].data.has_option(self.key, facet):
-                       return universe.files[self.origin].data.getint(self.key, facet)
+               if self.origin.data.has_option(self.key, facet):
+                       return self.origin.data.getint(self.key, facet)
                elif self.has_facet("inherit"):
                        for ancestor in self.ancestry():
                                if universe.contents[ancestor].has_facet(facet):
@@ -102,8 +141,8 @@ class Element:
        def getfloat(self, facet, default=None):
                """Return values as float type."""
                if default is None: default = 0.0
-               if universe.files[self.origin].data.has_option(self.key, facet):
-                       return universe.files[self.origin].data.getfloat(self.key, facet)
+               if self.origin.data.has_option(self.key, facet):
+                       return self.origin.data.getfloat(self.key, facet)
                elif self.has_facet("inherit"):
                        for ancestor in self.ancestry():
                                if universe.contents[ancestor].has_facet(facet):
@@ -123,9 +162,11 @@ class Element:
                else: return default
        def set(self, facet, value):
                """Set values."""
-               if type(value) is long: value = str(value)
-               elif not type(value) is str: value = repr(value)
-               universe.files[self.origin].data.set(self.key, facet, value)
+               if not self.has_facet(facet) or not self.get(facet) == value:
+                       if type(value) is long: value = str(value)
+                       elif not type(value) is str: value = repr(value)
+                       self.origin.data.set(self.key, facet, value)
+                       self.origin.modified = True
        def append(self, facet, value):
                """Append value tp a list."""
                if type(value) is long: value = str(value)
@@ -133,13 +174,42 @@ class Element:
                newlist = self.getlist(facet)
                newlist.append(value)
                self.set(facet, newlist)
+
+       def new_event(self, action, when=None):
+               """Create, attach and enqueue an event element."""
+
+               # if when isn't specified, that means now
+               if not when: when = universe.get_time()
+
+               # events are elements themselves
+               event = Element("event:" + self.key + ":" + counter)
+
        def send(self, message, eol="$(eol)"):
                """Convenience method to pass messages to an owner."""
                if self.owner: self.owner.send(message, eol)
+
+       def can_run(self, command):
+               """Check if the user can run this command object."""
+
+               # has to be in the commands category
+               if command not in universe.categories["command"].values(): result = False
+
+               # avatars of administrators can run any command
+               elif self.owner and self.owner.account.getboolean("administrator"): result = True
+
+               # everyone can run non-administrative commands
+               elif not command.getboolean("administrative"): result = True
+
+               # otherwise the command cannot be run by this actor
+               else: result = False
+
+               # pass back the result
+               return result
+
        def go_to(self, location):
                """Relocate the element to a specific location."""
                current = self.get("location")
-               if current and current in universe.contents[current].contents:
+               if current and self.key in universe.contents[current].contents:
                        del universe.contents[current].contents[self.key]
                if location in universe.contents: self.set("location", location)
                universe.contents[location].contents[self.key] = self
@@ -147,9 +217,13 @@ class Element:
        def go_home(self):
                """Relocate the element to its default location."""
                self.go_to(self.get("default_location"))
+               self.echo_to_location("You suddenly realize that " + self.get("name") + " is here.")
        def move_direction(self, direction):
                """Relocate the element in a specified direction."""
+               self.echo_to_location(self.get("name") + " exits " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
+               self.send("You exit " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
                self.go_to(universe.contents[self.get("location")].link_neighbor(direction))
+               self.echo_to_location(self.get("name") + " arrives from " + universe.categories["internal"]["directions"].getdict(direction)["enter"] + ".")
        def look_at(self, key):
                """Show an element to another element."""
                if self.owner:
@@ -172,14 +246,8 @@ class Element:
                portals = {}
                if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
                        coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
-                       offsets = {
-                               "down": (0,0,-1),
-                               "east": (1,0,0),
-                               "north": (0,1,0),
-                               "south": (0,-1,0),
-                               "up": (0,0,1),
-                               "west": (-1,0,0)
-                               }
+                       directions = universe.categories["internal"]["directions"]
+                       offsets = dict([(x, directions.getdict(x)["vector"]) for x in directions.facets()])
                        for portal in self.getlist("gridlinks"):
                                adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
                                neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
@@ -203,6 +271,7 @@ class Element:
 class DataFile:
        """A file containing universe elements."""
        def __init__(self, filename, universe):
+               self.modified = False
                self.data = RawConfigParser()
                if access(filename, R_OK): self.data.read(filename)
                self.filename = filename
@@ -231,11 +300,14 @@ class DataFile:
                        if not isabs(include_file):
                                include_file = path_join(dirname(filename), include_file)
                        DataFile(include_file, universe)
+       def is_writeable(self):
+               """Returns True if the __control__ read_only is False."""
+               return not self.data.has_option("__control__", "read_only") or not self.data.getboolean("__control__", "read_only")
        def save(self):
                """Write the data, if necessary."""
 
-               # when there is content or the file exists, but is not read-only
-               if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("__control__", "read_only") and self.data.getboolean("__control__", "read_only") ):
+               # when modified, writeable and has content or the file exists
+               if self.modified and self.is_writeable() and ( self.data.sections() or exists(self.filename) ):
 
                        # make parent directories if necessary
                        if not exists(dirname(self.filename)):
@@ -263,6 +335,9 @@ class DataFile:
                        file_descriptor.flush()
                        file_descriptor.close()
 
+                       # unset the modified flag
+                       self.modified = False
+
 class Universe:
        """The universe."""
        def __init__(self, filename=""):
@@ -272,6 +347,9 @@ class Universe:
                self.default_origins = {}
                self.files = {}
                self.private_files = []
+               self.loglines = {}
+               self.pending_events_long = {}
+               self.pending_events_short = {}
                self.userlist = []
                self.terminate_world = False
                self.reload_modules = False
@@ -320,6 +398,10 @@ class Universe:
                # note that we're now ready for user connections
                log("Waiting for connection(s)...")
 
+       def get_time(self):
+               """Convenience method to get the elapsed time counter."""
+               return self.categories["internal"]["counters"].getint("elapsed")
+
 class User:
        """This is a connected user."""
 
@@ -337,6 +419,7 @@ class User:
                self.output_queue = []
                self.partial_input = ""
                self.echoing = True
+               self.received_newline = True
                self.terminator = IAC+GA
                self.negotiation_pause = 0
                self.avatar = None
@@ -349,7 +432,7 @@ class User:
                if name: message = "User " + name
                else: message = "An unnamed user"
                message += " logged out."
-               log(message)
+               log(message, 2)
                self.deactivate_avatar()
                self.connection.close()
                self.remove()
@@ -377,6 +460,7 @@ class User:
                        "output_queue",
                        "partial_input",
                        "echoing",
+                       "received_newline",
                        "terminator",
                        "negotiation_pause",
                        "avatar",
@@ -403,7 +487,7 @@ class User:
                        if old_user.account.get("name") == self.account.get("name") and old_user is not self:
 
                                # make a note of it
-                               log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".")
+                               log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
                                old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
 
                                # close the old connection
@@ -428,7 +512,7 @@ class User:
        def authenticate(self):
                """Flag the user as authenticated and disconnect duplicates."""
                if not self.state is "authenticated":
-                       log("User " + self.account.get("name") + " logged in.")
+                       log("User " + self.account.get("name") + " logged in.", 2)
                        self.authenticated = True
                        if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
                                self.account.set("administrator", "True")
@@ -451,7 +535,7 @@ class User:
                """Remove a user from the list of connected users."""
                universe.userlist.remove(self)
 
-       def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True):
+       def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
                """Send arbitrary text to a connected user."""
 
                # unless raw mode is on, clean it up all nice and pretty
@@ -470,10 +554,13 @@ class User:
                        # start with a newline, append the message, then end
                        # with the optional eol string passed to this function
                        # and the ansi escape to return to normal text
-                       output = "$(eol)" + output + eol + chr(27) + "[0m"
+                       if not just_prompt: output = "$(eol)$(eol)" + output
+                       output += eol + chr(27) + "[0m"
 
                        # tack on a prompt if active
-                       if self.state == "active" and add_prompt: output += "$(eol)> "
+                       if self.state == "active":
+                               if not just_prompt: output += "$(eol)"
+                               if add_prompt: output += "> "
 
                        # find and replace macros in the output
                        output = replace_macros(self, output)
@@ -521,6 +608,10 @@ class User:
        def flush(self):
                """Try to send the last item in the queue and remove it."""
                if self.output_queue:
+                       if self.received_newline:
+                               self.received_newline = False
+                               if self.output_queue[0].startswith("\r\n"):
+                                       self.output_queue[0] = self.output_queue[0][2:]
                        try:
                                self.connection.send(self.output_queue[0])
                                del self.output_queue[0]
@@ -573,7 +664,7 @@ class User:
                                        if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
                                        else: logline += "unknown user: "
                                        logline += repr(removed)
-                                       log(logline)
+                                       log(logline, 4)
 
                                # filter out non-printables
                                line = filter(lambda x: " " <= x <= "~", line)
@@ -651,30 +742,12 @@ class User:
                # replace the input with our cleaned-up text
                self.partial_input = text
 
-       def can_run(self, command):
-               """Check if the user can run this command object."""
-
-               # has to be in the commands category
-               if command not in universe.categories["command"].values(): result = False
-
-               # administrators can run any command
-               elif self.account.getboolean("administrator"): result = True
-
-               # everyone can run non-administrative commands
-               elif not command.getboolean("administrative"): result = True
-
-               # otherwise the command cannot be run by this user
-               else: result = False
-
-               # pass back the result
-               return result
-
        def new_avatar(self):
                """Instantiate a new, unconfigured avatar for this user."""
                counter = 0
                while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
                self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
-               self.avatar.append("inherit", "template:actor")
+               self.avatar.append("inherit", "archetype:avatar")
                self.account.append("avatars", self.avatar.key)
 
        def delete_avatar(self, avatar):
@@ -697,6 +770,7 @@ class User:
                if self.avatar:
                        current = self.avatar.get("location")
                        self.avatar.set("default_location", current)
+                       self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
                        del universe.contents[current].contents[self.avatar.key]
                        self.avatar.remove_facet("location")
                        self.avatar.owner = None
@@ -722,23 +796,88 @@ def makedict(value):
        elif value.find(":") > 0: return eval("{" + value + "}")
        else: return { value: None }
 
-def broadcast(message):
+def broadcast(message, add_prompt=True):
        """Send a message to all connected users."""
-       for each_user in universe.userlist: each_user.send("$(eol)" + message)
+       for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
 
-def log(message):
+def log(message, level=0):
        """Log a message."""
 
-       # the time in posix log timestamp format
+       # a couple references we need
+       file_name = universe.categories["internal"]["logging"].get("file")
+       max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
+       syslog_name = universe.categories["internal"]["logging"].get("syslog")
        timestamp = asctime()[4:19]
 
-       # send the timestamp and message to standard output
-       print(timestamp + " " + message)
+       # turn the message into a list of lines
+       lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
+
+       # send the timestamp and line to a file
+       if file_name:
+               file_descriptor = file(file_name, "a")
+               for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
+               file_descriptor.flush()
+               file_descriptor.close()
+
+       # send the timestamp and line to standard output
+       if universe.categories["internal"]["logging"].getboolean("stdout"):
+               for line in lines: print(timestamp + " " + line)
+
+       # send the line to the system log
+       if syslog_name:
+               openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
+               for line in lines: syslog(line)
+               closelog()
+
+       # display to connected administrators
+       for user in universe.userlist:
+               if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
+                       # iterate over every line in the message
+                       full_message = ""
+                       for line in lines:
+                               full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
+                       user.send(full_message, flush=True)
+
+       # add to the recent log list
+       for line in lines:
+               while 0 < len(universe.loglines) >= max_log_lines: del universe.loglines[0]
+               universe.loglines.append((level, timestamp + " " + line))
+
+def get_loglines(level, start, stop=0):
+       """Return a specific range of loglines filtered by level."""
+
+       # begin with a blank message
+       message = ""
+
+       # filter the log lines
+       loglines = filter(lambda x,y: x>=level, universe.loglines)
+
+       # we need this in several places
+       count = len(loglines)
+
+       # don't proceed if there are no lines
+       if count:
+
+               # can't start before the begining or at the end
+               if start > count: start = count
+               if start < 1: start = 1
+
+               # can't stop before we start
+               if stop >= start: stop = start - 1
+
+               # some preamble
+               message += "There are " + str(len(universe.loglist))
+               message += " log lines in memory and " + str(count)
+               message += " at or above level " + str(level) + "."
+               message += " The lines from " + str(stop)
+               message += " to " + str(start) + " are:$(eol)$(eol)"
+
+               # add the text from the selected lines
+               for line in loglines[-start:-stop]:
+                       message += "   " + line[1] + "$(eol)"
 
-       # send the message to the system log
-       openlog("mudpy", LOG_PID, LOG_INFO | LOG_DAEMON)
-       syslog(message)
-       closelog()
+       # pass it back
+       return message
 
 def wrap_ansi_text(text, width):
        """Wrap text with arbitrary width while ignoring ANSI colors."""
@@ -899,7 +1038,7 @@ def replace_macros(user, text, is_input=False):
                else:
                        text = text.replace(macro, "")
                        if not is_input:
-                               log("Unexpected replacement macro " + macro + " encountered.")
+                               log("Unexpected replacement macro " + macro + " encountered.", 6)
 
        # replace the look-like-a-macro sequence
        text = text.replace("$_(", "$(")
@@ -960,7 +1099,7 @@ def check_for_connection(listening_socket):
                return None
 
        # note that we got one
-       log("Connection from " + address[0])
+       log("Connection from " + address[0], 2)
 
        # disable blocking so we can proceed whether or not we can send/receive
        connection.setblocking(0)
@@ -1157,7 +1296,7 @@ def handle_user_input(user):
        user.menu_seen = False
 
        # if the user's client echo is off, send a blank line for aesthetics
-       if not user.echoing: user.send("", "")
+       if user.echoing: user.received_newline = True
 
 def generic_menu_handler(user):
        """A generic menu choice handler."""
@@ -1199,7 +1338,7 @@ def handler_entering_account_name(user):
                else:
                        user.account = Element("account:" + name, universe)
                        user.account.set("name", name)
-                       log("New user: " + name)
+                       log("New user: " + name, 2)
                        user.state = "checking_new_account_name"
 
        # if the user entered nothing for a name, then buhbye
@@ -1287,61 +1426,70 @@ def handler_active(user):
        # get the next waiting line of input
        input_data = user.input_queue.pop(0)
 
-       # split out the command (first word) and parameters (everything else)
-       if input_data.find(" ") > 0:
-               command_name, parameters = input_data.split(" ", 1)
-       else:
-               command_name = input_data
-               parameters = ""
+       # is there input?
+       if input_data:
 
-       # lowercase the command
-       command_name = command_name.lower()
+               # split out the command (first word) and parameters (everything else)
+               if input_data.find(" ") > 0:
+                       command_name, parameters = input_data.split(" ", 1)
+               else:
+                       command_name = input_data
+                       parameters = ""
 
-       # the command matches a command word for which we have data
-       if command_name in universe.categories["command"]:
-               command = universe.categories["command"][command_name]
-       else: command = None
+               # lowercase the command
+               command_name = command_name.lower()
 
-       # if it's allowed, do it
-       if user.can_run(command): exec(command.get("action"))
+               # the command matches a command word for which we have data
+               if command_name in universe.categories["command"]:
+                       command = universe.categories["command"][command_name]
+               else: command = None
 
-       # otherwise, give an error
-       elif command_name: command_error(user, input_data)
+               # if it's allowed, do it
+               if user.avatar.can_run(command): exec(command.get("action"))
 
-def command_halt(user, parameters):
+               # otherwise, give an error
+               elif command_name: command_error(user.avatar, input_data)
+
+       # if no input, just idle back with a prompt
+       else: user.send("", just_prompt=True)
+       
+def command_halt(actor, parameters):
        """Halt the world."""
+       if actor.owner:
 
-       # see if there's a message or use a generic one
-       if parameters: message = "Halting: " + parameters
-       else: message = "User " + user.account.get("name") + " halted the world."
+               # see if there's a message or use a generic one
+               if parameters: message = "Halting: " + parameters
+               else: message = "User " + actor.owner.account.get("name") + " halted the world."
 
-       # let everyone know
-       broadcast(message)
-       log(message)
+               # let everyone know
+               broadcast(message, add_prompt=False)
+               log(message, 8)
 
-       # set a flag to terminate the world
-       universe.terminate_world = True
+               # set a flag to terminate the world
+               universe.terminate_world = True
 
-def command_reload(user):
+def command_reload(actor):
        """Reload all code modules, configs and data."""
+       if actor.owner:
 
-       # let the user know and log
-       user.send("Reloading all code modules, configs and data.")
-       log("User " + user.account.get("name") + " reloaded the world.")
+               # let the user know and log
+               actor.send("Reloading all code modules, configs and data.")
+               log("User " + actor.owner.account.get("name") + " reloaded the world.", 8)
 
-       # set a flag to reload
-       universe.reload_modules = True
+               # set a flag to reload
+               universe.reload_modules = True
 
-def command_quit(user):
+def command_quit(actor):
        """Leave the world and go back to the main menu."""
-       user.deactivate_avatar()
-       user.state = "main_utility"
+       if actor.owner:
+               actor.owner.deactivate_avatar()
+               actor.owner.state = "main_utility"
 
-def command_help(user, parameters):
+def command_help(actor, parameters):
        """List available commands and provide help for commands."""
 
        # did the user ask for help on a specific command word?
-       if parameters:
+       if parameters and actor.owner:
 
                # is the command word one for which we have data?
                if parameters in universe.categories["command"]:
@@ -1349,7 +1497,7 @@ def command_help(user, parameters):
                else: command = None
 
                # only for allowed commands
-               if user.can_run(command):
+               if actor.can_run(command):
 
                        # add a description if provided
                        description = command.get("description")
@@ -1378,7 +1526,7 @@ def command_help(user, parameters):
                sorted_commands.sort()
                for item in sorted_commands:
                        command = universe.categories["command"][item]
-                       if user.can_run(command):
+                       if actor.can_run(command):
                                description = command.get("description")
                                if not description:
                                        description = "(no short description provided)"
@@ -1388,20 +1536,25 @@ def command_help(user, parameters):
                output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
 
        # send the accumulated output to the user
-       user.send(output)
+       actor.send(output)
 
-def command_move(user, parameters):
+def command_move(actor, parameters):
        """Move the avatar in a given direction."""
-       if parameters in universe.contents[user.avatar.get("location")].portals():
-               user.avatar.move_direction(parameters)
-       else: user.send("You cannot go that way.")
+       if parameters in universe.contents[actor.get("location")].portals():
+               actor.move_direction(parameters)
+       else: actor.send("You cannot go that way.")
+
+def command_look(actor, parameters):
+       """Look around."""
+       if parameters: actor.send("You can't look at or in anything yet.")
+       else: actor.look_at(actor.get("location"))
 
-def command_say(user, parameters):
+def command_say(actor, parameters):
        """Speak to others in the same room."""
 
        # check for replacement macros
-       if replace_macros(user, parameters, True) != parameters:
-               user.send("You cannot speak $_(replacement macros).")
+       if replace_macros(actor.owner, parameters, True) != parameters:
+               actor.send("You cannot speak $_(replacement macros).")
 
        # the user entered a message
        elif parameters:
@@ -1436,14 +1589,14 @@ def command_say(user, parameters):
                        message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
 
                # tell the room
-               user.avatar.echo_to_location(user.avatar.get("name") + " " + action + "s, \"" + message + "\"")
-               user.send("You " + action + ", \"" + message + "\"")
+               actor.echo_to_location(actor.get("name") + " " + action + "s, \"" + message + "\"")
+               actor.send("You " + action + ", \"" + message + "\"")
 
        # there was no message
        else:
-               user.send("What do you want to say?")
+               actor.send("What do you want to say?")
 
-def command_show(user, parameters):
+def command_show(actor, parameters):
        """Show program data."""
        message = ""
        if parameters.find(" ") < 1:
@@ -1483,14 +1636,24 @@ def command_show(user, parameters):
                                        message = repr(eval(" ".join(arguments[1:])))
                                except:
                                        message = "Your expression raised an exception!"
+               elif arguments[0] == "log":
+                       if match("^\d+$", arguments[1]) and int(arguments[1]) > 0:
+                               linecount = int(arguments[1])
+                               if linecount > len(universe.loglines): linecount = len(universe.loglist)
+                               message = "There are " + str(len(universe.loglist)) + " log lines in memory."
+                               message += " The most recent " + str(linecount) + " lines are:$(eol)$(eol)"
+                               for line in universe.loglist[-linecount:]:
+                                       message += "   " + line + "$(eol)"
+                       else: message = "\"" + arguments[1] + "\" is not a positive integer greater than 0."
        if not message:
                if parameters: message = "I don't know what \"" + parameters + "\" is."
                else: message = "What do you want to show?"
-       user.send(message)
+       actor.send(message)
 
-def command_create(user, parameters):
+def command_create(actor, parameters):
        """Create an element if it does not exist."""
        if not parameters: message = "You must at least specify an element to create."
+       elif not actor.owner: message = ""
        else:
                arguments = parameters.split()
                if len(arguments) == 1: arguments.append("")
@@ -1499,28 +1662,29 @@ def command_create(user, parameters):
                        if element in universe.contents: message = "The \"" + element + "\" element already exists."
                        else:
                                message = "You create \"" + element + "\" within the universe."
-                               logline = user.account.get("name") + " created an element: " + element
+                               logline = actor.owner.account.get("name") + " created an element: " + element
                                if filename:
                                        logline += " in file " + filename
                                        if filename not in universe.files:
                                                message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
                                Element(element, universe, filename)
-                               log(logline)
+                               log(logline, 6)
                elif len(arguments) > 2: message = "You can only specify an element and a filename."
-       user.send(message)
+       actor.send(message)
 
-def command_destroy(user, parameters):
+def command_destroy(actor, parameters):
        """Destroy an element if it exists."""
-       if not parameters: message = "You must specify an element to destroy."
-       else:
-               if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
+       if actor.owner:
+               if not parameters: message = "You must specify an element to destroy."
                else:
-                       universe.contents[parameters].destroy()
-                       message = "You destroy \"" + parameters + "\" within the universe."
-                       log(user.account.get("name") + " destroyed an element: " + parameters)
-       user.send(message)
+                       if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
+                       else:
+                               universe.contents[parameters].destroy()
+                               message = "You destroy \"" + parameters + "\" within the universe."
+                               log(actor.owner.account.get("name") + " destroyed an element: " + parameters, 6)
+               actor.send(message)
 
-def command_set(user, parameters):
+def command_set(actor, parameters):
        """Set a facet of an element."""
        if not parameters: message = "You must specify an element, a facet and a value."
        else:
@@ -1533,9 +1697,9 @@ def command_set(user, parameters):
                        else:
                                universe.contents[element].set(facet, value)
                                message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
-       user.send(message)
+       actor.send(message)
 
-def command_delete(user, parameters):
+def command_delete(actor, parameters):
        """Delete a facet from an element."""
        if not parameters: message = "You must specify an element and a facet."
        else:
@@ -1547,11 +1711,11 @@ def command_delete(user, parameters):
                        if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
                        elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
                        else:
-                               universe.contents[element].delete(facet)
+                               universe.contents[element].remove_facet(facet)
                                message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
-       user.send(message)
+       actor.send(message)
 
-def command_error(user, input_data):
+def command_error(actor, input_data):
        """Generic error for an unrecognized command word."""
 
        # 90% of the time use a generic error
@@ -1563,7 +1727,7 @@ def command_error(user, input_data):
                message = "Arglebargle, glop-glyf!?!"
 
        # send the error message
-       user.send(message)
+       actor.send(message)
 
 # if there is no universe, create an empty one
 if not "universe" in locals(): universe = Universe()