]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/game/chat.lua
Put torch/signlike node on floor if no paramtype2 (#11074)
[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                 return true, S("Players online with the \"@1\" privilege: @2",
216                                 param,
217                                 table.concat(players_with_priv, ", "))
218         end
219 })
220
221 local function handle_grant_command(caller, grantname, grantprivstr)
222         local caller_privs = core.get_player_privs(caller)
223         if not (caller_privs.privs or caller_privs.basic_privs) then
224                 return false, S("Your privileges are insufficient.")
225         end
226
227         if not core.get_auth_handler().get_auth(grantname) then
228                 return false, S("Player @1 does not exist.", grantname)
229         end
230         local grantprivs = core.string_to_privs(grantprivstr)
231         if grantprivstr == "all" then
232                 grantprivs = core.registered_privileges
233         end
234         local privs = core.get_player_privs(grantname)
235         local privs_unknown = ""
236         local basic_privs =
237                 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
238         for priv, _ in pairs(grantprivs) do
239                 if not basic_privs[priv] and not caller_privs.privs then
240                         return false, S("Your privileges are insufficient. "..
241                                         "'@1' only allows you to grant: @2",
242                                         "basic_privs",
243                                         core.privs_to_string(basic_privs, ', '))
244                 end
245                 if not core.registered_privileges[priv] then
246                         privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
247                 end
248                 privs[priv] = true
249         end
250         if privs_unknown ~= "" then
251                 return false, privs_unknown
252         end
253         for priv, _ in pairs(grantprivs) do
254                 -- call the on_grant callbacks
255                 core.run_priv_callbacks(grantname, priv, caller, "grant")
256         end
257         core.set_player_privs(grantname, privs)
258         core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
259         if grantname ~= caller then
260                 core.chat_send_player(grantname,
261                                 S("@1 granted you privileges: @2", caller,
262                                 core.privs_to_string(grantprivs, ', ')))
263         end
264         return true, privileges_of(grantname)
265 end
266
267 core.register_chatcommand("grant", {
268         params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
269         description = S("Give privileges to player"),
270         func = function(name, param)
271                 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
272                 if not grantname or not grantprivstr then
273                         return false, S("Invalid parameters (see /help grant).")
274                 end
275                 return handle_grant_command(name, grantname, grantprivstr)
276         end,
277 })
278
279 core.register_chatcommand("grantme", {
280         params = S("<privilege> [, <privilege2> [<...>]] | all"),
281         description = S("Grant privileges to yourself"),
282         func = function(name, param)
283                 if param == "" then
284                         return false, S("Invalid parameters (see /help grantme).")
285                 end
286                 return handle_grant_command(name, name, param)
287         end,
288 })
289
290 local function handle_revoke_command(caller, revokename, revokeprivstr)
291         local caller_privs = core.get_player_privs(caller)
292         if not (caller_privs.privs or caller_privs.basic_privs) then
293                 return false, S("Your privileges are insufficient.")
294         end
295
296         if not core.get_auth_handler().get_auth(revokename) then
297                 return false, S("Player @1 does not exist.", revokename)
298         end
299
300         local privs = core.get_player_privs(revokename)
301
302         local revokeprivs = core.string_to_privs(revokeprivstr)
303         local is_singleplayer = core.is_singleplayer()
304         local is_admin = not is_singleplayer
305                         and revokename == core.settings:get("name")
306                         and revokename ~= ""
307         if revokeprivstr == "all" then
308                 revokeprivs = privs
309                 privs = {}
310         else
311                 for priv, _ in pairs(revokeprivs) do
312                         privs[priv] = nil
313                 end
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                         privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
331                 elseif is_singleplayer and def.give_to_singleplayer then
332                         irrevokable[priv] = true
333                 elseif is_admin and def.give_to_admin then
334                         irrevokable[priv] = true
335                 end
336         end
337         for priv, _ in pairs(irrevokable) do
338                 revokeprivs[priv] = nil
339                 has_irrevokable_priv = true
340         end
341         if privs_unknown ~= "" then
342                 return false, privs_unknown
343         end
344         if has_irrevokable_priv then
345                 if is_singleplayer then
346                         core.chat_send_player(caller,
347                                         S("Note: Cannot revoke in singleplayer: @1",
348                                         core.privs_to_string(irrevokable, ', ')))
349                 elseif is_admin then
350                         core.chat_send_player(caller,
351                                         S("Note: Cannot revoke from admin: @1",
352                                         core.privs_to_string(irrevokable, ', ')))
353                 end
354         end
355
356         local revokecount = 0
357         for priv, _ in pairs(revokeprivs) do
358                 -- call the on_revoke callbacks
359                 core.run_priv_callbacks(revokename, priv, caller, "revoke")
360                 revokecount = revokecount + 1
361         end
362
363         core.set_player_privs(revokename, privs)
364         local new_privs = core.get_player_privs(revokename)
365
366         if revokecount == 0 then
367                 return false, S("No privileges were revoked.")
368         end
369
370         core.log("action", caller..' revoked ('
371                         ..core.privs_to_string(revokeprivs, ', ')
372                         ..') privileges from '..revokename)
373         if revokename ~= caller then
374                 core.chat_send_player(revokename,
375                         S("@1 revoked privileges from you: @2", caller,
376                         core.privs_to_string(revokeprivs, ', ')))
377         end
378         return true, privileges_of(revokename, new_privs)
379 end
380
381 core.register_chatcommand("revoke", {
382         params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
383         description = S("Remove privileges from player"),
384         privs = {},
385         func = function(name, param)
386                 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
387                 if not revokename or not revokeprivstr then
388                         return false, S("Invalid parameters (see /help revoke).")
389                 end
390                 return handle_revoke_command(name, revokename, revokeprivstr)
391         end,
392 })
393
394 core.register_chatcommand("revokeme", {
395         params = S("<privilege> [, <privilege2> [<...>]] | all"),
396         description = S("Revoke privileges from yourself"),
397         privs = {},
398         func = function(name, param)
399                 if param == "" then
400                         return false, S("Invalid parameters (see /help revokeme).")
401                 end
402                 return handle_revoke_command(name, name, param)
403         end,
404 })
405
406 core.register_chatcommand("setpassword", {
407         params = S("<name> <password>"),
408         description = S("Set player's password"),
409         privs = {password=true},
410         func = function(name, param)
411                 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
412                 if not toname then
413                         toname = param:match("^([^ ]+) *$")
414                         raw_password = nil
415                 end
416
417                 if not toname then
418                         return false, S("Name field required.")
419                 end
420
421                 local msg_chat, msg_log, msg_ret
422                 if not raw_password then
423                         core.set_player_password(toname, "")
424                         msg_chat = S("Your password was cleared by @1.", name)
425                         msg_log = name .. " clears password of " .. toname .. "."
426                         msg_ret = S("Password of player \"@1\" cleared.", toname)
427                 else
428                         core.set_player_password(toname,
429                                         core.get_password_hash(toname,
430                                                         raw_password))
431                         msg_chat = S("Your password was set by @1.", name)
432                         msg_log = name .. " sets password of " .. toname .. "."
433                         msg_ret = S("Password of player \"@1\" set.", toname)
434                 end
435
436                 if toname ~= name then
437                         core.chat_send_player(toname, msg_chat)
438                 end
439
440                 core.log("action", msg_log)
441
442                 return true, msg_ret
443         end,
444 })
445
446 core.register_chatcommand("clearpassword", {
447         params = S("<name>"),
448         description = S("Set empty password for a player"),
449         privs = {password=true},
450         func = function(name, param)
451                 local toname = param
452                 if toname == "" then
453                         return false, S("Name field required.")
454                 end
455                 core.set_player_password(toname, '')
456
457                 core.log("action", name .. " clears password of " .. toname .. ".")
458
459                 return true, S("Password of player \"@1\" cleared.", toname)
460         end,
461 })
462
463 core.register_chatcommand("auth_reload", {
464         params = "",
465         description = S("Reload authentication data"),
466         privs = {server=true},
467         func = function(name, param)
468                 local done = core.auth_reload()
469                 return done, (done and S("Done.") or S("Failed."))
470         end,
471 })
472
473 core.register_chatcommand("remove_player", {
474         params = S("<name>"),
475         description = S("Remove a player's data"),
476         privs = {server=true},
477         func = function(name, param)
478                 local toname = param
479                 if toname == "" then
480                         return false, S("Name field required.")
481                 end
482
483                 local rc = core.remove_player(toname)
484
485                 if rc == 0 then
486                         core.log("action", name .. " removed player data of " .. toname .. ".")
487                         return true, S("Player \"@1\" removed.", toname)
488                 elseif rc == 1 then
489                         return true, S("No such player \"@1\" to remove.", toname)
490                 elseif rc == 2 then
491                         return true, S("Player \"@1\" is connected, cannot remove.", toname)
492                 end
493
494                 return false, S("Unhandled remove_player return code @1.", tostring(rc))
495         end,
496 })
497
498
499 -- pos may be a non-integer position
500 local function find_free_position_near(pos)
501         local tries = {
502                 {x=1, y=0, z=0},
503                 {x=-1, y=0, z=0},
504                 {x=0, y=0, z=1},
505                 {x=0, y=0, z=-1},
506         }
507         for _, d in ipairs(tries) do
508                 local p = vector.add(pos, d)
509                 local n = core.get_node_or_nil(p)
510                 if n then
511                         local def = core.registered_nodes[n.name]
512                         if def and not def.walkable then
513                                 return p
514                         end
515                 end
516         end
517         return pos
518 end
519
520 -- Teleports player <name> to <p> if possible
521 local function teleport_to_pos(name, p)
522         local lm = 31000
523         if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
524                         or p.z < -lm or p.z > lm then
525                 return false, S("Cannot teleport out of map bounds!")
526         end
527         local teleportee = core.get_player_by_name(name)
528         if not teleportee then
529                 return false, S("Cannot get player with name @1.", name)
530         end
531         if teleportee:get_attach() then
532                 return false, S("Cannot teleport, @1 " ..
533                         "is attached to an object!", name)
534         end
535         teleportee:set_pos(p)
536         return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
537 end
538
539 -- Teleports player <name> next to player <target_name> if possible
540 local function teleport_to_player(name, target_name)
541         if name == target_name then
542                 return false, S("One does not teleport to oneself.")
543         end
544         local teleportee = core.get_player_by_name(name)
545         if not teleportee then
546                 return false, S("Cannot get teleportee with name @1.", name)
547         end
548         if teleportee:get_attach() then
549                 return false, S("Cannot teleport, @1 " ..
550                         "is attached to an object!", name)
551         end
552         local target = core.get_player_by_name(target_name)
553         if not target then
554                 return false, S("Cannot get target player with name @1.", target_name)
555         end
556         local p = find_free_position_near(target:get_pos())
557         teleportee:set_pos(p)
558         return true, S("Teleporting @1 to @2 at @3.", name, target_name,
559                 core.pos_to_string(p, 1))
560 end
561
562 core.register_chatcommand("teleport", {
563         params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
564         description = S("Teleport to position or player"),
565         privs = {teleport=true},
566         func = function(name, param)
567                 local p = {}
568                 p.x, p.y, p.z = param:match("^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
569                 p = vector.apply(p, tonumber)
570                 if p.x and p.y and p.z then
571                         return teleport_to_pos(name, p)
572                 end
573
574                 local target_name = param:match("^([^ ]+)$")
575                 if target_name then
576                         return teleport_to_player(name, target_name)
577                 end
578
579                 local has_bring_priv = core.check_player_privs(name, {bring=true})
580                 local missing_bring_msg = S("You don't have permission to teleport " ..
581                         "other players (missing privilege: @1).", "bring")
582
583                 local teleportee_name
584                 teleportee_name, p.x, p.y, p.z = param:match(
585                                 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
586                 p = vector.apply(p, tonumber)
587                 if teleportee_name and p.x and p.y and p.z then
588                         if not has_bring_priv then
589                                 return false, missing_bring_msg
590                         end
591                         return teleport_to_pos(teleportee_name, p)
592                 end
593
594                 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
595                 if teleportee_name and target_name then
596                         if not has_bring_priv then
597                                 return false, missing_bring_msg
598                         end
599                         return teleport_to_player(teleportee_name, target_name)
600                 end
601
602                 return false
603         end,
604 })
605
606 core.register_chatcommand("set", {
607         params = S("([-n] <name> <value>) | <name>"),
608         description = S("Set or read server configuration setting"),
609         privs = {server=true},
610         func = function(name, param)
611                 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
612                 if arg and arg == "-n" and setname and setvalue then
613                         core.settings:set(setname, setvalue)
614                         return true, setname .. " = " .. setvalue
615                 end
616
617                 setname, setvalue = string.match(param, "([^ ]+) (.+)")
618                 if setname and setvalue then
619                         if not core.settings:get(setname) then
620                                 return false, S("Failed. Use '/set -n <name> <value>' "
621                                         .. "to create a new setting.")
622                         end
623                         core.settings:set(setname, setvalue)
624                         return true, S("@1 = @2", setname, setvalue)
625                 end
626
627                 setname = string.match(param, "([^ ]+)")
628                 if setname then
629                         setvalue = core.settings:get(setname)
630                         if not setvalue then
631                                 setvalue = S("<not set>")
632                         end
633                         return true, S("@1 = @2", setname, setvalue)
634                 end
635
636                 return false, S("Invalid parameters (see /help set).")
637         end,
638 })
639
640 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
641         if ctx.total_blocks == 0 then
642                 ctx.total_blocks   = num_calls_remaining + 1
643                 ctx.current_blocks = 0
644         end
645         ctx.current_blocks = ctx.current_blocks + 1
646
647         if ctx.current_blocks == ctx.total_blocks then
648                 core.chat_send_player(ctx.requestor_name,
649                         S("Finished emerging @1 blocks in @2ms.",
650                                 ctx.total_blocks,
651                                 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
652         end
653 end
654
655 local function emergeblocks_progress_update(ctx)
656         if ctx.current_blocks ~= ctx.total_blocks then
657                 core.chat_send_player(ctx.requestor_name,
658                         S("emergeblocks update: @1/@2 blocks emerged (@3%)",
659                         ctx.current_blocks, ctx.total_blocks,
660                         string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
661
662                 core.after(2, emergeblocks_progress_update, ctx)
663         end
664 end
665
666 core.register_chatcommand("emergeblocks", {
667         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
668         description = S("Load (or, if nonexistent, generate) map blocks contained in "
669                 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
670         privs = {server=true},
671         func = function(name, param)
672                 local p1, p2 = parse_range_str(name, param)
673                 if p1 == false then
674                         return false, p2
675                 end
676
677                 local context = {
678                         current_blocks = 0,
679                         total_blocks   = 0,
680                         start_time     = os.clock(),
681                         requestor_name = name
682                 }
683
684                 core.emerge_area(p1, p2, emergeblocks_callback, context)
685                 core.after(2, emergeblocks_progress_update, context)
686
687                 return true, S("Started emerge of area ranging from @1 to @2.",
688                         core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
689         end,
690 })
691
692 core.register_chatcommand("deleteblocks", {
693         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
694         description = S("Delete map blocks contained in area pos1 to pos2 "
695                 .. "(<pos1> and <pos2> must be in parentheses)"),
696         privs = {server=true},
697         func = function(name, param)
698                 local p1, p2 = parse_range_str(name, param)
699                 if p1 == false then
700                         return false, p2
701                 end
702
703                 if core.delete_area(p1, p2) then
704                         return true, S("Successfully cleared area "
705                                 .. "ranging from @1 to @2.",
706                                 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
707                 else
708                         return false, S("Failed to clear one or more "
709                                 .. "blocks in area.")
710                 end
711         end,
712 })
713
714 core.register_chatcommand("fixlight", {
715         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
716         description = S("Resets lighting in the area between pos1 and pos2 "
717                 .. "(<pos1> and <pos2> must be in parentheses)"),
718         privs = {server = true},
719         func = function(name, param)
720                 local p1, p2 = parse_range_str(name, param)
721                 if p1 == false then
722                         return false, p2
723                 end
724
725                 if core.fix_light(p1, p2) then
726                         return true, S("Successfully reset light in the area "
727                                 .. "ranging from @1 to @2.",
728                                 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
729                 else
730                         return false, S("Failed to load one or more blocks in area.")
731                 end
732         end,
733 })
734
735 core.register_chatcommand("mods", {
736         params = "",
737         description = S("List mods installed on the server"),
738         privs = {},
739         func = function(name, param)
740                 return true, table.concat(core.get_modnames(), ", ")
741         end,
742 })
743
744 local function handle_give_command(cmd, giver, receiver, stackstring)
745         core.log("action", giver .. " invoked " .. cmd
746                         .. ', stackstring="' .. stackstring .. '"')
747         local itemstack = ItemStack(stackstring)
748         if itemstack:is_empty() then
749                 return false, S("Cannot give an empty item.")
750         elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
751                 return false, S("Cannot give an unknown item.")
752         -- Forbid giving 'ignore' due to unwanted side effects
753         elseif itemstack:get_name() == "ignore" then
754                 return false, S("Giving 'ignore' is not allowed.")
755         end
756         local receiverref = core.get_player_by_name(receiver)
757         if receiverref == nil then
758                 return false, S("@1 is not a known player.", receiver)
759         end
760         local leftover = receiverref:get_inventory():add_item("main", itemstack)
761         local partiality
762         if leftover:is_empty() then
763                 partiality = nil
764         elseif leftover:get_count() == itemstack:get_count() then
765                 partiality = false
766         else
767                 partiality = true
768         end
769         -- The actual item stack string may be different from what the "giver"
770         -- entered (e.g. big numbers are always interpreted as 2^16-1).
771         stackstring = itemstack:to_string()
772         local msg
773         if partiality == true then
774                 msg = S("@1 partially added to inventory.", stackstring)
775         elseif partiality == false then
776                 msg = S("@1 could not be added to inventory.", stackstring)
777         else
778                 msg = S("@1 added to inventory.", stackstring)
779         end
780         if giver == receiver then
781                 return true, msg
782         else
783                 core.chat_send_player(receiver, msg)
784                 local msg_other
785                 if partiality == true then
786                         msg_other = S("@1 partially added to inventory of @2.",
787                                         stackstring, receiver)
788                 elseif partiality == false then
789                         msg_other = S("@1 could not be added to inventory of @2.",
790                                         stackstring, receiver)
791                 else
792                         msg_other = S("@1 added to inventory of @2.",
793                                         stackstring, receiver)
794                 end
795                 return true, msg_other
796         end
797 end
798
799 core.register_chatcommand("give", {
800         params = S("<name> <ItemString> [<count> [<wear>]]"),
801         description = S("Give item to player"),
802         privs = {give=true},
803         func = function(name, param)
804                 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
805                 if not toname or not itemstring then
806                         return false, S("Name and ItemString required.")
807                 end
808                 return handle_give_command("/give", name, toname, itemstring)
809         end,
810 })
811
812 core.register_chatcommand("giveme", {
813         params = S("<ItemString> [<count> [<wear>]]"),
814         description = S("Give item to yourself"),
815         privs = {give=true},
816         func = function(name, param)
817                 local itemstring = string.match(param, "(.+)$")
818                 if not itemstring then
819                         return false, S("ItemString required.")
820                 end
821                 return handle_give_command("/giveme", name, name, itemstring)
822         end,
823 })
824
825 core.register_chatcommand("spawnentity", {
826         params = S("<EntityName> [<X>,<Y>,<Z>]"),
827         description = S("Spawn entity at given (or your) position"),
828         privs = {give=true, interact=true},
829         func = function(name, param)
830                 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
831                 if not entityname then
832                         return false, S("EntityName required.")
833                 end
834                 core.log("action", ("%s invokes /spawnentity, entityname=%q")
835                                 :format(name, entityname))
836                 local player = core.get_player_by_name(name)
837                 if player == nil then
838                         core.log("error", "Unable to spawn entity, player is nil")
839                         return false, S("Unable to spawn entity, player is nil.")
840                 end
841                 if not core.registered_entities[entityname] then
842                         return false, S("Cannot spawn an unknown entity.")
843                 end
844                 if p == "" then
845                         p = player:get_pos()
846                 else
847                         p = core.string_to_pos(p)
848                         if p == nil then
849                                 return false, S("Invalid parameters (@1).", param)
850                         end
851                 end
852                 p.y = p.y + 1
853                 local obj = core.add_entity(p, entityname)
854                 if obj then
855                         return true, S("@1 spawned.", entityname)
856                 else
857                         return true, S("@1 failed to spawn.", entityname)
858                 end
859         end,
860 })
861
862 core.register_chatcommand("pulverize", {
863         params = "",
864         description = S("Destroy item in hand"),
865         func = function(name, param)
866                 local player = core.get_player_by_name(name)
867                 if not player then
868                         core.log("error", "Unable to pulverize, no player.")
869                         return false, S("Unable to pulverize, no player.")
870                 end
871                 local wielded_item = player:get_wielded_item()
872                 if wielded_item:is_empty() then
873                         return false, S("Unable to pulverize, no item in hand.")
874                 end
875                 core.log("action", name .. " pulverized \"" ..
876                         wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
877                 player:set_wielded_item(nil)
878                 return true, S("An item was pulverized.")
879         end,
880 })
881
882 -- Key = player name
883 core.rollback_punch_callbacks = {}
884
885 core.register_on_punchnode(function(pos, node, puncher)
886         local name = puncher and puncher:get_player_name()
887         if name and core.rollback_punch_callbacks[name] then
888                 core.rollback_punch_callbacks[name](pos, node, puncher)
889                 core.rollback_punch_callbacks[name] = nil
890         end
891 end)
892
893 core.register_chatcommand("rollback_check", {
894         params = S("[<range>] [<seconds>] [<limit>]"),
895         description = S("Check who last touched a node or a node near it "
896                 .. "within the time specified by <seconds>. "
897                 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
898                 .. "Set <seconds> to inf for no time limit"),
899         privs = {rollback=true},
900         func = function(name, param)
901                 if not core.settings:get_bool("enable_rollback_recording") then
902                         return false, S("Rollback functions are disabled.")
903                 end
904                 local range, seconds, limit =
905                         param:match("(%d+) *(%d*) *(%d*)")
906                 range = tonumber(range) or 0
907                 seconds = tonumber(seconds) or 86400
908                 limit = tonumber(limit) or 5
909                 if limit > 100 then
910                         return false, S("That limit is too high!")
911                 end
912
913                 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
914                         local name = puncher:get_player_name()
915                         core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
916                         local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
917                         if not actions then
918                                 core.chat_send_player(name, S("Rollback functions are disabled."))
919                                 return
920                         end
921                         local num_actions = #actions
922                         if num_actions == 0 then
923                                 core.chat_send_player(name,
924                                                 S("Nobody has touched the specified "
925                                                 .. "location in @1 seconds.",
926                                                 seconds))
927                                 return
928                         end
929                         local time = os.time()
930                         for i = num_actions, 1, -1 do
931                                 local action = actions[i]
932                                 core.chat_send_player(name,
933                                         S("@1 @2 @3 -> @4 @5 seconds ago.",
934                                                         core.pos_to_string(action.pos),
935                                                         action.actor,
936                                                         action.oldnode.name,
937                                                         action.newnode.name,
938                                                         time - action.time))
939                         end
940                 end
941
942                 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
943                                 range, seconds, limit)
944         end,
945 })
946
947 core.register_chatcommand("rollback", {
948         params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
949         description = S("Revert actions of a player. "
950                 .. "Default for <seconds> is 60. "
951                 .. "Set <seconds> to inf for no time limit"),
952         privs = {rollback=true},
953         func = function(name, param)
954                 if not core.settings:get_bool("enable_rollback_recording") then
955                         return false, S("Rollback functions are disabled.")
956                 end
957                 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
958                 local rev_msg
959                 if not target_name then
960                         local player_name
961                         player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
962                         if not player_name then
963                                 return false, S("Invalid parameters. "
964                                         .. "See /help rollback and "
965                                         .. "/help rollback_check.")
966                         end
967                         seconds = tonumber(seconds) or 60
968                         target_name = "player:"..player_name
969                         rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
970                                 player_name, seconds)
971                 else
972                         seconds = tonumber(seconds) or 60
973                         rev_msg = S("Reverting actions of @1 since @2 seconds.",
974                                 target_name, seconds)
975                 end
976                 core.chat_send_player(name, rev_msg)
977                 local success, log = core.rollback_revert_actions_by(
978                                 target_name, seconds)
979                 local response = ""
980                 if #log > 100 then
981                         response = S("(log is too long to show)").."\n"
982                 else
983                         for _, line in pairs(log) do
984                                 response = response .. line .. "\n"
985                         end
986                 end
987                 if success then
988                         response = response .. S("Reverting actions succeeded.")
989                 else
990                         response = response .. S("Reverting actions FAILED.")
991                 end
992                 return success, response
993         end,
994 })
995
996 core.register_chatcommand("status", {
997         description = S("Show server status"),
998         func = function(name, param)
999                 local status = core.get_server_status(name, false)
1000                 if status and status ~= "" then
1001                         return true, status
1002                 end
1003                 return false, S("This command was disabled by a mod or game.")
1004         end,
1005 })
1006
1007 core.register_chatcommand("time", {
1008         params = S("[<0..23>:<0..59> | <0..24000>]"),
1009         description = S("Show or set time of day"),
1010         privs = {},
1011         func = function(name, param)
1012                 if param == "" then
1013                         local current_time = math.floor(core.get_timeofday() * 1440)
1014                         local minutes = current_time % 60
1015                         local hour = (current_time - minutes) / 60
1016                         return true, S("Current time is @1:@2.",
1017                                         string.format("%d", hour),
1018                                         string.format("%02d", minutes))
1019                 end
1020                 local player_privs = core.get_player_privs(name)
1021                 if not player_privs.settime then
1022                         return false, S("You don't have permission to run "
1023                                 .. "this command (missing privilege: @1).", "settime")
1024                 end
1025                 local hour, minute = param:match("^(%d+):(%d+)$")
1026                 if not hour then
1027                         local new_time = tonumber(param)
1028                         if not new_time then
1029                                 return false, S("Invalid time.")
1030                         end
1031                         -- Backward compatibility.
1032                         core.set_timeofday((new_time % 24000) / 24000)
1033                         core.log("action", name .. " sets time to " .. new_time)
1034                         return true, S("Time of day changed.")
1035                 end
1036                 hour = tonumber(hour)
1037                 minute = tonumber(minute)
1038                 if hour < 0 or hour > 23 then
1039                         return false, S("Invalid hour (must be between 0 and 23 inclusive).")
1040                 elseif minute < 0 or minute > 59 then
1041                         return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1042                 end
1043                 core.set_timeofday((hour * 60 + minute) / 1440)
1044                 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
1045                 return true, S("Time of day changed.")
1046         end,
1047 })
1048
1049 core.register_chatcommand("days", {
1050         description = S("Show day count since world creation"),
1051         func = function(name, param)
1052                 return true, S("Current day is @1.", core.get_day_count())
1053         end
1054 })
1055
1056 core.register_chatcommand("shutdown", {
1057         params = S("[<delay_in_seconds> | -1] [reconnect] [<message>]"),
1058         description = S("Shutdown server (-1 cancels a delayed shutdown)"),
1059         privs = {server=true},
1060         func = function(name, param)
1061                 local delay, reconnect, message
1062                 delay, param = param:match("^%s*(%S+)(.*)")
1063                 if param then
1064                         reconnect, param = param:match("^%s*(%S+)(.*)")
1065                 end
1066                 message = param and param:match("^%s*(.+)") or ""
1067                 delay = tonumber(delay) or 0
1068
1069                 if delay == 0 then
1070                         core.log("action", name .. " shuts down server")
1071                         core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1072                 end
1073                 core.request_shutdown(message:trim(), core.is_yes(reconnect), delay)
1074                 return true
1075         end,
1076 })
1077
1078 core.register_chatcommand("ban", {
1079         params = S("[<name>]"),
1080         description = S("Ban the IP of a player or show the ban list"),
1081         privs = {ban=true},
1082         func = function(name, param)
1083                 if param == "" then
1084                         local ban_list = core.get_ban_list()
1085                         if ban_list == "" then
1086                                 return true, S("The ban list is empty.")
1087                         else
1088                                 return true, S("Ban list: @1", ban_list)
1089                         end
1090                 end
1091                 if not core.get_player_by_name(param) then
1092                         return false, S("Player is not online.")
1093                 end
1094                 if not core.ban_player(param) then
1095                         return false, S("Failed to ban player.")
1096                 end
1097                 local desc = core.get_ban_description(param)
1098                 core.log("action", name .. " bans " .. desc .. ".")
1099                 return true, S("Banned @1.", desc)
1100         end,
1101 })
1102
1103 core.register_chatcommand("unban", {
1104         params = S("<name> | <IP_address>"),
1105         description = S("Remove IP ban belonging to a player/IP"),
1106         privs = {ban=true},
1107         func = function(name, param)
1108                 if not core.unban_player_or_ip(param) then
1109                         return false, S("Failed to unban player/IP.")
1110                 end
1111                 core.log("action", name .. " unbans " .. param)
1112                 return true, S("Unbanned @1.", param)
1113         end,
1114 })
1115
1116 core.register_chatcommand("kick", {
1117         params = S("<name> [<reason>]"),
1118         description = S("Kick a player"),
1119         privs = {kick=true},
1120         func = function(name, param)
1121                 local tokick, reason = param:match("([^ ]+) (.+)")
1122                 tokick = tokick or param
1123                 if not core.kick_player(tokick, reason) then
1124                         return false, S("Failed to kick player @1.", tokick)
1125                 end
1126                 local log_reason = ""
1127                 if reason then
1128                         log_reason = " with reason \"" .. reason .. "\""
1129                 end
1130                 core.log("action", name .. " kicks " .. tokick .. log_reason)
1131                 return true, S("Kicked @1.", tokick)
1132         end,
1133 })
1134
1135 core.register_chatcommand("clearobjects", {
1136         params = S("[full | quick]"),
1137         description = S("Clear all objects in world"),
1138         privs = {server=true},
1139         func = function(name, param)
1140                 local options = {}
1141                 if param == "" or param == "quick" then
1142                         options.mode = "quick"
1143                 elseif param == "full" then
1144                         options.mode = "full"
1145                 else
1146                         return false, S("Invalid usage, see /help clearobjects.")
1147                 end
1148
1149                 core.log("action", name .. " clears objects ("
1150                                 .. options.mode .. " mode).")
1151                 if options.mode == "full" then
1152                         core.chat_send_all(S("Clearing all objects. This may take a long time. "
1153                                 .. "You may experience a timeout. (by @1)", name))
1154                 end
1155                 core.clear_objects(options)
1156                 core.log("action", "Object clearing done.")
1157                 core.chat_send_all("*** "..S("Cleared all objects."))
1158                 return true
1159         end,
1160 })
1161
1162 core.register_chatcommand("msg", {
1163         params = S("<name> <message>"),
1164         description = S("Send a direct message to a player"),
1165         privs = {shout=true},
1166         func = function(name, param)
1167                 local sendto, message = param:match("^(%S+)%s(.+)$")
1168                 if not sendto then
1169                         return false, S("Invalid usage, see /help msg.")
1170                 end
1171                 if not core.get_player_by_name(sendto) then
1172                         return false, S("The player @1 is not online.", sendto)
1173                 end
1174                 core.log("action", "DM from " .. name .. " to " .. sendto
1175                                 .. ": " .. message)
1176                 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1177                 return true, S("Message sent.")
1178         end,
1179 })
1180
1181 core.register_chatcommand("last-login", {
1182         params = S("[<name>]"),
1183         description = S("Get the last login time of a player or yourself"),
1184         func = function(name, param)
1185                 if param == "" then
1186                         param = name
1187                 end
1188                 local pauth = core.get_auth_handler().get_auth(param)
1189                 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1190                         -- Time in UTC, ISO 8601 format
1191                         return true, S("@1's last login time was @2.",
1192                                 param,
1193                                 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1194                 end
1195                 return false, S("@1's last login time is unknown.", param)
1196         end,
1197 })
1198
1199 core.register_chatcommand("clearinv", {
1200         params = S("[<name>]"),
1201         description = S("Clear the inventory of yourself or another player"),
1202         func = function(name, param)
1203                 local player
1204                 if param and param ~= "" and param ~= name then
1205                         if not core.check_player_privs(name, {server=true}) then
1206                                 return false, S("You don't have permission to "
1207                                         .. "clear another player's inventory "
1208                                         .. "(missing privilege: @1).", "server")
1209                         end
1210                         player = core.get_player_by_name(param)
1211                         core.chat_send_player(param, S("@1 cleared your inventory.", name))
1212                 else
1213                         player = core.get_player_by_name(name)
1214                 end
1215
1216                 if player then
1217                         player:get_inventory():set_list("main", {})
1218                         player:get_inventory():set_list("craft", {})
1219                         player:get_inventory():set_list("craftpreview", {})
1220                         core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1221                         return true, S("Cleared @1's inventory.", player:get_player_name())
1222                 else
1223                         return false, S("Player must be online to clear inventory!")
1224                 end
1225         end,
1226 })
1227
1228 local function handle_kill_command(killer, victim)
1229         if core.settings:get_bool("enable_damage") == false then
1230                 return false, S("Players can't be killed, damage has been disabled.")
1231         end
1232         local victimref = core.get_player_by_name(victim)
1233         if victimref == nil then
1234                 return false, S("Player @1 is not online.", victim)
1235         elseif victimref:get_hp() <= 0 then
1236                 if killer == victim then
1237                         return false, S("You are already dead.")
1238                 else
1239                         return false, S("@1 is already dead.", victim)
1240                 end
1241         end
1242         if not killer == victim then
1243                 core.log("action", string.format("%s killed %s", killer, victim))
1244         end
1245         -- Kill victim
1246         victimref:set_hp(0)
1247         return true, S("@1 has been killed.", victim)
1248 end
1249
1250 core.register_chatcommand("kill", {
1251         params = S("[<name>]"),
1252         description = S("Kill player or yourself"),
1253         privs = {server=true},
1254         func = function(name, param)
1255                 return handle_kill_command(name, param == "" and name or param)
1256         end,
1257 })