chat.lua 38 KB

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