338be052f63affe1bb8deab2041cd994994cfbb6
[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(src, dst)
12 # It's obviously an error if the source user does not exist.
13 raise NonexistentUserError.new(src.to_s()) if not user_exists(src)
14
15 # And if the destination domain does not exist.
16 if not domain_exists(dst.domain())
17 raise NonexistentDomainError.new(dst.domain.to_s())
18 end
19
20 # But the destination *user* should *not* exist.
21 # And it's an error if the destination user exists already.
22 raise UserAlreadyExistsError.new(dst.to_s()) if user_exists(dst)
23
24 mailbox_query = 'UPDATE mailbox SET '
25 mailbox_query += ' username=$1,'
26 mailbox_query += ' domain=$2,'
27 mailbox_query += " maildir=CONCAT($2, '/', $3, '/'),"
28 mailbox_query += ' local_part=$3 '
29 mailbox_query += 'WHERE username=$4;'
30
31 alias_query1 = 'UPDATE alias SET '
32 alias_query1 += ' address=$1,'
33 alias_query1 += ' domain=$2,'
34 alias_query1 += ' goto=REPLACE(goto, $4, $1) '
35 alias_query1 += 'WHERE address=$4;'
36
37 alias_query2 = 'UPDATE alias SET '
38 alias_query2 += 'goto=REPLACE(goto, $4, $1);'
39
40 sql_queries = [mailbox_query, alias_query1, alias_query2]
41
42 begin
43 connection = PGconn.connect(@db_host,
44 @db_port,
45 @db_opts,
46 @db_tty,
47 @db_name,
48 @db_user,
49 @db_pass)
50
51 sql_queries.each do |sql_query|
52 varchar = 1043 # from pg_type.h
53 params = [{:value => dst.to_s(), :type => varchar},
54 {:value => dst.domainpart(), :type => varchar},
55 {:value => dst.localpart(), :type => varchar},
56 {:value => src.to_s(), :type => varchar}]
57 connection.query(sql_query, params)
58 end
59
60 connection.close()
61
62 rescue PGError => e
63 # Pretend like we're database-agnostic in case we ever are.
64 raise DatabaseError.new(e)
65 end
66 end
67
68
69 end