]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/game/chat.lua
c4fb6314e564e2f90e6e7bd9e7190b4863d5040d
[dragonfireclient.git] / builtin / game / chat.lua
1 -- Minetest: builtin/game/chat.lua
2
3 local S = core.get_translator("__builtin")
4
5 -- Helper function that implements search and replace without pattern matching
6 -- Returns the string and a boolean indicating whether or not the string was modified
7 local function safe_gsub(s, replace, with)
8         local i1, i2 = s:find(replace, 1, true)
9         if not i1 then
10                 return s, false
11         end
12
13         return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
14 end
15
16 --
17 -- Chat message formatter
18 --
19
20 -- Implemented in Lua to allow redefinition
21 function core.format_chat_message(name, message)
22         local error_str = "Invalid chat message format - missing %s"
23         local str = core.settings:get("chat_message_format")
24         local replaced
25
26         -- Name
27         str, replaced = safe_gsub(str, "@name", name)
28         if not replaced then
29                 error(error_str:format("@name"), 2)
30         end
31
32         -- Timestamp
33         str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))
34
35         -- Insert the message into the string only after finishing all other processing
36         str, replaced = safe_gsub(str, "@message", message)
37         if not replaced then
38                 error(error_str:format("@message"), 2)
39         end
40
41         return str
42 end
43
44 --
45 -- Chat command handler
46 --
47
48 core.chatcommands = core.registered_chatcommands -- BACKWARDS COMPATIBILITY
49
50 local msg_time_threshold =
51         tonumber(core.settings:get("chatcommand_msg_time_threshold")) or 0.1
52 core.register_on_chat_message(function(name, message)
53         if message:sub(1,1) ~= "/" then
54                 return
55         end
56
57         local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
58         if not cmd then
59                 core.chat_send_player(name, "-!- "..S("Empty command."))
60                 return true
61         end
62
63         param = param or ""
64
65         -- Run core.registered_on_chatcommands callbacks.
66         if core.run_callbacks(core.registered_on_chatcommands, 5, name, cmd, param) then
67                 return true
68         end
69
70         local cmd_def = core.registered_chatcommands[cmd]
71         if not cmd_def then
72                 core.chat_send_player(name, "-!- "..S("Invalid command: @1", cmd))
73                 return true
74         end
75         local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
76         if has_privs then
77                 core.set_last_run_mod(cmd_def.mod_origin)
78                 local t_before = core.get_us_time()
79                 local success, result = cmd_def.func(name, param)
80                 local delay = (core.get_us_time() - t_before) / 1000000
81                 if success == false and result == nil then
82                         core.chat_send_player(name, "-!- "..S("Invalid command usage."))
83                         local help_def = core.registered_chatcommands["help"]
84                         if help_def then
85                                 local _, helpmsg = help_def.func(name, cmd)
86                                 if helpmsg then
87                                         core.chat_send_player(name, helpmsg)
88                                 end
89                         end
90                 else
91                         if delay > msg_time_threshold then
92                                 -- Show how much time it took to execute the command
93                                 if result then
94                                         result = result .. core.colorize("#f3d2ff", S(" (@1 s)",
95                                                 string.format("%.5f", delay)))
96                                 else
97                                         result = core.colorize("#f3d2ff", S(
98                                                 "Command execution took @1 s",
99                                                 string.format("%.5f", delay)))
100                                 end
101                         end
102                         if result then
103                                 core.chat_send_player(name, result)
104                         end
105                 end
106         else
107                 core.chat_send_player(name,
108                                 S("You don't have permission to run this command "
109                                 .. "(missing privileges: @1).",
110                                 table.concat(missing_privs, ", ")))
111         end
112         return true  -- Handled chat message
113 end)
114
115 if core.settings:get_bool("profiler.load") then
116         -- Run after register_chatcommand and its register_on_chat_message
117         -- Before any chatcommands that should be profiled
118         profiler.init_chatcommand()
119 end
120
121 -- Parses a "range" string in the format of "here (number)" or
122 -- "(x1, y1, z1) (x2, y2, z2)", returning two position vectors
123 local function parse_range_str(player_name, str)
124         local p1, p2
125         local args = str:split(" ")
126
127         if args[1] == "here" then
128                 p1, p2 = core.get_player_radius_area(player_name, tonumber(args[2]))
129                 if p1 == nil then
130                         return false, S("Unable to get position of player @1.", player_name)
131                 end
132         else
133                 p1, p2 = core.string_to_area(str)
134                 if p1 == nil then
135                         return false, S("Incorrect area format. "
136                                 .. "Expected: (x1,y1,z1) (x2,y2,z2)")
137                 end
138         end
139
140         return p1, p2
141 end
142
143 --
144 -- Chat commands
145 --
146 core.register_chatcommand("me", {
147         params = S("<action>"),
148         description = S("Show chat action (e.g., '/me orders a pizza' "
149                 .. "displays '<player name> orders a pizza')"),
150         privs = {shout=true},
151         func = function(name, param)
152                 core.chat_send_all("* " .. name .. " " .. param)
153                 return true
154         end,
155 })
156
157 core.register_chatcommand("admin", {
158         description = S("Show the name of the server owner"),
159         func = function(name)
160                 local admin = core.settings:get("name")
161                 if admin then
162                         return true, S("The administrator of this server is @1.", admin)
163                 else
164                         return false, S("There's no administrator named "
165                                 .. "in the config file.")
166                 end
167         end,
168 })
169
170 local function privileges_of(name, privs)
171         if not privs then
172                 privs = core.get_player_privs(name)
173         end
174         local privstr = core.privs_to_string(privs, ", ")
175         if privstr == "" then
176                 return S("@1 does not have any privileges.", name)
177         else
178                 return S("Privileges of @1: @2", name, privstr)
179         end
180 end
181
182 core.register_chatcommand("privs", {
183         params = S("[<name>]"),
184         description = S("Show privileges of yourself or another player"),
185         func = function(caller, param)
186                 param = param:trim()
187                 local name = (param ~= "" and param or caller)
188                 if not core.player_exists(name) then
189                         return false, S("Player @1 does not exist.", name)
190                 end
191                 return true, privileges_of(name)
192         end,
193 })
194
195 core.register_chatcommand("haspriv", {
196         params = S("<privilege>"),
197         description = S("Return list of all online players with privilege"),
198         privs = {basic_privs = true},
199         func = function(caller, param)
200                 param = param:trim()
201                 if param == "" then
202                         return false, S("Invalid parameters (see /help haspriv).")
203                 end
204                 if not core.registered_privileges[param] then
205                         return false, S("Unknown privilege!")
206                 end
207                 local privs = core.string_to_privs(param)
208                 local players_with_priv = {}
209                 for _, player in pairs(core.get_connected_players()) do
210                         local player_name = player:get_player_name()
211                         if core.check_player_privs(player_name, privs) then
212                                 table.insert(players_with_priv, player_name)
213                         end
214                 end
215                 if #players_with_priv == 0 then
216                         return true, S("No online player has the \"@1\" privilege.",
217                                         param)
218                 else
219                         return true, S("Players online with the \"@1\" privilege: @2",
220                                         param,
221                                         table.concat(players_with_priv, ", "))
222                 end
223         end
224 })
225
226 local function handle_grant_command(caller, grantname, grantprivstr)
227         local caller_privs = core.get_player_privs(caller)
228         if not (caller_privs.privs or caller_privs.basic_privs) then
229                 return false, S("Your privileges are insufficient.")
230         end
231
232         if not core.get_auth_handler().get_auth(grantname) then
233                 return false, S("Player @1 does not exist.", grantname)
234         end
235         local grantprivs = core.string_to_privs(grantprivstr)
236         if grantprivstr == "all" then
237                 grantprivs = core.registered_privileges
238         end
239         local privs = core.get_player_privs(grantname)
240         local privs_unknown = ""
241         local basic_privs =
242                 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
243         for priv, _ in pairs(grantprivs) do
244                 if not basic_privs[priv] and not caller_privs.privs then
245                         return false, S("Your privileges are insufficient. "..
246                                         "'@1' only allows you to grant: @2",
247                                         "basic_privs",
248                                         core.privs_to_string(basic_privs, ', '))
249                 end
250                 if not core.registered_privileges[priv] then
251                         privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
252                 end
253                 privs[priv] = true
254         end
255         if privs_unknown ~= "" then
256                 return false, privs_unknown
257         end
258         core.set_player_privs(grantname, privs)
259         for priv, _ in pairs(grantprivs) do
260                 -- call the on_grant callbacks
261                 core.run_priv_callbacks(grantname, priv, caller, "grant")
262         end
263         core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
264         if grantname ~= caller then
265                 core.chat_send_player(grantname,
266                                 S("@1 granted you privileges: @2", caller,
267                                 core.privs_to_string(grantprivs, ', ')))
268         end
269         return true, privileges_of(grantname)
270 end
271
272 core.register_chatcommand("grant", {
273         params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
274         description = S("Give privileges to player"),
275         func = function(name, param)
276                 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
277                 if not grantname or not grantprivstr then
278                         return false, S("Invalid parameters (see /help grant).")
279                 end
280                 return handle_grant_command(name, grantname, grantprivstr)
281         end,
282 })
283
284 core.register_chatcommand("grantme", {
285         params = S("<privilege> [, <privilege2> [<...>]] | all"),
286         description = S("Grant privileges to yourself"),
287         func = function(name, param)
288                 if param == "" then
289                         return false, S("Invalid parameters (see /help grantme).")
290                 end
291                 return handle_grant_command(name, name, param)
292         end,
293 })
294
295 local function handle_revoke_command(caller, revokename, revokeprivstr)
296         local caller_privs = core.get_player_privs(caller)
297         if not (caller_privs.privs or caller_privs.basic_privs) then
298                 return false, S("Your privileges are insufficient.")
299         end
300
301         if not core.get_auth_handler().get_auth(revokename) then
302                 return false, S("Player @1 does not exist.", revokename)
303         end
304
305         local privs = core.get_player_privs(revokename)
306
307         local revokeprivs = core.string_to_privs(revokeprivstr)
308         local is_singleplayer = core.is_singleplayer()
309         local is_admin = not is_singleplayer
310                         and revokename == core.settings:get("name")
311                         and revokename ~= ""
312         if revokeprivstr == "all" then
313                 revokeprivs = table.copy(privs)
314         end
315
316         local privs_unknown = ""
317         local basic_privs =
318                 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
319         local irrevokable = {}
320         local has_irrevokable_priv = false
321         for priv, _ in pairs(revokeprivs) do
322                 if not basic_privs[priv] and not caller_privs.privs then
323                         return false, S("Your privileges are insufficient. "..
324                                         "'@1' only allows you to revoke: @2",
325                                         "basic_privs",
326                                         core.privs_to_string(basic_privs, ', '))
327                 end
328                 local def = core.registered_privileges[priv]
329                 if not def then
330                         -- Old/removed privileges might still be granted to certain players
331                         if not privs[priv] then
332                                 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
333                         end
334                 elseif is_singleplayer and def.give_to_singleplayer then
335                         irrevokable[priv] = true
336                 elseif is_admin and def.give_to_admin then
337                         irrevokable[priv] = true
338                 end
339         end
340         for priv, _ in pairs(irrevokable) do
341                 revokeprivs[priv] = nil
342                 has_irrevokable_priv = true
343         end
344         if privs_unknown ~= "" then
345                 return false, privs_unknown
346         end
347         if has_irrevokable_priv then
348                 if is_singleplayer then
349                         core.chat_send_player(caller,
350                                         S("Note: Cannot revoke in singleplayer: @1",
351                                         core.privs_to_string(irrevokable, ', ')))
352                 elseif is_admin then
353                         core.chat_send_player(caller,
354                                         S("Note: Cannot revoke from admin: @1",
355                                         core.privs_to_string(irrevokable, ', ')))
356                 end
357         end
358
359         local revokecount = 0
360         for priv, _ in pairs(revokeprivs) do
361                 privs[priv] = nil
362                 revokecount = revokecount + 1
363         end
364
365         if revokecount == 0 then
366                 return false, S("No privileges were revoked.")
367         end
368
369         core.set_player_privs(revokename, privs)
370         for priv, _ in pairs(revokeprivs) do
371                 -- call the on_revoke callbacks
372                 core.run_priv_callbacks(revokename, priv, caller, "revoke")
373         end
374         local new_privs = core.get_player_privs(revokename)
375
376         core.log("action", caller..' revoked ('
377                         ..core.privs_to_string(revokeprivs, ', ')
378                         ..') privileges from '..revokename)
379         if revokename ~= caller then
380                 core.chat_send_player(revokename,
381                         S("@1 revoked privileges from you: @2", caller,
382                         core.privs_to_string(revokeprivs, ', ')))
383         end
384         return true, privileges_of(revokename, new_privs)
385 end
386
387 core.register_chatcommand("revoke", {
388         params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
389         description = S("Remove privileges from player"),
390         privs = {},
391         func = function(name, param)
392                 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
393                 if not revokename or not revokeprivstr then
394                         return false, S("Invalid parameters (see /help revoke).")
395                 end
396                 return handle_revoke_command(name, revokename, revokeprivstr)
397         end,
398 })
399
400 core.register_chatcommand("revokeme", {
401         params = S("<privilege> [, <privilege2> [<...>]] | all"),
402         description = S("Revoke privileges from yourself"),
403         privs = {},
404         func = function(name, param)
405                 if param == "" then
406                         return false, S("Invalid parameters (see /help revokeme).")
407                 end
408                 return handle_revoke_command(name, name, param)
409         end,
410 })
411
412 core.register_chatcommand("setpassword", {
413         params = S("<name> <password>"),
414         description = S("Set player's password"),
415         privs = {password=true},
416         func = function(name, param)
417                 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
418                 if not toname then
419                         toname = param:match("^([^ ]+) *$")
420                         raw_password = nil
421                 end
422
423                 if not toname then
424                         return false, S("Name field required.")
425                 end
426
427                 local msg_chat, msg_log, msg_ret
428                 if not raw_password then
429                         core.set_player_password(toname, "")
430                         msg_chat = S("Your password was cleared by @1.", name)
431                         msg_log = name .. " clears password of " .. toname .. "."
432                         msg_ret = S("Password of player \"@1\" cleared.", toname)
433                 else
434                         core.set_player_password(toname,
435                                         core.get_password_hash(toname,
436                                                         raw_password))
437                         msg_chat = S("Your password was set by @1.", name)
438                         msg_log = name .. " sets password of " .. toname .. "."
439                         msg_ret = S("Password of player \"@1\" set.", toname)
440                 end
441
442                 if toname ~= name then
443                         core.chat_send_player(toname, msg_chat)
444                 end
445
446                 core.log("action", msg_log)
447
448                 return true, msg_ret
449         end,
450 })
451
452 core.register_chatcommand("clearpassword", {
453         params = S("<name>"),
454         description = S("Set empty password for a player"),
455         privs = {password=true},
456         func = function(name, param)
457                 local toname = param
458                 if toname == "" then
459                         return false, S("Name field required.")
460                 end
461                 core.set_player_password(toname, '')
462
463                 core.log("action", name .. " clears password of " .. toname .. ".")
464
465                 return true, S("Password of player \"@1\" cleared.", toname)
466         end,
467 })
468
469 core.register_chatcommand("auth_reload", {
470         params = "",
471         description = S("Reload authentication data"),
472         privs = {server=true},
473         func = function(name, param)
474                 local done = core.auth_reload()
475                 return done, (done and S("Done.") or S("Failed."))
476         end,
477 })
478
479 core.register_chatcommand("remove_player", {
480         params = S("<name>"),
481         description = S("Remove a player's data"),
482         privs = {server=true},
483         func = function(name, param)
484                 local toname = param
485                 if toname == "" then
486                         return false, S("Name field required.")
487                 end
488
489                 local rc = core.remove_player(toname)
490
491                 if rc == 0 then
492                         core.log("action", name .. " removed player data of " .. toname .. ".")
493                         return true, S("Player \"@1\" removed.", toname)
494                 elseif rc == 1 then
495                         return true, S("No such player \"@1\" to remove.", toname)
496                 elseif rc == 2 then
497                         return true, S("Player \"@1\" is connected, cannot remove.", toname)
498                 end
499
500                 return false, S("Unhandled remove_player return code @1.", tostring(rc))
501         end,
502 })
503
504
505 -- pos may be a non-integer position
506 local function find_free_position_near(pos)
507         local tries = {
508                 vector.new( 1, 0,  0),
509                 vector.new(-1, 0,  0),
510                 vector.new( 0, 0,  1),
511                 vector.new( 0, 0, -1),
512         }
513         for _, d in ipairs(tries) do
514                 local p = vector.add(pos, d)
515                 local n = core.get_node_or_nil(p)
516                 if n then
517                         local def = core.registered_nodes[n.name]
518                         if def and not def.walkable then
519                                 return p
520                         end
521                 end
522         end
523         return pos
524 end
525
526 -- Teleports player <name> to <p> if possible
527 local function teleport_to_pos(name, p)
528         local lm = 31007 -- equals MAX_MAP_GENERATION_LIMIT in C++
529         if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
530                         or p.z < -lm or p.z > lm then
531                 return false, S("Cannot teleport out of map bounds!")
532         end
533         local teleportee = core.get_player_by_name(name)
534         if not teleportee then
535                 return false, S("Cannot get player with name @1.", name)
536         end
537         if teleportee:get_attach() then
538                 return false, S("Cannot teleport, @1 " ..
539                         "is attached to an object!", name)
540         end
541         teleportee:set_pos(p)
542         return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
543 end
544
545 -- Teleports player <name> next to player <target_name> if possible
546 local function teleport_to_player(name, target_name)
547         if name == target_name then
548                 return false, S("One does not teleport to oneself.")
549         end
550         local teleportee = core.get_player_by_name(name)
551         if not teleportee then
552                 return false, S("Cannot get teleportee with name @1.", name)
553         end
554         if teleportee:get_attach() then
555                 return false, S("Cannot teleport, @1 " ..
556                         "is attached to an object!", name)
557         end
558         local target = core.get_player_by_name(target_name)
559         if not target then
560                 return false, S("Cannot get target player with name @1.", target_name)
561         end
562         local p = find_free_position_near(target:get_pos())
563         teleportee:set_pos(p)
564         return true, S("Teleporting @1 to @2 at @3.", name, target_name,
565                 core.pos_to_string(p, 1))
566 end
567
568 core.register_chatcommand("teleport", {
569         params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
570         description = S("Teleport to position or player"),
571         privs = {teleport=true},
572         func = function(name, param)
573                 local p = {}
574                 p.x, p.y, p.z = param:match("^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
575                 p = vector.apply(p, tonumber)
576                 if p.x and p.y and p.z then
577                         return teleport_to_pos(name, p)
578                 end
579
580                 local target_name = param:match("^([^ ]+)$")
581                 if target_name then
582                         return teleport_to_player(name, target_name)
583                 end
584
585                 local has_bring_priv = core.check_player_privs(name, {bring=true})
586                 local missing_bring_msg = S("You don't have permission to teleport " ..
587                         "other players (missing privilege: @1).", "bring")
588
589                 local teleportee_name
590                 teleportee_name, p.x, p.y, p.z = param:match(
591                                 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
592                 p = vector.apply(p, tonumber)
593                 if teleportee_name and p.x and p.y and p.z then
594                         if not has_bring_priv then
595                                 return false, missing_bring_msg
596                         end
597                         return teleport_to_pos(teleportee_name, p)
598                 end
599
600                 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
601                 if teleportee_name and target_name then
602                         if not has_bring_priv then
603                                 return false, missing_bring_msg
604                         end
605                         return teleport_to_player(teleportee_name, target_name)
606                 end
607
608                 return false
609         end,
610 })
611
612 core.register_chatcommand("set", {
613         params = S("([-n] <name> <value>) | <name>"),
614         description = S("Set or read server configuration setting"),
615         privs = {server=true},
616         func = function(name, param)
617                 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
618                 if arg and arg == "-n" and setname and setvalue then
619                         core.settings:set(setname, setvalue)
620                         return true, setname .. " = " .. setvalue
621                 end
622
623                 setname, setvalue = string.match(param, "([^ ]+) (.+)")
624                 if setname and setvalue then
625                         if setname:sub(1, 7) == "secure." then
626                                 return false, S("Failed. Cannot modify secure settings. "
627                                         .. "Edit the settings file manually.")
628                         end
629                         if not core.settings:get(setname) then
630                                 return false, S("Failed. Use '/set -n <name> <value>' "
631                                         .. "to create a new setting.")
632                         end
633                         core.settings:set(setname, setvalue)
634                         return true, S("@1 = @2", setname, setvalue)
635                 end
636
637                 setname = string.match(param, "([^ ]+)")
638                 if setname then
639                         setvalue = core.settings:get(setname)
640                         if not setvalue then
641                                 setvalue = S("<not set>")
642                         end
643                         return true, S("@1 = @2", setname, setvalue)
644                 end
645
646                 return false, S("Invalid parameters (see /help set).")
647         end,
648 })
649
650 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
651         if ctx.total_blocks == 0 then
652                 ctx.total_blocks   = num_calls_remaining + 1
653                 ctx.current_blocks = 0
654         end
655         ctx.current_blocks = ctx.current_blocks + 1
656
657         if ctx.current_blocks == ctx.total_blocks then
658                 core.chat_send_player(ctx.requestor_name,
659                         S("Finished emerging @1 blocks in @2ms.",
660                                 ctx.total_blocks,
661                                 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
662         end
663 end
664
665 local function emergeblocks_progress_update(ctx)
666         if ctx.current_blocks ~= ctx.total_blocks then
667                 core.chat_send_player(ctx.requestor_name,
668                         S("emergeblocks update: @1/@2 blocks emerged (@3%)",
669                         ctx.current_blocks, ctx.total_blocks,
670                         string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
671
672                 core.after(2, emergeblocks_progress_update, ctx)
673         end
674 end
675
676 core.register_chatcommand("emergeblocks", {
677         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
678         description = S("Load (or, if nonexistent, generate) map blocks contained in "
679                 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
680         privs = {server=true},
681         func = function(name, param)
682                 local p1, p2 = parse_range_str(name, param)
683                 if p1 == false then
684                         return false, p2
685                 end
686
687                 local context = {
688                         current_blocks = 0,
689                         total_blocks   = 0,
690                         start_time     = os.clock(),
691                         requestor_name = name
692                 }
693
694                 core.emerge_area(p1, p2, emergeblocks_callback, context)
695                 core.after(2, emergeblocks_progress_update, context)
696
697                 return true, S("Started emerge of area ranging from @1 to @2.",
698                         core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
699         end,
700 })
701
702 core.register_chatcommand("deleteblocks", {
703         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
704         description = S("Delete map blocks contained in area pos1 to pos2 "
705                 .. "(<pos1> and <pos2> must be in parentheses)"),
706         privs = {server=true},
707         func = function(name, param)
708                 local p1, p2 = parse_range_str(name, param)
709                 if p1 == false then
710                         return false, p2
711                 end
712
713                 if core.delete_area(p1, p2) then
714                         return true, S("Successfully cleared area "
715                                 .. "ranging from @1 to @2.",
716                                 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
717                 else
718                         return false, S("Failed to clear one or more "
719                                 .. "blocks in area.")
720                 end
721         end,
722 })
723
724 core.register_chatcommand("fixlight", {
725         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
726         description = S("Resets lighting in the area between pos1 and pos2 "
727                 .. "(<pos1> and <pos2> must be in parentheses)"),
728         privs = {server = true},
729         func = function(name, param)
730                 local p1, p2 = parse_range_str(name, param)
731                 if p1 == false then
732                         return false, p2
733                 end
734
735                 if core.fix_light(p1, p2) then
736                         return true, S("Successfully reset light in the area "
737                                 .. "ranging from @1 to @2.",
738                                 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
739                 else
740                         return false, S("Failed to load one or more blocks in area.")
741                 end
742         end,
743 })
744
745 core.register_chatcommand("mods", {
746         params = "",
747         description = S("List mods installed on the server"),
748         privs = {},
749         func = function(name, param)
750                 local mods = core.get_modnames()
751                 if #mods == 0 then
752                         return true, S("No mods installed.")
753                 else
754                         return true, table.concat(core.get_modnames(), ", ")
755                 end
756         end,
757 })
758
759 local function handle_give_command(cmd, giver, receiver, stackstring)
760         core.log("action", giver .. " invoked " .. cmd
761                         .. ', stackstring="' .. stackstring .. '"')
762         local itemstack = ItemStack(stackstring)
763         if itemstack:is_empty() then
764                 return false, S("Cannot give an empty item.")
765         elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
766                 return false, S("Cannot give an unknown item.")
767         -- Forbid giving 'ignore' due to unwanted side effects
768         elseif itemstack:get_name() == "ignore" then
769                 return false, S("Giving 'ignore' is not allowed.")
770         end
771         local receiverref = core.get_player_by_name(receiver)
772         if receiverref == nil then
773                 return false, S("@1 is not a known player.", receiver)
774         end
775         local leftover = receiverref:get_inventory():add_item("main", itemstack)
776         local partiality
777         if leftover:is_empty() then
778                 partiality = nil
779         elseif leftover:get_count() == itemstack:get_count() then
780                 partiality = false
781         else
782                 partiality = true
783         end
784         -- The actual item stack string may be different from what the "giver"
785         -- entered (e.g. big numbers are always interpreted as 2^16-1).
786         stackstring = itemstack:to_string()
787         local msg
788         if partiality == true then
789                 msg = S("@1 partially added to inventory.", stackstring)
790         elseif partiality == false then
791                 msg = S("@1 could not be added to inventory.", stackstring)
792         else
793                 msg = S("@1 added to inventory.", stackstring)
794         end
795         if giver == receiver then
796                 return true, msg
797         else
798                 core.chat_send_player(receiver, msg)
799                 local msg_other
800                 if partiality == true then
801                         msg_other = S("@1 partially added to inventory of @2.",
802                                         stackstring, receiver)
803                 elseif partiality == false then
804                         msg_other = S("@1 could not be added to inventory of @2.",
805                                         stackstring, receiver)
806                 else
807                         msg_other = S("@1 added to inventory of @2.",
808                                         stackstring, receiver)
809                 end
810                 return true, msg_other
811         end
812 end
813
814 core.register_chatcommand("give", {
815         params = S("<name> <ItemString> [<count> [<wear>]]"),
816         description = S("Give item to player"),
817         privs = {give=true},
818         func = function(name, param)
819                 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
820                 if not toname or not itemstring then
821                         return false, S("Name and ItemString required.")
822                 end
823                 return handle_give_command("/give", name, toname, itemstring)
824         end,
825 })
826
827 core.register_chatcommand("giveme", {
828         params = S("<ItemString> [<count> [<wear>]]"),
829         description = S("Give item to yourself"),
830         privs = {give=true},
831         func = function(name, param)
832                 local itemstring = string.match(param, "(.+)$")
833                 if not itemstring then
834                         return false, S("ItemString required.")
835                 end
836                 return handle_give_command("/giveme", name, name, itemstring)
837         end,
838 })
839
840 core.register_chatcommand("spawnentity", {
841         params = S("<EntityName> [<X>,<Y>,<Z>]"),
842         description = S("Spawn entity at given (or your) position"),
843         privs = {give=true, interact=true},
844         func = function(name, param)
845                 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
846                 if not entityname then
847                         return false, S("EntityName required.")
848                 end
849                 core.log("action", ("%s invokes /spawnentity, entityname=%q")
850                                 :format(name, entityname))
851                 local player = core.get_player_by_name(name)
852                 if player == nil then
853                         core.log("error", "Unable to spawn entity, player is nil")
854                         return false, S("Unable to spawn entity, player is nil.")
855                 end
856                 if not core.registered_entities[entityname] then
857                         return false, S("Cannot spawn an unknown entity.")
858                 end
859                 if p == "" then
860                         p = player:get_pos()
861                 else
862                         p = core.string_to_pos(p)
863                         if p == nil then
864                                 return false, S("Invalid parameters (@1).", param)
865                         end
866                 end
867                 p.y = p.y + 1
868                 local obj = core.add_entity(p, entityname)
869                 if obj then
870                         return true, S("@1 spawned.", entityname)
871                 else
872                         return true, S("@1 failed to spawn.", entityname)
873                 end
874         end,
875 })
876
877 core.register_chatcommand("pulverize", {
878         params = "",
879         description = S("Destroy item in hand"),
880         func = function(name, param)
881                 local player = core.get_player_by_name(name)
882                 if not player then
883                         core.log("error", "Unable to pulverize, no player.")
884                         return false, S("Unable to pulverize, no player.")
885                 end
886                 local wielded_item = player:get_wielded_item()
887                 if wielded_item:is_empty() then
888                         return false, S("Unable to pulverize, no item in hand.")
889                 end
890                 core.log("action", name .. " pulverized \"" ..
891                         wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
892                 player:set_wielded_item(nil)
893                 return true, S("An item was pulverized.")
894         end,
895 })
896
897 -- Key = player name
898 core.rollback_punch_callbacks = {}
899
900 core.register_on_punchnode(function(pos, node, puncher)
901         local name = puncher and puncher:get_player_name()
902         if name and core.rollback_punch_callbacks[name] then
903                 core.rollback_punch_callbacks[name](pos, node, puncher)
904                 core.rollback_punch_callbacks[name] = nil
905         end
906 end)
907
908 core.register_chatcommand("rollback_check", {
909         params = S("[<range>] [<seconds>] [<limit>]"),
910         description = S("Check who last touched a node or a node near it "
911                 .. "within the time specified by <seconds>. "
912                 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
913                 .. "Set <seconds> to inf for no time limit"),
914         privs = {rollback=true},
915         func = function(name, param)
916                 if not core.settings:get_bool("enable_rollback_recording") then
917                         return false, S("Rollback functions are disabled.")
918                 end
919                 local range, seconds, limit =
920                         param:match("(%d+) *(%d*) *(%d*)")
921                 range = tonumber(range) or 0
922                 seconds = tonumber(seconds) or 86400
923                 limit = tonumber(limit) or 5
924                 if limit > 100 then
925                         return false, S("That limit is too high!")
926                 end
927
928                 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
929                         local name = puncher:get_player_name()
930                         core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
931                         local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
932                         if not actions then
933                                 core.chat_send_player(name, S("Rollback functions are disabled."))
934                                 return
935                         end
936                         local num_actions = #actions
937                         if num_actions == 0 then
938                                 core.chat_send_player(name,
939                                                 S("Nobody has touched the specified "
940                                                 .. "location in @1 seconds.",
941                                                 seconds))
942                                 return
943                         end
944                         local time = os.time()
945                         for i = num_actions, 1, -1 do
946                                 local action = actions[i]
947                                 core.chat_send_player(name,
948                                         S("@1 @2 @3 -> @4 @5 seconds ago.",
949                                                         core.pos_to_string(action.pos),
950                                                         action.actor,
951                                                         action.oldnode.name,
952                                                         action.newnode.name,
953                                                         time - action.time))
954                         end
955                 end
956
957                 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
958                                 range, seconds, limit)
959         end,
960 })
961
962 core.register_chatcommand("rollback", {
963         params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
964         description = S("Revert actions of a player. "
965                 .. "Default for <seconds> is 60. "
966                 .. "Set <seconds> to inf for no time limit"),
967         privs = {rollback=true},
968         func = function(name, param)
969                 if not core.settings:get_bool("enable_rollback_recording") then
970                         return false, S("Rollback functions are disabled.")
971                 end
972                 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
973                 local rev_msg
974                 if not target_name then
975                         local player_name
976                         player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
977                         if not player_name then
978                                 return false, S("Invalid parameters. "
979                                         .. "See /help rollback and "
980                                         .. "/help rollback_check.")
981                         end
982                         seconds = tonumber(seconds) or 60
983                         target_name = "player:"..player_name
984                         rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
985                                 player_name, seconds)
986                 else
987                         seconds = tonumber(seconds) or 60
988                         rev_msg = S("Reverting actions of @1 since @2 seconds.",
989                                 target_name, seconds)
990                 end
991                 core.chat_send_player(name, rev_msg)
992                 local success, log = core.rollback_revert_actions_by(
993                                 target_name, seconds)
994                 local response = ""
995                 if #log > 100 then
996                         response = S("(log is too long to show)").."\n"
997                 else
998                         for _, line in pairs(log) do
999                                 response = response .. line .. "\n"
1000                         end
1001                 end
1002                 if success then
1003                         response = response .. S("Reverting actions succeeded.")
1004                 else
1005                         response = response .. S("Reverting actions FAILED.")
1006                 end
1007                 return success, response
1008         end,
1009 })
1010
1011 core.register_chatcommand("status", {
1012         description = S("Show server status"),
1013         func = function(name, param)
1014                 local status = core.get_server_status(name, false)
1015                 if status and status ~= "" then
1016                         return true, status
1017                 end
1018                 return false, S("This command was disabled by a mod or game.")
1019         end,
1020 })
1021
1022 core.register_chatcommand("time", {
1023         params = S("[<0..23>:<0..59> | <0..24000>]"),
1024         description = S("Show or set time of day"),
1025         privs = {},
1026         func = function(name, param)
1027                 if param == "" then
1028                         local current_time = math.floor(core.get_timeofday() * 1440)
1029                         local minutes = current_time % 60
1030                         local hour = (current_time - minutes) / 60
1031                         return true, S("Current time is @1:@2.",
1032                                         string.format("%d", hour),
1033                                         string.format("%02d", minutes))
1034                 end
1035                 local player_privs = core.get_player_privs(name)
1036                 if not player_privs.settime then
1037                         return false, S("You don't have permission to run "
1038                                 .. "this command (missing privilege: @1).", "settime")
1039                 end
1040                 local hour, minute = param:match("^(%d+):(%d+)$")
1041                 if not hour then
1042                         local new_time = tonumber(param) or -1
1043                         if new_time ~= new_time or new_time < 0 or new_time > 24000 then
1044                                 return false, S("Invalid time (must be between 0 and 24000).")
1045                         end
1046                         core.set_timeofday(new_time / 24000)
1047                         core.log("action", name .. " sets time to " .. new_time)
1048                         return true, S("Time of day changed.")
1049                 end
1050                 hour = tonumber(hour)
1051                 minute = tonumber(minute)
1052                 if hour < 0 or hour > 23 then
1053                         return false, S("Invalid hour (must be between 0 and 23 inclusive).")
1054                 elseif minute < 0 or minute > 59 then
1055                         return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1056                 end
1057                 core.set_timeofday((hour * 60 + minute) / 1440)
1058                 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
1059                 return true, S("Time of day changed.")
1060         end,
1061 })
1062
1063 core.register_chatcommand("days", {
1064         description = S("Show day count since world creation"),
1065         func = function(name, param)
1066                 return true, S("Current day is @1.", core.get_day_count())
1067         end
1068 })
1069
1070 local function parse_shutdown_param(param)
1071         local delay, reconnect, message
1072         local one, two, three
1073         one, two, three = param:match("^(%S+) +(%-r) +(.*)")
1074         if one and two and three then
1075                 -- 3 arguments: delay, reconnect and message
1076                 return one, two, three
1077         end
1078         -- 2 arguments
1079         one, two = param:match("^(%S+) +(.*)")
1080         if one and two then
1081                 if tonumber(one) then
1082                         delay = one
1083                         if two == "-r" then
1084                                 reconnect = two
1085                         else
1086                                 message = two
1087                         end
1088                 elseif one == "-r" then
1089                         reconnect, message = one, two
1090                 end
1091                 return delay, reconnect, message
1092         end
1093         -- 1 argument
1094         one = param:match("(.*)")
1095         if tonumber(one) then
1096                 delay = one
1097         elseif one == "-r" then
1098                 reconnect = one
1099         else
1100                 message = one
1101         end
1102         return delay, reconnect, message
1103 end
1104
1105 core.register_chatcommand("shutdown", {
1106         params = S("[<delay_in_seconds> | -1] [-r] [<message>]"),
1107         description = S("Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)"),
1108         privs = {server=true},
1109         func = function(name, param)
1110                 local delay, reconnect, message = parse_shutdown_param(param)
1111                 local bool_reconnect = reconnect == "-r"
1112                 if not message then
1113                         message = ""
1114                 end
1115                 delay = tonumber(delay) or 0
1116
1117                 if delay == 0 then
1118                         core.log("action", name .. " shuts down server")
1119                         core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1120                 end
1121                 core.request_shutdown(message:trim(), bool_reconnect, delay)
1122                 return true
1123         end,
1124 })
1125
1126 core.register_chatcommand("ban", {
1127         params = S("[<name>]"),
1128         description = S("Ban the IP of a player or show the ban list"),
1129         privs = {ban=true},
1130         func = function(name, param)
1131                 if param == "" then
1132                         local ban_list = core.get_ban_list()
1133                         if ban_list == "" then
1134                                 return true, S("The ban list is empty.")
1135                         else
1136                                 return true, S("Ban list: @1", ban_list)
1137                         end
1138                 end
1139                 if not core.get_player_by_name(param) then
1140                         return false, S("Player is not online.")
1141                 end
1142                 if not core.ban_player(param) then
1143                         return false, S("Failed to ban player.")
1144                 end
1145                 local desc = core.get_ban_description(param)
1146                 core.log("action", name .. " bans " .. desc .. ".")
1147                 return true, S("Banned @1.", desc)
1148         end,
1149 })
1150
1151 core.register_chatcommand("unban", {
1152         params = S("<name> | <IP_address>"),
1153         description = S("Remove IP ban belonging to a player/IP"),
1154         privs = {ban=true},
1155         func = function(name, param)
1156                 if not core.unban_player_or_ip(param) then
1157                         return false, S("Failed to unban player/IP.")
1158                 end
1159                 core.log("action", name .. " unbans " .. param)
1160                 return true, S("Unbanned @1.", param)
1161         end,
1162 })
1163
1164 core.register_chatcommand("kick", {
1165         params = S("<name> [<reason>]"),
1166         description = S("Kick a player"),
1167         privs = {kick=true},
1168         func = function(name, param)
1169                 local tokick, reason = param:match("([^ ]+) (.+)")
1170                 tokick = tokick or param
1171                 if not core.kick_player(tokick, reason) then
1172                         return false, S("Failed to kick player @1.", tokick)
1173                 end
1174                 local log_reason = ""
1175                 if reason then
1176                         log_reason = " with reason \"" .. reason .. "\""
1177                 end
1178                 core.log("action", name .. " kicks " .. tokick .. log_reason)
1179                 return true, S("Kicked @1.", tokick)
1180         end,
1181 })
1182
1183 core.register_chatcommand("clearobjects", {
1184         params = S("[full | quick]"),
1185         description = S("Clear all objects in world"),
1186         privs = {server=true},
1187         func = function(name, param)
1188                 local options = {}
1189                 if param == "" or param == "quick" then
1190                         options.mode = "quick"
1191                 elseif param == "full" then
1192                         options.mode = "full"
1193                 else
1194                         return false, S("Invalid usage, see /help clearobjects.")
1195                 end
1196
1197                 core.log("action", name .. " clears objects ("
1198                                 .. options.mode .. " mode).")
1199                 if options.mode == "full" then
1200                         core.chat_send_all(S("Clearing all objects. This may take a long time. "
1201                                 .. "You may experience a timeout. (by @1)", name))
1202                 end
1203                 core.clear_objects(options)
1204                 core.log("action", "Object clearing done.")
1205                 core.chat_send_all("*** "..S("Cleared all objects."))
1206                 return true
1207         end,
1208 })
1209
1210 core.register_chatcommand("msg", {
1211         params = S("<name> <message>"),
1212         description = S("Send a direct message to a player"),
1213         privs = {shout=true},
1214         func = function(name, param)
1215                 local sendto, message = param:match("^(%S+)%s(.+)$")
1216                 if not sendto then
1217                         return false, S("Invalid usage, see /help msg.")
1218                 end
1219                 if not core.get_player_by_name(sendto) then
1220                         return false, S("The player @1 is not online.", sendto)
1221                 end
1222                 core.log("action", "DM from " .. name .. " to " .. sendto
1223                                 .. ": " .. message)
1224                 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1225                 return true, S("Message sent.")
1226         end,
1227 })
1228
1229 core.register_chatcommand("last-login", {
1230         params = S("[<name>]"),
1231         description = S("Get the last login time of a player or yourself"),
1232         func = function(name, param)
1233                 if param == "" then
1234                         param = name
1235                 end
1236                 local pauth = core.get_auth_handler().get_auth(param)
1237                 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1238                         -- Time in UTC, ISO 8601 format
1239                         return true, S("@1's last login time was @2.",
1240                                 param,
1241                                 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1242                 end
1243                 return false, S("@1's last login time is unknown.", param)
1244         end,
1245 })
1246
1247 core.register_chatcommand("clearinv", {
1248         params = S("[<name>]"),
1249         description = S("Clear the inventory of yourself or another player"),
1250         func = function(name, param)
1251                 local player
1252                 if param and param ~= "" and param ~= name then
1253                         if not core.check_player_privs(name, {server=true}) then
1254                                 return false, S("You don't have permission to "
1255                                         .. "clear another player's inventory "
1256                                         .. "(missing privilege: @1).", "server")
1257                         end
1258                         player = core.get_player_by_name(param)
1259                         core.chat_send_player(param, S("@1 cleared your inventory.", name))
1260                 else
1261                         player = core.get_player_by_name(name)
1262                 end
1263
1264                 if player then
1265                         player:get_inventory():set_list("main", {})
1266                         player:get_inventory():set_list("craft", {})
1267                         player:get_inventory():set_list("craftpreview", {})
1268                         core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1269                         return true, S("Cleared @1's inventory.", player:get_player_name())
1270                 else
1271                         return false, S("Player must be online to clear inventory!")
1272                 end
1273         end,
1274 })
1275
1276 local function handle_kill_command(killer, victim)
1277         if core.settings:get_bool("enable_damage") == false then
1278                 return false, S("Players can't be killed, damage has been disabled.")
1279         end
1280         local victimref = core.get_player_by_name(victim)
1281         if victimref == nil then
1282                 return false, S("Player @1 is not online.", victim)
1283         elseif victimref:get_hp() <= 0 then
1284                 if killer == victim then
1285                         return false, S("You are already dead.")
1286                 else
1287                         return false, S("@1 is already dead.", victim)
1288                 end
1289         end
1290         if killer ~= victim then
1291                 core.log("action", string.format("%s killed %s", killer, victim))
1292         end
1293         -- Kill victim
1294         victimref:set_hp(0)
1295         return true, S("@1 has been killed.", victim)
1296 end
1297
1298 core.register_chatcommand("kill", {
1299         params = S("[<name>]"),
1300         description = S("Kill player or yourself"),
1301         privs = {server=true},
1302         func = function(name, param)
1303                 return handle_kill_command(name, param == "" and name or param)
1304         end,
1305 })