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