util.lua 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. -- Copyright 2008 Steven Barth <steven@midlink.org>
  2. -- Copyright 2017 Matthias Schiffer <mschiffer@universe-factory.net>
  3. -- Licensed to the public under the Apache License 2.0.
  4. local io = require "io"
  5. local table = require "table"
  6. local tparser = require "gluon.web.template.parser"
  7. local json = require "luci.jsonc"
  8. local nixio = require "nixio"
  9. local fs = require "nixio.fs"
  10. local getmetatable, setmetatable = getmetatable, setmetatable
  11. local tostring, pairs = tostring, pairs
  12. module "gluon.web.util"
  13. --
  14. -- Class helper routines
  15. --
  16. -- Instantiates a class
  17. local function _instantiate(class, ...)
  18. local inst = setmetatable({}, {__index = class})
  19. if inst.__init__ then
  20. inst:__init__(...)
  21. end
  22. return inst
  23. end
  24. -- The class object can be instantiated by calling itself.
  25. -- Any class functions or shared parameters can be attached to this object.
  26. -- Attaching a table to the class object makes this table shared between
  27. -- all instances of this class. For object parameters use the __init__ function.
  28. -- Classes can inherit member functions and values from a base class.
  29. -- Class can be instantiated by calling them. All parameters will be passed
  30. -- to the __init__ function of this class - if such a function exists.
  31. -- The __init__ function must be used to set any object parameters that are not shared
  32. -- with other objects of this class. Any return values will be ignored.
  33. function class(base)
  34. return setmetatable({}, {
  35. __call = _instantiate,
  36. __index = base
  37. })
  38. end
  39. function instanceof(object, class)
  40. while object do
  41. if object == class then
  42. return true
  43. end
  44. local mt = getmetatable(object)
  45. object = mt and mt.__index
  46. end
  47. return false
  48. end
  49. --
  50. -- String and data manipulation routines
  51. --
  52. function pcdata(value)
  53. return value and tparser.pcdata(tostring(value))
  54. end
  55. function contains(table, value)
  56. for k, v in pairs(table) do
  57. if value == v then
  58. return k
  59. end
  60. end
  61. return false
  62. end
  63. --
  64. -- System utility functions
  65. --
  66. function exec(command)
  67. local pp = io.popen(command)
  68. local data = pp:read("*a")
  69. pp:close()
  70. return data
  71. end
  72. function uniqueid(bytes)
  73. local rand = fs.readfile("/dev/urandom", bytes)
  74. return nixio.bin.hexlify(rand)
  75. end
  76. serialize_json = json.stringify
  77. function libpath()
  78. return '/lib/gluon/web'
  79. end