601bc82c3ca7d2e3704e1465ef795c31478e0100
[mudpy.git] / mudpy / command.py
1 """User command functions for the mudpy engine."""
2
3 # Copyright (c) 2004-2019 mudpy authors. Permission to use, copy,
4 # modify, and distribute this software is granted under terms
5 # provided in the LICENSE file distributed with this software.
6
7 import random
8 import re
9 import traceback
10 import unicodedata
11
12 import mudpy
13
14
15 def chat(actor, parameters):
16     """Toggle chat mode."""
17     mode = actor.get("mode")
18     if not mode:
19         actor.set("mode", "chat")
20         actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
21     elif mode == "chat":
22         actor.remove_facet("mode")
23         actor.send("Exiting chat mode.")
24     else:
25         actor.send("Sorry, but you're already busy with something else!")
26
27
28 def create(actor, parameters):
29     """Create an element if it does not exist."""
30     if not parameters:
31         message = "You must at least specify an element to create."
32     elif not actor.owner:
33         message = ""
34     else:
35         arguments = parameters.split()
36         if len(arguments) == 1:
37             arguments.append("")
38         if len(arguments) == 2:
39             element, filename = arguments
40             if element in actor.universe.contents:
41                 message = 'The "' + element + '" element already exists.'
42             else:
43                 message = ('You create "' +
44                            element + '" within the universe.')
45                 logline = actor.owner.account.get(
46                     "name"
47                 ) + " created an element: " + element
48                 if filename:
49                     logline += " in file " + filename
50                     if filename not in actor.universe.files:
51                         message += (
52                             ' Warning: "' + filename + '" is not yet '
53                             "included in any other file and will not be read "
54                             "on startup unless this is remedied.")
55                 mudpy.misc.Element(element, actor.universe, filename)
56                 mudpy.misc.log(logline, 6)
57         elif len(arguments) > 2:
58             message = "You can only specify an element and a filename."
59     actor.send(message)
60
61
62 def delete(actor, parameters):
63     """Delete a facet from an element."""
64     if not parameters:
65         message = "You must specify an element and a facet."
66     else:
67         arguments = parameters.split(" ")
68         if len(arguments) == 1:
69             message = ('What facet of element "' + arguments[0]
70                        + '" would you like to delete?')
71         elif len(arguments) != 2:
72             message = "You may only specify an element and a facet."
73         else:
74             element, facet = arguments
75             if element not in actor.universe.contents:
76                 message = 'The "' + element + '" element does not exist.'
77             elif facet not in actor.universe.contents[element].facets():
78                 message = ('The "' + element + '" element has no "' + facet
79                            + '" facet.')
80             else:
81                 actor.universe.contents[element].remove_facet(facet)
82                 message = ('You have successfully deleted the "' + facet
83                            + '" facet of element "' + element
84                            + '". Try "show element ' +
85                            element + '" for verification.')
86     actor.send(message)
87
88
89 def destroy(actor, parameters):
90     """Destroy an element if it exists."""
91     if actor.owner:
92         if not parameters:
93             message = "You must specify an element to destroy."
94         else:
95             if parameters not in actor.universe.contents:
96                 message = 'The "' + parameters + '" element does not exist.'
97             else:
98                 actor.universe.contents[parameters].destroy()
99                 message = ('You destroy "' + parameters
100                            + '" within the universe.')
101                 mudpy.misc.log(
102                     actor.owner.account.get(
103                         "name"
104                     ) + " destroyed an element: " + parameters,
105                     6
106                 )
107         actor.send(message)
108
109
110 def error(actor, input_data):
111     """Generic error for an unrecognized command word."""
112
113     # 90% of the time use a generic error
114     if random.randrange(10):
115         message = '''I'm not sure what "''' + input_data + '''" means...'''
116
117     # 10% of the time use the classic diku error
118     else:
119         message = "Arglebargle, glop-glyf!?!"
120
121     # try to send the error message, and log if we can't
122     try:
123         actor.send(message)
124     except Exception:
125         mudpy.misc.log(
126             'Sending a command error to user %s raised exception...\n%s' % (
127                 actor.owner.account.get("name"), traceback.format_exc()))
128
129
130 def halt(actor, parameters):
131     """Halt the world."""
132     if actor.owner:
133
134         # see if there's a message or use a generic one
135         if parameters:
136             message = "Halting: " + parameters
137         else:
138             message = "User " + actor.owner.account.get(
139                 "name"
140             ) + " halted the world."
141
142         # let everyone know
143         mudpy.misc.broadcast(message, add_prompt=False)
144         mudpy.misc.log(message, 8)
145
146         # set a flag to terminate the world
147         actor.universe.terminate_flag = True
148
149
150 def help(actor, parameters):
151     """List available commands and provide help for commands."""
152
153     # did the user ask for help on a specific command word?
154     if parameters and actor.owner:
155
156         # is the command word one for which we have data?
157         command = mudpy.misc.find_command(parameters)
158
159         # only for allowed commands
160         if actor.can_run(command):
161
162             # add a description if provided
163             description = command.get("description")
164             if not description:
165                 description = "(no short description provided)"
166             if command.get("administrative"):
167                 output = "$(red)"
168             else:
169                 output = "$(grn)"
170             output = "%s%s$(nrm) - %s$(eol)$(eol)" % (
171                 output, command.subkey, description)
172
173             # add the help text if provided
174             help_text = command.get("help")
175             if not help_text:
176                 help_text = "No help is provided for this command."
177             output += help_text
178
179             # list related commands
180             see_also = command.get("see_also")
181             if see_also:
182                 really_see_also = ""
183                 for item in see_also:
184                     if item in actor.universe.groups["command"]:
185                         command = actor.universe.groups["command"][item]
186                         if actor.can_run(command):
187                             if really_see_also:
188                                 really_see_also += ", "
189                             if command.get("administrative"):
190                                 really_see_also += "$(red)"
191                             else:
192                                 really_see_also += "$(grn)"
193                             really_see_also += item + "$(nrm)"
194                 if really_see_also:
195                     output += "$(eol)$(eol)See also: " + really_see_also
196
197         # no data for the requested command word
198         else:
199             output = "That is not an available command."
200
201     # no specific command word was indicated
202     else:
203
204         # preamble text
205         output = ("These are the commands available to you [brackets indicate "
206                   "optional portion]:$(eol)$(eol)")
207
208         # list command names in alphabetical order
209         for command_name, command in sorted(
210                 actor.universe.groups["command"].items()):
211
212             # skip over disallowed commands
213             if actor.can_run(command):
214
215                 # start incrementing substrings
216                 for position in range(1, len(command_name) + 1):
217
218                     # we've found our shortest possible abbreviation
219                     candidate = mudpy.misc.find_command(
220                             command_name[:position])
221                     try:
222                         if candidate.subkey == command_name:
223                             break
224                     except AttributeError:
225                         pass
226
227                 # use square brackets to indicate optional part of command name
228                 if position < len(command_name):
229                     abbrev = "%s[%s]" % (
230                         command_name[:position], command_name[position:])
231                 else:
232                     abbrev = command_name
233
234                 # supply a useful default if the short description is missing
235                 description = command.get(
236                     "description", "(no short description provided)")
237
238                 # administrative command names are in red, others in green
239                 if command.get("administrative"):
240                     color = "red"
241                 else:
242                     color = "grn"
243
244                 # format the entry for this command
245                 output = "%s   $(%s)%s$(nrm) - %s$(eol)" % (
246                     output, color, abbrev, description)
247
248         # add a footer with instructions on getting additional information
249         output = ('%s $(eol)Enter "help COMMAND" for help on a command named '
250                   '"COMMAND".' % output)
251
252     # send the accumulated output to the user
253     actor.send(output)
254
255
256 def look(actor, parameters):
257     """Look around."""
258     if parameters:
259         actor.send("You can't look at or in anything yet.")
260     else:
261         actor.look_at(actor.get("location"))
262
263
264 def move(actor, parameters):
265     """Move the avatar in a given direction."""
266     for portal in sorted(
267             actor.universe.contents[actor.get("location")].portals()):
268         if portal.startswith(parameters):
269             actor.move_direction(portal)
270             return(portal)
271     actor.send("You cannot go that way.")
272
273
274 def preferences(actor, parameters):
275     """List, view and change actor preferences."""
276
277     # Escape replacement macros in preferences
278     parameters = mudpy.misc.escape_macros(parameters)
279
280     message = ""
281     arguments = parameters.split()
282     allowed_prefs = set()
283     base_prefs = []
284     user_config = actor.universe.contents.get("mudpy.user")
285     if user_config:
286         base_prefs = user_config.get("pref_allow", [])
287         allowed_prefs.update(base_prefs)
288         if actor.owner.account.get("administrator"):
289             allowed_prefs.update(user_config.get("pref_admin", []))
290     if not arguments:
291         message += "These are your current preferences:"
292
293         # color-code base and admin prefs
294         for pref in sorted(allowed_prefs):
295             if pref in base_prefs:
296                 color = "grn"
297             else:
298                 color = "red"
299             message += ("$(eol)   $(%s)%s$(nrm) - %s" % (
300                 color, pref, actor.owner.account.get(pref, "<not set>")))
301
302     elif arguments[0] not in allowed_prefs:
303         message += (
304             'Preference "%s" does not exist. Try the `preferences` command by '
305             "itself for a list of valid preferences." % arguments[0])
306     elif len(arguments) == 1:
307         message += "%s" % actor.owner.account.get(arguments[0], "<not set>")
308     else:
309         pref = arguments[0]
310         value = " ".join(arguments[1:])
311         try:
312             actor.owner.account.set(pref, value)
313             message += 'Preference "%s" set to "%s".' % (pref, value)
314         except ValueError:
315             message = (
316                 'Preference "%s" cannot be set to type "%s".' % (
317                     pref, type(value)))
318     actor.send(message)
319
320
321 def quit(actor, parameters):
322     """Leave the world and go back to the main menu."""
323     if actor.owner:
324         actor.owner.state = "main_utility"
325         actor.owner.deactivate_avatar()
326
327
328 def reload(actor, parameters):
329     """Reload all code modules, configs and data."""
330     if actor.owner:
331
332         # let the user know and log
333         actor.send("Reloading all code modules, configs and data.")
334         mudpy.misc.log(
335             "User " +
336             actor.owner.account.get("name") + " reloaded the world.",
337             6
338         )
339
340         # set a flag to reload
341         actor.universe.reload_flag = True
342
343
344 def say(actor, parameters):
345     """Speak to others in the same area."""
346
347     # check for replacement macros and escape them
348     parameters = mudpy.misc.escape_macros(parameters)
349
350     # if the message is wrapped in quotes, remove them and leave contents
351     # intact
352     if parameters.startswith('"') and parameters.endswith('"'):
353         message = parameters[1:-1]
354         literal = True
355
356     # otherwise, get rid of stray quote marks on the ends of the message
357     else:
358         message = parameters.strip('''"'`''')
359         literal = False
360
361     # the user entered a message
362     if message:
363
364         # match the punctuation used, if any, to an action
365         if "mudpy.linguistic" in actor.universe.contents:
366             actions = actor.universe.contents[
367                 "mudpy.linguistic"].get("actions", {})
368             default_punctuation = (actor.universe.contents[
369                 "mudpy.linguistic"].get("default_punctuation", "."))
370         else:
371             actions = {}
372             default_punctuation = "."
373         action = ""
374
375         # reverse sort punctuation options so the longest match wins
376         for mark in sorted(actions.keys(), reverse=True):
377             if not literal and message.endswith(mark):
378                 action = actions[mark]
379                 break
380
381         # add punctuation if needed
382         if not action:
383             action = actions[default_punctuation]
384             if message and not (
385                literal or unicodedata.category(message[-1]) == "Po"
386                ):
387                 message += default_punctuation
388
389         # failsafe checks to avoid unwanted reformatting and null strings
390         if message and not literal:
391
392             # decapitalize the first letter to improve matching
393             message = message[0].lower() + message[1:]
394
395             # iterate over all words in message, replacing typos
396             if "mudpy.linguistic" in actor.universe.contents:
397                 typos = actor.universe.contents[
398                     "mudpy.linguistic"].get("typos", {})
399             else:
400                 typos = {}
401             words = message.split()
402             for index in range(len(words)):
403                 word = words[index]
404                 while unicodedata.category(word[0]) == "Po":
405                     word = word[1:]
406                 while unicodedata.category(word[-1]) == "Po":
407                     word = word[:-1]
408                 if word in typos.keys():
409                     words[index] = words[index].replace(word, typos[word])
410             message = " ".join(words)
411
412             # capitalize the first letter
413             message = message[0].upper() + message[1:]
414
415     # tell the area
416     if message:
417         actor.echo_to_location(
418             actor.get("name") + " " + action + 's, "' + message + '"'
419         )
420         actor.send("You " + action + ', "' + message + '"')
421
422     # there was no message
423     else:
424         actor.send("What do you want to say?")
425
426
427 def c_set(actor, parameters):
428     """Set a facet of an element."""
429     if not parameters:
430         message = "You must specify an element, a facet and a value."
431     else:
432         arguments = parameters.split(" ", 2)
433         if len(arguments) == 1:
434             message = ('What facet of element "' + arguments[0]
435                        + '" would you like to set?')
436         elif len(arguments) == 2:
437             message = ('What value would you like to set for the "' +
438                        arguments[1] + '" facet of the "' + arguments[0]
439                        + '" element?')
440         else:
441             element, facet, value = arguments
442             if element not in actor.universe.contents:
443                 message = 'The "' + element + '" element does not exist.'
444             else:
445                 try:
446                     actor.universe.contents[element].set(facet, value)
447                 except PermissionError:
448                     message = ('The "%s" element is kept in read-only file '
449                                '"%s" and cannot be altered.' %
450                                (element, actor.universe.contents[
451                                         element].origin.source))
452                 except ValueError:
453                     message = ('Value "%s" of type "%s" cannot be coerced '
454                                'to the correct datatype for facet "%s".' %
455                                (value, type(value), facet))
456                 else:
457                     message = ('You have successfully (re)set the "' + facet
458                                + '" facet of element "' + element
459                                + '". Try "show element ' +
460                                element + '" for verification.')
461     actor.send(message)
462
463
464 def show(actor, parameters):
465     """Show program data."""
466     message = ""
467     arguments = parameters.split()
468     if not parameters:
469         message = "What do you want to show?"
470     elif arguments[0] == "version":
471         message = repr(actor.universe.versions)
472     elif arguments[0] == "time":
473         message = "%s increments elapsed since the world was created." % (
474             str(actor.universe.groups["internal"]["counters"].get("elapsed")))
475     elif arguments[0] == "groups":
476         message = "These are the element groups:$(eol)"
477         groups = list(actor.universe.groups.keys())
478         groups.sort()
479         for group in groups:
480             message += "$(eol)   $(grn)" + group + "$(nrm)"
481     elif arguments[0] == "files":
482         message = "These are the current files containing the universe:$(eol)"
483         filenames = sorted(actor.universe.files)
484         for filename in filenames:
485             if actor.universe.files[filename].is_writeable():
486                 status = "rw"
487             else:
488                 status = "ro"
489             message += ("$(eol)   $(red)(%s) $(grn)%s$(nrm)" %
490                         (status, filename))
491             if actor.universe.files[filename].flags:
492                 message += (" $(yel)[%s]$(nrm)" %
493                             ",".join(actor.universe.files[filename].flags))
494     elif arguments[0] == "group":
495         if len(arguments) != 2:
496             message = "You must specify one group."
497         elif arguments[1] in actor.universe.groups:
498             message = ('These are the elements in the "' + arguments[1]
499                        + '" group:$(eol)')
500             elements = [
501                 (
502                     actor.universe.groups[arguments[1]][x].key
503                 ) for x in actor.universe.groups[arguments[1]].keys()
504             ]
505             elements.sort()
506             for element in elements:
507                 message += "$(eol)   $(grn)" + element + "$(nrm)"
508         else:
509             message = 'Group "' + arguments[1] + '" does not exist.'
510     elif arguments[0] == "file":
511         if len(arguments) != 2:
512             message = "You must specify one file."
513         elif arguments[1] in actor.universe.files:
514             message = ('These are the nodes in the "' + arguments[1]
515                        + '" file:$(eol)')
516             elements = sorted(actor.universe.files[arguments[1]].data)
517             for element in elements:
518                 message += "$(eol)   $(grn)" + element + "$(nrm)"
519         else:
520             message = 'File "%s" does not exist.' % arguments[1]
521     elif arguments[0] == "element":
522         if len(arguments) != 2:
523             message = "You must specify one element."
524         elif arguments[1].strip(".") in actor.universe.contents:
525             element = actor.universe.contents[arguments[1].strip(".")]
526             message = ('These are the properties of the "' + arguments[1]
527                        + '" element (in "' + element.origin.source
528                        + '"):$(eol)')
529             facets = element.facets()
530             for facet in sorted(facets):
531                 message += ("$(eol)   $(grn)%s: $(red)%s$(nrm)" %
532                             (facet, str(facets[facet])))
533         else:
534             message = 'Element "' + arguments[1] + '" does not exist.'
535     elif arguments[0] == "result":
536         if len(arguments) < 2:
537             message = "You need to specify an expression."
538         else:
539             try:
540                 # there is no other option than to use eval() for this, since
541                 # its purpose is to evaluate arbitrary expressions, so do what
542                 # we can to secure it and whitelist it for bandit analysis
543                 message = repr(eval(  # nosec
544                     " ".join(arguments[1:]),
545                     {"mudpy": mudpy, "universe": actor.universe}))
546             except Exception as e:
547                 message = ("$(red)Your expression raised an exception...$(eol)"
548                            "$(eol)$(bld)%s$(nrm)" % e)
549     elif arguments[0] == "log":
550         if len(arguments) == 4:
551             if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
552                 stop = int(arguments[3])
553             else:
554                 stop = -1
555         else:
556             stop = 0
557         if len(arguments) >= 3:
558             if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
559                 start = int(arguments[2])
560             else:
561                 start = -1
562         else:
563             start = 10
564         if len(arguments) >= 2:
565             if (re.match(r"^\d+$", arguments[1])
566                     and 0 <= int(arguments[1]) <= 9):
567                 level = int(arguments[1])
568             else:
569                 level = -1
570         elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
571             level = actor.owner.account.get("loglevel", 0)
572         else:
573             level = 1
574         if level > -1 and start > -1 and stop > -1:
575             message = mudpy.misc.get_loglines(level, start, stop)
576         else:
577             message = ("When specified, level must be 0-9 (default 1), "
578                        "start and stop must be >=1 (default 10 and 1).")
579     else:
580         message = '''I don't know what "''' + parameters + '" is.'
581     actor.send(message)