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