summaryrefslogtreecommitdiffstats
path: root/kabc/plugins/sql/resourcesql.cpp
blob: 2e6eb6902cade04cde35e58b9157ec82c04bd345 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
    This file is part of libkabc.
    Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <qsqldatabase.h>
#include <qsqlcursor.h>

#include <kdebug.h>
#include <kglobal.h>
#include <klineedit.h>
#include <klocale.h>

#include "resourcesql.h"
#include "resourcesqlconfig.h"

using namespace KABC;

extern "C"
{
  KDE_EXPORT void *init_kabc_sql()
  {
    return new KRES::PluginFactory<ResourceSql,ResourceSqlConfig>();
  }
}

ResourceSql::ResourceSql( AddressBook *ab, const KConfig *config )
  : Resource( ab ), mDb( 0 )
{
  QString user, password, db, host;

  user = config->readEntry( "SqlUser" );
  password = cryptStr( config->readEntry( "SqlPassword " ) );
  db = config->readEntry( "SqlName" );
  host = config->readEntry( "SqlHost" );

  init( user, password, db, host );
}

ResourceSql::ResourceSql( AddressBook *ab, const QString &user,
    const QString &password, const QString &db, const QString &host )
  : Resource( ab ), mDb( 0 )
{
  init( user, password, db, host );
}

void ResourceSql::init( const QString &user, const QString &password,
    const QString &db, const QString &host )
{
  mUser = user;
  mPassword = password;
  mDbName = db;
  mHost = host;
}

Ticket *ResourceSql::requestSaveTicket()
{
  if ( !addressBook() ) {
    kdDebug(5700) << "no addressbook" << endl;
    return 0;
  }

  return createTicket( this );
}

bool ResourceSql::open()
{
  QStringList drivers = QSqlDatabase::drivers();
  for ( QStringList::Iterator it = drivers.begin(); it != drivers.end(); ++it ) {
    kdDebug(5700) << "Driver: " << (*it) << endl;
  }

  mDb = QSqlDatabase::addDatabase( "QMYSQL3" );

  if ( !mDb ) {
    kdDebug(5700) << "Error. Unable to connect to database." << endl;
    return false;
  }

  mDb->setDatabaseName( mDbName );
  mDb->setUserName( mUser );
  mDb->setPassword( mPassword );
  mDb->setHostName( mHost );

  if ( !mDb->open() ) {
    kdDebug(5700) << "Error. Unable to open database '" << mDbName << "'." << endl;
    return false;
  }

  return true;
}

void ResourceSql::close()
{
  mDb->close();
}

bool ResourceSql::load()
{
  QSqlQuery query( "select addressId, name, familyName, givenName, "
      "additionalName, prefix, suffix, nickname, birthday, "
      "mailer, timezone, geo_latitude, geo_longitude, title, "
      "role, organization, note, productId, revision, "
      "sortString, url from kaddressbook_main_" + mUser );

  while ( query.next() ) {
    QString addrId = query.value(0).toString();

    Addressee addr;
    addr.setResource( this );
    addr.setUid( addrId );
    addr.setName( query.value(1).toString() );
    addr.setFamilyName( query.value(2).toString() );
    addr.setGivenName( query.value(3).toString() );
    addr.setAdditionalName( query.value(4).toString() );
    addr.setPrefix( query.value(5).toString() );
    addr.setSuffix( query.value(6).toString() );
    addr.setNickName( query.value(7).toString() );
    addr.setBirthday( query.value(8).toDateTime() );
    addr.setMailer( query.value(9).toString() );
    addr.setTimeZone( TimeZone( query.value(10).toInt() ) );
    addr.setGeo( Geo( query.value(11).toDouble(), query.value(12).toDouble() ) );
    addr.setTitle( query.value(13).toString() );
    addr.setRole( query.value(14).toString() );
    addr.setOrganization( query.value(15).toString() );
    addr.setNote( query.value(16).toString() );
    addr.setProductId( query.value(17).toString() );
    addr.setRevision( query.value(18).toDateTime() );
    addr.setSortString( query.value(19).toString() );
    addr.setUrl( query.value(20).toString() );

    // emails
    {
      QSqlQuery emailsQuery( "select email, preferred from kaddressbook_emails "
          "where addressId = '" + addrId + "'" );
      while ( emailsQuery.next() )
        addr.insertEmail( emailsQuery.value( 0 ).toString(),
      emailsQuery.value( 1 ).toInt() );
    }

    // phones
    {
      QSqlQuery phonesQuery( "select number, type from kaddressbook_phones "
          "where addressId = '" + addrId + "'" );
      while ( phonesQuery.next() )
        addr.insertPhoneNumber( PhoneNumber( phonesQuery.value( 0 ).toString(),
      phonesQuery.value( 1 ).toInt() ) );
    }    

    // addresses
    {
      QSqlQuery addressesQuery( "select postOfficeBox, extended, street, "
          "locality, region, postalCode, country, label, type "
          "from kaddressbook_addresses where addressId = '" + addrId + "'" );
      while ( addressesQuery.next() ) {
        Address a;
        a.setPostOfficeBox( addressesQuery.value(0).toString() );
        a.setExtended( addressesQuery.value(1).toString() );
        a.setStreet( addressesQuery.value(2).toString() );
        a.setLocality( addressesQuery.value(3).toString() );
        a.setRegion( addressesQuery.value(4).toString() );
        a.setPostalCode( addressesQuery.value(5).toString() );
        a.setCountry( addressesQuery.value(6).toString() );
        a.setLabel( addressesQuery.value(7).toString() );
        a.setType( addressesQuery.value(8).toInt() );

        addr.insertAddress( a );
      }
    }

    // categories
    {
      QSqlQuery categoriesQuery( "select category from kaddressbook_categories "
          "where addressId = '" + addrId + "'" );
      while ( categoriesQuery.next() )
        addr.insertCategory( categoriesQuery.value( 0 ).toString() );
    }

    // customs
    {
      QSqlQuery customsQuery( "select app, name, value from kaddressbook_customs "
          "where addressId = '" + addrId + "'" );
      while ( customsQuery.next() )
        addr.insertCustom( customsQuery.value( 0 ).toString(),
      customsQuery.value( 1 ).toString(),
      customsQuery.value( 2 ).toString());
    }

    addressBook()->insertAddressee( addr );
  }
 
  return true;
}

