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