2
0

chat.lua 34 KB

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