bool ResourceSql::save( Ticket * )
{
  // we have to delete all entries for this user and reinsert them
  QSqlQuery query( "select addressId from kaddressbook_main_" + mUser );

  while ( query.next() ) {
    QString addrId = query.value( 0 ).toString();
    QSqlQuery q;
	
    q.exec( "DELETE FROM kaddressbook_emails WHERE addressId = '" + addrId + "'" );
    q.exec( "DELETE FROM kaddressbook_phones WHERE addressId = '" + addrId + "'" );
    q.exec( "DELETE FROM kaddressbook_addresses WHERE addressId = '" + addrId + "'" );
    q.exec( "DELETE FROM kaddressbook_categories WHERE addressId = '" + addrId + "'" );
    q.exec( "DELETE FROM kaddressbook_customs WHERE addressId = '" + addrId + "'" );

    q.exec( "DELETE FROM kaddressbook_main_" + mUser + " WHERE addressId = '" + addrId + "'" );
  }

  // let's start...
  AddressBook::Iterator it;
  for ( it = addressBook()->begin(); it != addressBook()->end(); ++it ) {
    if ( (*it).resource() != this && (*it).resource() != 0 ) // save only my and new entries
      continue;

    QString uid = (*it).uid();

    query.exec( "INSERT INTO kaddressbook_main_" + mUser + " VALUES ('" +
        (*it).uid() + "','" +
        (*it).name() + "','" +
        (*it).familyName() + "','" +
        (*it).givenName() + "','" +
        (*it).additionalName() + "','" +
        (*it).prefix() + "','" +
        (*it).suffix() + "','" +
        (*it).nickName() + "','" +
        (*it).birthday().toString( Qt::ISODate ) + "','" +
        (*it).mailer() + "','" +
        QString::number( (*it).timeZone().offset() ) + "','" +
        QString::number( (*it).geo().latitude() ) + "','" +
        QString::number( (*it).geo().longitude() ) + "','" +
        (*it).title() + "','" +
        (*it).role() + "','" +
        (*it).organization() + "','" +
        (*it).note() + "','" +
        (*it).productId() + "','" +
        (*it).revision().toString( Qt::ISODate ) + "','" +
        (*it).sortString() + "','" +
        (*it).url().url() + "')"
    );

    // emails
    {
      QStringList emails = (*it).emails();
      QStringList::ConstIterator it;
      bool preferred = true;
      for( it = emails.begin(); it != emails.end(); ++it ) {
        query.exec("INSERT INTO kaddressbook_emails VALUES ('" +
            uid + "','" +
            (*it) + "','" +
            QString::number(preferred) + "')");
        preferred = false;
      }
    }

    // phonenumbers
    {
      PhoneNumber::List phoneNumberList = (*it).phoneNumbers();
      PhoneNumber::List::ConstIterator it;
      for( it = phoneNumberList.begin(); it != phoneNumberList.end(); ++it ) {
        query.exec("INSERT INTO kaddressbook_phones VALUES ('" +
            uid + "','" +
            (*it).number() + "','" +
            QString::number( (*it).type() ) + "')");
      }
    }

    // postal addresses
    {
      Address::List addressList = (*it).addresses();
      Address::List::ConstIterator it;
      for( it = addressList.begin(); it != addressList.end(); ++it ) {
        query.exec("INSERT INTO kaddressbook_addresses VALUES ('" +
            uid + "','" +
            (*it).postOfficeBox() + "','" +
            (*it).extended() + "','" +
            (*it).street() + "','" +
            (*it).locality() + "','" +
            (*it).region() + "','" +
            (*it).postalCode() + "','" +
            (*it).country() + "','" +
            (*it).label() + "','" +
            QString::number( (*it).type() ) + "')");
      }
    }

    // categories
    {
      QStringList categories = (*it).categories();
      QStringList::ConstIterator it;
      for( it = categories.begin(); it != categories.end(); ++it )
        query.exec("INSERT INTO kaddressbook_categories VALUES ('" +
            uid + "','" +
            (*it) + "')");
    }

    // customs
    {
      QStringList list = (*it).customs();
      QStringList::ConstIterator it;
      for( it = list.begin(); it != list.end(); ++it ) {
        int dashPos = (*it).find( '-' );
        int colonPos = (*it).find( ':' );
        QString app = (*it).left( dashPos );
        QString name = (*it).mid( dashPos + 1, colonPos - dashPos - 1 );
        QString value = (*it).right( (*it).length() - colonPos - 1 );

        query.exec("INSERT INTO kaddressbook_categories VALUES ('" +
            uid + "','" + app + "','" + name + "','" + value + "')");
      }
    }
  }

  return true;
}

QString ResourceSql::identifier() const
{
  return mHost + "_" + mDbName;
}