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