Implement user moving for Postfixadmin.
[mailshears.git] / lib / mv / plugins / postfixadmin.rb
1 require 'pg'
2
3 require 'common/postfixadmin_plugin'
4 require 'mv/mv_plugin'
5
6 class PostfixadminMv
7
8 include PostfixadminPlugin
9 include MvPlugin
10
11 def mv_user(user_from, user_to)
12 if not user_exists(user_from)
13 raise NonexistentUserError.new("source user #{user_from} does not exist")
14 end
15
16 user_to_parts = user_to.split('@')
17 localpart_to = user_to_parts[0]
18 domain_to = user_to_parts[1]
19
20 if domain_to.nil?
21 # There was no "@" in the destination user.
22 msg = "the destination user #{user_to} is not valid"
23 raise InvalidUserError.new(msg)
24 end
25
26 if not domain_exists(domain_to)
27 msg = "destination domain #{domain_to} does not exist"
28 raise NonexistentDomainError.new(msg)
29 end
30
31 mailbox_query = 'UPDATE mailbox SET '
32 mailbox_query += ' username=$1,'
33 mailbox_query += ' domain=$2,'
34 mailbox_query += " maildir=CONCAT($2, '/', $3, '/'),"
35 mailbox_query += ' local_part=$3 '
36 mailbox_query += 'WHERE username=$4;'
37
38 alias_query1 = 'UPDATE alias SET '
39 alias_query1 += ' address=$1,'
40 alias_query1 += ' domain=$2,'
41 alias_query1 += ' goto=REPLACE(goto, $4, $1) '
42 alias_query1 += 'WHERE address=$4;'
43
44 alias_query2 = 'UPDATE alias SET '
45 alias_query2 += 'goto=REPLACE(goto, $4, $1);'
46
47 sql_queries = [mailbox_query, alias_query1, alias_query2]
48
49 begin
50 connection = PGconn.connect(@db_host,
51 @db_port,
52 @db_opts,
53 @db_tty,
54 @db_name,
55 @db_user,
56 @db_pass)
57
58 sql_queries.each do |sql_query|
59 varchar = 1043 # from pg_type.h
60 params = [{:value => user_to, :type => varchar},
61 {:value => domain_to, :type => varchar},
62 {:value => localpart_to, :type => varchar},
63 {:value => user_from, :type => varchar}]
64 connection.query(sql_query, params)
65 end
66
67 connection.close()
68
69 rescue PGError => e
70 # Pretend like we're database-agnostic in case we ever are.
71 raise DatabaseError.new(e)
72 end
73 end
74
75
76 end