Fix quoting issues with the new AgenDAV "with" column.
[mailshears.git] / lib / mv / plugins / agendav.rb
1 require 'pg'
2
3 require 'common/agendav_plugin'
4 require 'mv/mv_plugin'
5
6
7 # Handle moving (renaming) Agendav users in its database. Agendav has
8 # no concept of domains.
9 #
10 class AgendavMv
11
12 include AgendavPlugin
13 include MvPlugin
14
15 # Move the user *src* to *dst* within the Agendav database. This
16 # should "rename" him in _every_ table where he is referenced.
17 #
18 # This can fail if *dst* already exists before the move. It should
19 # also be an error if the destination domain doesn't exist. But
20 # Agendav doesn't know about domains, so we let that slide.
21 #
22 # If the source user doesn't exist, we do our best. AgenDAV has a
23 # "shares" table that isn't keyed on the username, but rather the
24 # principal URL. And its "prefs" table doesn't contain entries for
25 # users who have default preferences. As a result, we may need to
26 # perform some find/replaces in the "shares" table even if no
27 # corresponding user exists in the "prefs" table (which is how we
28 # tell if a user exists in AgenDAV). Thus it's not a fatal error if
29 # the *src* user doesn't exist.
30 #
31 # @param src [User] the source user to be moved.
32 #
33 # @param dst [User] the destination user being moved to.
34 #
35 def mv_user(src, dst)
36 raise UserAlreadyExistsError.new(dst.to_s()) if user_exists(dst)
37
38 connection = PG::Connection.new(@db_hash)
39 begin
40 # The "prefs" table uses the normal username as a key...
41 # This should be harmless if the source user does not exist.
42 sql_query0 = 'UPDATE prefs SET username = $1 WHERE username = $2;'
43 connection.query(sql_query0, [dst.to_s(), src.to_s()])
44
45 # But the "shares" table uses encoded principal URLs. For the
46 # "shares" table, we need to do a find/replace on the username
47 # with its "@" symbol translated to a "%40".
48 encoded_src = src.to_s()['@'] = '%40'
49 encoded_dst = dst.to_s()['@'] = '%40'
50
51 # Unlike in the "rm" plugin, we do modify the "calendar" field
52 # here. That's because in the usual legitimate use case, the
53 # calendar URL will change when a user moves. This will ALSO
54 # affect people who name their calendars something like
55 # "user%40example.com", but screw those people.
56 sql_queries = ['UPDATE shares SET owner=REPLACE(owner, $2, $1);']
57 sql_queries << 'UPDATE shares SET calendar=REPLACE(calendar, $2, $1);'
58 sql_queries << 'UPDATE shares SET "with"=REPLACE("with", $2, $1);'
59
60 sql_queries.each do |sql_query|
61 connection.query(sql_query, [encoded_dst, encoded_src])
62 end
63 ensure
64 # Make sure the connection gets closed even if a query explodes.
65 connection.close()
66 end
67 end
68
69 end