3a5494bced822593e7a63f7a65c4422a02f3fb75
[mailshears.git] / lib / common / postfixadmin_plugin.rb
1 require 'common/domain'
2 require 'common/plugin'
3 require 'common/user'
4 require 'pg'
5
6 module PostfixadminPlugin
7 # Code that all Postfixadmin plugins (Prune, Rm, Mv...) will
8 # share. That is, we implement the Plugin interface.
9 include Plugin
10
11 def initialize(cfg)
12 @db_host = cfg.postfixadmin_dbhost
13 @db_port = cfg.postfixadmin_dbport
14 @db_opts = cfg.postfixadmin_dbopts
15 @db_tty = cfg.postfixadmin_dbtty
16 @db_name = cfg.postfixadmin_dbname
17 @db_user = cfg.postfixadmin_dbuser
18 @db_pass = cfg.postfixadmin_dbpass
19 end
20
21
22 def list_domains()
23 domains = []
24
25 connection = PGconn.connect(@db_host, @db_port, @db_opts, @db_tty,
26 @db_name, @db_user, @db_pass)
27
28 # 'ALL' is a magic domain, and we don't want it.
29 sql_query = "SELECT domain FROM domain WHERE domain <> 'ALL';"
30 connection.query(sql_query) do |result|
31 domains = result.field_values('domain')
32 end
33
34 connection.close()
35
36 return domains.map{ |d| Domain.new(d) }
37 end
38
39
40
41 def list_users()
42 users = []
43
44 connection = PGconn.connect(@db_host, @db_port, @db_opts, @db_tty,
45 @db_name, @db_user, @db_pass)
46
47 sql_query = 'SELECT username FROM mailbox;'
48 connection.query(sql_query) do |result|
49 users = result.field_values('username')
50 end
51
52 connection.close()
53
54 return users.map{ |u| User.new(u) }
55 end
56
57
58 def list_domains_users(domains)
59 usernames = []
60
61 connection = PGconn.connect(@db_host, @db_port, @db_opts, @db_tty,
62 @db_name, @db_user, @db_pass)
63
64 sql_query = 'SELECT username FROM mailbox WHERE domain IN $1;'
65
66 connection.query(sql_query, domains.map{|d| d.to_s()}) do |result|
67 usernames = result.field_values('username')
68 end
69
70 connection.close()
71
72 return usernames.map{ |u| User.new(u) }
73 end
74
75
76 def list_aliases()
77 #
78 # Get a list of all aliases, useful for testing.
79 #
80 aliases = []
81
82 connection = PGconn.connect(@db_host, @db_port, @db_opts, @db_tty,
83 @db_name, @db_user, @db_pass)
84
85 sql_query = 'SELECT address,goto FROM alias;'
86 results = connection.query(sql_query)
87 results.each do |row|
88 aliases << row # row should be a hash
89 end
90
91 connection.close()
92
93 return aliases
94 end
95
96 end