]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/sximporter/importer.py
98c9dbd64872a63fdc73ee9d9d8407b7539c4a36
[osqa.git] / forum_modules / sximporter / importer.py
1 # -*- coding: utf-8 -*-
2
3 from datetime import datetime
4 import time
5 import re
6 import os
7 import gc
8 from django.utils.translation import ugettext as _
9
10 from django.utils.encoding import force_unicode
11
12 try:
13     from cPickle import loads, dumps
14 except ImportError:
15     from pickle import loads, dumps
16
17 from copy import deepcopy
18 from base64 import b64encode, b64decode
19 from zlib import compress, decompress
20
21 from xml.sax import make_parser
22 from xml.sax.handler import ContentHandler
23
24 def create_orm():
25     from django.conf import settings
26     from south.orm import FakeORM
27
28     get_migration_number_re = re.compile(r'^((\d+)_.*)\.py$')
29
30     migrations_folder = os.path.join(settings.SITE_SRC_ROOT, 'forum/migrations')
31
32     highest_number = 0
33     highest_file = None
34
35     for f in os.listdir(migrations_folder):
36         if os.path.isfile(os.path.join(migrations_folder, f)):
37             m = get_migration_number_re.match(f)
38
39             if m:
40                 found = int(m.group(2))
41
42                 if found > highest_number:
43                     highest_number = found
44                     highest_file = m.group(1)
45
46     mod = __import__('forum.migrations.%s' % highest_file, globals(), locals(), ['forum.migrations'])
47     return FakeORM(getattr(mod, 'Migration'), "forum")
48
49 orm = create_orm()
50
51 class SXTableHandler(ContentHandler):
52     def __init__(self, fname, callback):
53         self.in_row = False
54         self.el_data = {}
55         self.ch_data = ''
56
57         self.fname = fname.lower()
58         self.callback = callback
59
60     def startElement(self, name, attrs):
61         if name.lower() == self.fname:
62             pass
63         elif name.lower() == "row":
64             self.in_row = True
65
66     def characters(self, ch):
67         self.ch_data += ch
68
69     def endElement(self, name):
70         if name.lower() == self.fname:
71             pass
72         elif name.lower() == "row":
73             self.callback(self.el_data)
74
75             self.in_row = False
76             del self.el_data
77             self.el_data = {}
78         elif self.in_row:
79             self.el_data[name.lower()] = self.ch_data.strip()
80             del self.ch_data
81             self.ch_data = ''
82
83
84 def readTable(path, name, callback):
85     parser = make_parser()
86     handler = SXTableHandler(name, callback)
87     parser.setContentHandler(handler)
88
89     f = os.path.join(path, "%s.xml" % name)
90     parser.parse(f)
91
92
93 def dbsafe_encode(value):
94     return force_unicode(b64encode(compress(dumps(deepcopy(value)))))
95
96 def getText(el):
97     rc = ""
98     for node in el.childNodes:
99         if node.nodeType == node.TEXT_NODE:
100             rc = rc + node.data
101     return rc.strip()
102
103 msstrip = re.compile(r'^(.*)\.\d+')
104 def readTime(ts):
105     noms = msstrip.match(ts)
106     if noms:
107         ts = noms.group(1)
108
109     return datetime(*time.strptime(ts, '%Y-%m-%dT%H:%M:%S')[0:6])
110
111 #def readEl(el):
112 #    return dict([(n.tagName.lower(), getText(n)) for n in el.childNodes if n.nodeType == el.ELEMENT_NODE])
113
114 #def readTable(dump, name):
115 #    for e in minidom.parseString(dump.read("%s.xml" % name)).getElementsByTagName('row'):
116 #        yield readEl(e)
117 #return [readEl(e) for e in minidom.parseString(dump.read("%s.xml" % name)).getElementsByTagName('row')]
118
119 google_accounts_lookup = re.compile(r'^https?://www.google.com/accounts/')
120 yahoo_accounts_lookup = re.compile(r'^https?://me.yahoo.com/a/')
121
122 openid_lookups = [
123         re.compile(r'^https?://www.google.com/profiles/(?P<uname>\w+(\.\w+)*)/?$'),
124         re.compile(r'^https?://me.yahoo.com/(?P<uname>\w+(\.\w+)*)/?$'),
125         re.compile(r'^https?://openid.aol.com/(?P<uname>\w+(\.\w+)*)/?$'),
126         re.compile(r'^https?://(?P<uname>\w+(\.\w+)*).myopenid.com/?$'),
127         re.compile(r'^https?://flickr.com/(\w+/)*(?P<uname>\w+(\.\w+)*)/?$'),
128         re.compile(r'^https?://technorati.com/people/technorati/(?P<uname>\w+(\.\w+)*)/?$'),
129         re.compile(r'^https?://(?P<uname>\w+(\.\w+)*).wordpress.com/?$'),
130         re.compile(r'^https?://(?P<uname>\w+(\.\w+)*).blogspot.com/?$'),
131         re.compile(r'^https?://(?P<uname>\w+(\.\w+)*).livejournal.com/?$'),
132         re.compile(r'^https?://claimid.com/(?P<uname>\w+(\.\w+)*)/?$'),
133         re.compile(r'^https?://(?P<uname>\w+(\.\w+)*).pip.verisignlabs.com/?$'),
134         re.compile(r'^https?://getopenid.com/(?P<uname>\w+(\.\w+)*)/?$'),
135         re.compile(r'^https?://[\w\.]+/(\w+/)*(?P<uname>\w+(\.\w+)*)/?$'),
136         re.compile(r'^https?://(?P<uname>[\w\.]+)/?$'),
137         ]
138
139 def final_username_attempt(sxu):
140     openid = sxu.get('openid', None)
141
142     if openid:
143         if google_accounts_lookup.search(openid):
144             return UnknownGoogleUser(sxu.get('id'))
145         if yahoo_accounts_lookup.search(openid):
146             return UnknownYahooUser(sxu.get('id'))
147
148         for lookup in openid_lookups:
149             if lookup.search(openid):
150                 return lookup.search(openid).group('uname')
151
152     return UnknownUser(sxu.get('id'))
153
154 class UnknownUser(object):
155     def __init__(self, id):
156         self._id = id
157
158     def __str__(self):
159         return _("user-%(id)s") % {'id': self._id}
160
161     def __unicode__(self):
162         return self.__str__()
163
164     def encode(self, *args):
165         return self.__str__()
166
167 class UnknownGoogleUser(UnknownUser):
168     def __str__(self):
169         return _("user-%(id)s (google)") % {'id': self._id}
170
171 class UnknownYahooUser(UnknownUser):
172     def __str__(self):
173         return _("user-%(id)s (yahoo)") % {'id': self._id}
174
175
176 class IdMapper(dict):
177
178     def __init__(self):
179         self.default = 1
180
181     def __getitem__(self, key):
182         key = int(key)
183         return super(IdMapper, self).get(key, self.default)
184
185     def __setitem__(self, key, value):
186         super(IdMapper, self).__setitem__(int(key), int(value))
187
188 class IdIncrementer():
189     def __init__(self, initial):
190         self.value = initial
191
192     def inc(self):
193         self.value += 1
194
195 openidre = re.compile('^https?\:\/\/')
196 def userimport(path, options):
197
198     usernames = []
199     openids = set()
200     uidmapper = IdMapper()
201
202     authenticated_user = options.get('authenticated_user', None)
203     owneruid = options.get('owneruid', None)
204     #check for empty values
205     if not owneruid:
206         owneruid = None
207     else:
208         owneruid = int(owneruid)
209
210     def callback(sxu):
211         create = True
212         set_mapper_defaults = False
213
214         if sxu.get('id') == '-1':
215             return
216         #print "\n".join(["%s : %s" % i for i in sxu.items()])
217
218         if (owneruid and (int(sxu.get('id')) == owneruid)) or (
219             (not owneruid) and len(uidmapper)):
220
221             set_mapper_defaults = True
222
223             if authenticated_user:
224                 osqau = orm.User.objects.get(id=authenticated_user.id)
225
226                 for assoc in orm.AuthKeyUserAssociation.objects.filter(user=osqau):
227                     openids.add(assoc.key)
228
229                 uidmapper[owneruid] = osqau.id
230                 create = False
231
232         sxbadges = sxu.get('badgesummary', None)
233         badges = {'1':'0', '2':'0', '3':'0'}
234
235         if sxbadges:
236             badges.update(dict([b.split('=') for b in sxbadges.split()]))
237
238         if create:
239             username = unicode(sxu.get('displayname',
240                                sxu.get('displaynamecleaned', sxu.get('realname', final_username_attempt(sxu)))))[:30]
241
242             if username in usernames:
243             #if options.get('mergesimilar', False) and sxu.get('email', 'INVALID') == user_by_name[username].email:
244             #    osqau = user_by_name[username]
245             #    create = False
246             #    uidmapper[sxu.get('id')] = osqau.id
247             #else:
248                 inc = 0
249
250                 while True:
251                     inc += 1
252                     totest = "%s %d" % (username[:29 - len(str(inc))], inc)
253
254                     if not totest in usernames:
255                         username = totest
256                         break
257
258             osqau = orm.User(
259                     id           = sxu.get('id'),
260                     username     = username,
261                     password     = '!',
262                     email        = sxu.get('email', ''),
263                     is_superuser = sxu.get('usertypeid') == '5',
264                     is_staff     = sxu.get('usertypeid') == '4',
265                     is_active    = True,
266                     date_joined  = readTime(sxu.get('creationdate')),
267                     last_seen    = readTime(sxu.get('lastaccessdate')),
268                     about         = sxu.get('aboutme', ''),
269                     date_of_birth = sxu.get('birthday', None) and readTime(sxu['birthday']) or None,
270                     email_isvalid = int(sxu.get('usertypeid')) > 2,
271                     website       = sxu.get('websiteurl', ''),
272                     reputation    = int(sxu.get('reputation')),
273                     gold          = int(badges['1']),
274                     silver        = int(badges['2']),
275                     bronze        = int(badges['3']),
276                     real_name     = sxu.get('realname', '')[:30],
277                     location      = sxu.get('location', ''),
278                     )
279
280             osqau.save()
281
282             user_joins = orm.Action(
283                     action_type = "userjoins",
284                     action_date = osqau.date_joined,
285                     user = osqau
286                     )
287             user_joins.save()
288
289             rep = orm.ActionRepute(
290                     value = 1,
291                     user = osqau,
292                     date = osqau.date_joined,
293                     action = user_joins
294                     )
295             rep.save()
296
297             try:
298                 orm.SubscriptionSettings.objects.get(user=osqau)
299             except:
300                 s = orm.SubscriptionSettings(user=osqau)
301                 s.save()
302
303             uidmapper[osqau.id] = osqau.id
304         else:
305             new_about = sxu.get('aboutme', None)
306             if new_about and osqau.about != new_about:
307                 if osqau.about:
308                     osqau.about = "%s\n|\n%s" % (osqau.about, new_about)
309                 else:
310                     osqau.about = new_about
311
312             osqau.username = sxu.get('displayname',
313                                      sxu.get('displaynamecleaned', sxu.get('realname', final_username_attempt(sxu))))
314             osqau.email = sxu.get('email', '')
315             osqau.reputation += int(sxu.get('reputation'))
316             osqau.gold += int(badges['1'])
317             osqau.silver += int(badges['2'])
318             osqau.bronze += int(badges['3'])
319
320             osqau.date_joined = readTime(sxu.get('creationdate'))
321             osqau.website = sxu.get('websiteurl', '')
322             osqau.date_of_birth = sxu.get('birthday', None) and readTime(sxu['birthday']) or None
323             osqau.location = sxu.get('location', '')
324             osqau.real_name = sxu.get('realname', '')
325
326             #merged_users.append(osqau.id)
327             osqau.save()
328
329         if set_mapper_defaults:
330             uidmapper[-1] = osqau.id
331             uidmapper.default = osqau.id
332
333         usernames.append(osqau.username)
334
335         openid = sxu.get('openid', None)
336         if openid and openidre.match(openid) and (not openid in openids):
337             assoc = orm.AuthKeyUserAssociation(user=osqau, key=openid, provider="openidurl")
338             assoc.save()
339             openids.add(openid)
340
341         openidalt = sxu.get('openidalt', None)
342         if openidalt and openidre.match(openidalt) and (not openidalt in openids):
343             assoc = orm.AuthKeyUserAssociation(user=osqau, key=openidalt, provider="openidurl")
344             assoc.save()
345             openids.add(openidalt)
346
347     readTable(path, "Users", callback)
348
349     #if uidmapper[-1] == -1:
350     #    uidmapper[-1] = 1
351
352     return uidmapper
353
354 def tagsimport(dump, uidmap):
355
356     tagmap = {}
357
358     def callback(sxtag):
359         otag = orm.Tag(
360                 id = int(sxtag['id']),
361                 name = sxtag['name'],
362                 used_count = int(sxtag['count']),
363                 created_by_id = uidmap[sxtag.get('userid', 1)],
364                 )
365         otag.save()
366
367         tagmap[otag.name] = otag
368
369     readTable(dump, "Tags", callback)
370
371     return tagmap
372
373 def add_post_state(name, post, action):
374     if not "(%s)" % name in post.state_string:
375         post.state_string = "%s(%s)" % (post.state_string, name)
376         post.save()
377
378     try:
379         state = orm.NodeState.objects.get(node=post, state_type=name)
380         state.action = action
381         state.save()
382     except:
383         state = orm.NodeState(node=post, state_type=name, action=action)
384         state.save()
385
386 def remove_post_state(name, post):
387     if "(%s)" % name in post.state_string:
388         try:
389             state = orm.NodeState.objects.get(state_type=name, post=post)
390             state.delete()
391         except:
392             pass
393     post.state_string = "".join("(%s)" % s for s in re.findall('\w+', post.state_string) if s != name)
394
395 def postimport(dump, uidmap, tagmap):
396     all = []
397
398     def callback(sxpost):
399         nodetype = (sxpost.get('posttypeid') == '1') and "nodetype" or "answer"
400
401         post = orm.Node(
402                 node_type = nodetype,
403                 id = sxpost['id'],
404                 added_at = readTime(sxpost['creationdate']),
405                 body = sxpost['body'],
406                 score = sxpost.get('score', 0),
407                 author_id = sxpost.get('deletiondate', None) and 1 or uidmap[sxpost.get('owneruserid', 1)]
408                 )
409
410         post.save()
411
412         create_action = orm.Action(
413                 action_type = (nodetype == "nodetype") and "ask" or "answer",
414                 user_id = post.author_id,
415                 node = post,
416                 action_date = post.added_at
417                 )
418
419         create_action.save()
420
421         if sxpost.get('lasteditoruserid', None):
422             revise_action = orm.Action(
423                     action_type = "revise",
424                     user_id = uidmap[sxpost.get('lasteditoruserid')],
425                     node = post,
426                     action_date = readTime(sxpost['lasteditdate']),
427                     )
428
429             revise_action.save()
430             post.last_edited = revise_action
431
432         if sxpost.get('communityowneddate', None):
433             wikify_action = orm.Action(
434                     action_type = "wikify",
435                     user_id = 1,
436                     node = post,
437                     action_date = readTime(sxpost['communityowneddate'])
438                     )
439
440             wikify_action.save()
441             add_post_state("wiki", post, wikify_action)
442
443         if sxpost.get('lastactivityuserid', None):
444             post.last_activity_by_id = uidmap[sxpost['lastactivityuserid']]
445             post.last_activity_at = readTime(sxpost['lastactivitydate'])
446
447         if sxpost.get('posttypeid') == '1': #question
448             post.node_type = "question"
449             post.title = sxpost['title']
450
451             tagnames = sxpost['tags'].replace(u'ö', '-').replace(u'é', '').replace(u'à', '')
452             post.tagnames = tagnames
453
454             post.extra_count = sxpost.get('viewcount', 0)
455
456             add_tags_to_post(post, tagmap)
457
458         else:
459             post.parent_id = sxpost['parentid']
460
461         post.save()
462
463         all.append(int(post.id))
464         create_and_activate_revision(post)
465
466         del post
467
468     readTable(dump, "Posts", callback)
469
470     return all
471
472 def comment_import(dump, uidmap, posts):
473     currid = IdIncrementer(max(posts))
474     mapping = {}
475
476     def callback(sxc):
477         currid.inc()
478         oc = orm.Node(
479                 id = currid.value,
480                 node_type = "comment",
481                 added_at = readTime(sxc['creationdate']),
482                 author_id = uidmap[sxc.get('userid', 1)],
483                 body = sxc['text'],
484                 parent_id = sxc.get('postid'),
485                 )
486
487         if sxc.get('deletiondate', None):
488             delete_action = orm.Action(
489                     action_type = "delete",
490                     user_id = uidmap[sxc['deletionuserid']],
491                     action_date = readTime(sxc['deletiondate'])
492                     )
493
494             oc.author_id = uidmap[sxc['deletionuserid']]
495             oc.save()
496
497             delete_action.node = oc
498             delete_action.save()
499
500             add_post_state("deleted", oc, delete_action)
501         else:
502             oc.author_id = uidmap[sxc.get('userid', 1)]
503             oc.save()
504
505         create_action = orm.Action(
506                 action_type = "comment",
507                 user_id = oc.author_id,
508                 node = oc,
509                 action_date = oc.added_at
510                 )
511
512         create_and_activate_revision(oc)
513
514         create_action.save()
515         oc.save()
516
517         posts.append(int(oc.id))
518         mapping[int(sxc['id'])] = int(oc.id)
519
520     readTable(dump, "PostComments", callback)
521     return posts, mapping
522
523
524 def add_tags_to_post(post, tagmap):
525     tags = [tag for tag in [tagmap.get(name.strip()) for name in post.tagnames.split(u' ') if name] if tag]
526     post.tagnames = " ".join([t.name for t in tags]).strip()
527     post.tags = tags
528
529
530 def create_and_activate_revision(post):
531     rev = orm.NodeRevision(
532             author_id = post.author_id,
533             body = post.body,
534             node_id = post.id,
535             revised_at = post.added_at,
536             revision = 1,
537             summary = 'Initial revision',
538             tagnames = post.tagnames,
539             title = post.title,
540             )
541
542     rev.save()
543     post.active_revision_id = rev.id
544     post.save()
545
546 def post_vote_import(dump, uidmap, posts):
547     close_reasons = {}
548
549     def close_callback(r):
550         close_reasons[r['id']] = r['name']
551
552     readTable(dump, "CloseReasons", close_callback)
553
554     user2vote = []
555
556     def callback(sxv):
557         action = orm.Action(
558                 user_id=uidmap[sxv['userid']],
559                 action_date = readTime(sxv['creationdate']),
560                 )
561
562         if not int(sxv['postid']) in posts: return
563         node = orm.Node.objects.get(id=sxv['postid'])
564         action.node = node
565
566         if sxv['votetypeid'] == '1':
567             answer = node
568             question = orm.Node.objects.get(id=answer.parent_id)
569
570             action.action_type = "acceptanswer"
571             action.save()
572
573             answer.marked = True
574
575             question.extra_ref_id = answer.id
576
577             answer.save()
578             question.save()
579
580         elif sxv['votetypeid'] in ('2', '3'):
581             if not (action.node.id, action.user_id) in user2vote:
582                 user2vote.append((action.node.id, action.user_id))
583
584                 action.action_type = (sxv['votetypeid'] == '2') and "voteup" or "votedown"
585                 action.save()
586
587                 ov = orm.Vote(
588                         node_id = action.node.id,
589                         user_id = action.user_id,
590                         voted_at = action.action_date,
591                         value = sxv['votetypeid'] == '2' and 1 or -1,
592                         action = action
593                         )
594                 ov.save()
595             else:
596                 action.action_type = "unknown"
597                 action.save()
598
599         elif sxv['votetypeid'] in ('4', '12', '13'):
600             action.action_type = "flag"
601             action.save()
602
603             of = orm.Flag(
604                     node = action.node,
605                     user_id = action.user_id,
606                     flagged_at = action.action_date,
607                     reason = '',
608                     action = action
609                     )
610
611             of.save()
612
613         elif sxv['votetypeid'] == '5':
614             action.action_type = "favorite"
615             action.save()
616
617         elif sxv['votetypeid'] == '6':
618             action.action_type = "close"
619             action.extra = dbsafe_encode(close_reasons[sxv['comment']])
620             action.save()
621
622             node.marked = True
623             node.save()
624
625         elif sxv['votetypeid'] == '7':
626             action.action_type = "unknown"
627             action.save()
628
629             node.marked = False
630             node.save()
631
632             remove_post_state("closed", node)
633
634         elif sxv['votetypeid'] == '10':
635             action.action_type = "delete"
636             action.save()
637
638         elif sxv['votetypeid'] == '11':
639             action.action_type = "unknown"
640             action.save()
641
642             remove_post_state("deleted", node)
643
644         else:
645             action.action_type = "unknown"
646             action.save()
647
648         if sxv.get('targetrepchange', None):
649             rep = orm.ActionRepute(
650                     action = action,
651                     date = action.action_date,
652                     user_id = uidmap[sxv['targetuserid']],
653                     value = int(sxv['targetrepchange'])
654                     )
655
656             rep.save()
657
658         if sxv.get('voterrepchange', None):
659             rep = orm.ActionRepute(
660                     action = action,
661                     date = action.action_date,
662                     user_id = uidmap[sxv['userid']],
663                     value = int(sxv['voterrepchange'])
664                     )
665
666             rep.save()
667
668         if action.action_type in ("acceptanswer", "delete", "close"):
669             state = {"acceptanswer": "accepted", "delete": "deleted", "close": "closed"}[action.action_type]
670             add_post_state(state, node, action)
671
672     readTable(dump, "Posts2Votes", callback)
673
674
675 def comment_vote_import(dump, uidmap, comments):
676     user2vote = []
677     comments2score = {}
678
679     def callback(sxv):
680         if sxv['votetypeid'] == "2":
681             comment_id = comments[int(sxv['postcommentid'])]
682             user_id = uidmap[sxv['userid']]
683
684             if not (comment_id, user_id) in user2vote:
685                 user2vote.append((comment_id, user_id))
686
687                 action = orm.Action(
688                         action_type = "voteupcomment",
689                         user_id = user_id,
690                         action_date = readTime(sxv['creationdate']),
691                         node_id = comment_id
692                         )
693                 action.save()
694
695                 ov = orm.Vote(
696                         node_id = comment_id,
697                         user_id = user_id,
698                         voted_at = action.action_date,
699                         value = 1,
700                         action = action
701                         )
702
703                 ov.save()
704
705                 if not comment_id in comments2score:
706                     comments2score[comment_id] = 1
707                 else:
708                     comments2score[comment_id] += 1
709
710     readTable(dump, "Comments2Votes", callback)
711
712     for cid, score in comments2score.items():
713         orm.Node.objects.filter(id=cid).update(score=score)
714
715
716 def badges_import(dump, uidmap, post_list):
717
718     sxbadges = {}
719
720     def sxcallback(b):
721         sxbadges[int(b['id'])] = b
722
723     readTable(dump, "Badges", sxcallback)
724
725     obadges = dict([(b.cls, b) for b in orm.Badge.objects.all()])
726     user_badge_count = {}
727
728     sx_to_osqa = {}
729
730     for id, sxb in sxbadges.items():
731         cls = "".join(sxb['name'].replace('&', 'And').split(' '))
732
733         if cls in obadges:
734             sx_to_osqa[id] = obadges[cls]
735         else:
736             osqab = orm.Badge(
737                     cls = cls,
738                     awarded_count = 0,
739                     type = sxb['class']
740                     )
741             osqab.save()
742             sx_to_osqa[id] = osqab
743
744     osqaawards = []
745
746     def callback(sxa):
747         badge = sx_to_osqa[int(sxa['badgeid'])]
748
749         user_id = uidmap[sxa['userid']]
750         if not user_badge_count.get(user_id, None):
751             user_badge_count[user_id] = 0
752
753         action = orm.Action(
754                 action_type = "award",
755                 user_id = user_id,
756                 action_date = readTime(sxa['date'])
757                 )
758
759         action.save()
760
761         osqaa = orm.Award(
762                 user_id = uidmap[sxa['userid']],
763                 badge = badge,
764                 node_id = post_list[user_badge_count[user_id]],
765                 awarded_at = action.action_date,
766                 action = action
767                 )
768
769         osqaa.save()
770         badge.awarded_count += 1
771
772         user_badge_count[user_id] += 1
773
774     readTable(dump, "Users2Badges", callback)
775
776     for badge in obadges.values():
777         badge.save()
778
779 def save_setting(k, v):
780     try:
781         kv = orm.KeyValue.objects.get(key=k)
782         kv.value = v
783     except:
784         kv = orm.KeyValue(key = k, value = v)
785
786     kv.save()
787
788
789 def pages_import(dump, currid):
790     currid = IdIncrementer(currid)
791     registry = {}
792
793     def callback(sxp):
794         currid.inc()
795         page = orm.Node(
796                 id = currid.value,
797                 node_type = "page",
798                 title = sxp['name'],
799                 body = b64decode(sxp['value']),
800                 extra = dbsafe_encode({
801                 'path': sxp['url'][1:],
802                 'mimetype': sxp['contenttype'],
803                 'template': (sxp['usemaster'] == "true") and "default" or "none",
804                 'render': "html",
805                 'sidebar': "",
806                 'sidebar_wrap': True,
807                 'sidebar_render': "html",
808                 'comments': False
809                 }),
810                 author_id = 1
811                 )
812
813         create_and_activate_revision(page)
814
815         page.save()
816         registry[sxp['url'][1:]] = page.id
817
818         create_action = orm.Action(
819                 action_type = "newpage",
820                 user_id = page.author_id,
821                 node = page
822                 )
823
824         create_action.save()
825
826         if sxp['active'] == "true" and sxp['contenttype'] == "text/html":
827             pub_action = orm.Action(
828                     action_type = "publish",
829                     user_id = page.author_id,
830                     node = page
831                     )
832
833             pub_action.save()
834             add_post_state("published", page, pub_action)
835
836     readTable(dump, "FlatPages", callback)
837
838     save_setting('STATIC_PAGE_REGISTRY', dbsafe_encode(registry))
839
840 sx2osqa_set_map = {
841 u'theme.html.name': 'APP_TITLE',
842 u'theme.html.footer': 'CUSTOM_FOOTER',
843 u'theme.html.sidebar': 'SIDEBAR_UPPER_TEXT',
844 u'theme.html.sidebar-low': 'SIDEBAR_LOWER_TEXT',
845 u'theme.html.welcome': 'APP_INTRO',
846 u'theme.html.head': 'CUSTOM_HEAD',
847 u'theme.html.header': 'CUSTOM_HEADER',
848 u'theme.css': 'CUSTOM_CSS',
849 }
850
851 html_codes = (
852 ('&amp;', '&'),
853 ('&lt;', '<'),
854 ('&gt;', '>'),
855 ('&quot;', '"'),
856 ('&#39;', "'"),
857 )
858
859 def html_decode(html):
860     html = force_unicode(html)
861
862     for args in html_codes:
863         html = html.replace(*args)
864
865     return html
866
867
868 def static_import(dump):
869     sx_unknown = {}
870
871     def callback(set):
872         if unicode(set['name']) in sx2osqa_set_map:
873             save_setting(sx2osqa_set_map[set['name']], dbsafe_encode(html_decode(set['value'])))
874         else:
875             sx_unknown[set['name']] = html_decode(set['value'])
876
877     readTable(dump, "ThemeTextResources", callback)
878
879     save_setting('SXIMPORT_UNKNOWN_SETS', dbsafe_encode(sx_unknown))
880
881 def disable_triggers():
882     from south.db import db
883     if db.backend_name == "postgres":
884         db.execute_many(PG_DISABLE_TRIGGERS)
885         db.commit_transaction()
886         db.start_transaction()
887
888 def enable_triggers():
889     from south.db import db
890     if db.backend_name == "postgres":
891         db.start_transaction()
892         db.execute_many(PG_ENABLE_TRIGGERS)
893         db.commit_transaction()
894
895 def reset_sequences():
896     from south.db import db
897     if db.backend_name == "postgres":
898         db.start_transaction()
899         db.execute_many(PG_SEQUENCE_RESETS)
900         db.commit_transaction()
901
902 def reindex_fts():
903     from south.db import db
904     if db.backend_name == "postgres":
905         db.start_transaction()
906         db.execute_many("UPDATE forum_noderevision set id = id WHERE TRUE;")
907         db.commit_transaction()
908
909
910 def sximport(dump, options):
911     try:
912         disable_triggers()
913         triggers_disabled = True
914     except:
915         triggers_disabled = False
916
917     uidmap = userimport(dump, options)
918     tagmap = tagsimport(dump, uidmap)
919     gc.collect()
920
921     posts = postimport(dump, uidmap, tagmap)
922     gc.collect()
923
924     posts, comments = comment_import(dump, uidmap, posts)
925     gc.collect()
926
927     post_vote_import(dump, uidmap, posts)
928     gc.collect()
929
930     comment_vote_import(dump, uidmap, comments)
931     gc.collect()
932
933     badges_import(dump, uidmap, posts)
934
935     pages_import(dump, max(posts))
936     static_import(dump)
937     gc.collect()
938
939     from south.db import db
940     db.commit_transaction()
941
942     reset_sequences()
943
944     if triggers_disabled:
945         enable_triggers()
946         reindex_fts()
947
948
949 PG_DISABLE_TRIGGERS = """
950 ALTER table auth_user DISABLE TRIGGER ALL;
951 ALTER table auth_user_groups DISABLE TRIGGER ALL;
952 ALTER table auth_user_user_permissions DISABLE TRIGGER ALL;
953 ALTER table forum_keyvalue DISABLE TRIGGER ALL;
954 ALTER table forum_action DISABLE TRIGGER ALL;
955 ALTER table forum_actionrepute DISABLE TRIGGER ALL;
956 ALTER table forum_subscriptionsettings DISABLE TRIGGER ALL;
957 ALTER table forum_validationhash DISABLE TRIGGER ALL;
958 ALTER table forum_authkeyuserassociation DISABLE TRIGGER ALL;
959 ALTER table forum_tag DISABLE TRIGGER ALL;
960 ALTER table forum_markedtag DISABLE TRIGGER ALL;
961 ALTER table forum_node DISABLE TRIGGER ALL;
962 ALTER table forum_nodestate DISABLE TRIGGER ALL;
963 ALTER table forum_node_tags DISABLE TRIGGER ALL;
964 ALTER table forum_noderevision DISABLE TRIGGER ALL;
965 ALTER table forum_node_tags DISABLE TRIGGER ALL;
966 ALTER table forum_questionsubscription DISABLE TRIGGER ALL;
967 ALTER table forum_vote DISABLE TRIGGER ALL;
968 ALTER table forum_flag DISABLE TRIGGER ALL;
969 ALTER table forum_badge DISABLE TRIGGER ALL;
970 ALTER table forum_award DISABLE TRIGGER ALL;
971 ALTER table forum_openidnonce DISABLE TRIGGER ALL;
972 ALTER table forum_openidassociation DISABLE TRIGGER ALL;
973 """
974
975 PG_ENABLE_TRIGGERS = """
976 ALTER table auth_user ENABLE TRIGGER ALL;
977 ALTER table auth_user_groups ENABLE TRIGGER ALL;
978 ALTER table auth_user_user_permissions ENABLE TRIGGER ALL;
979 ALTER table forum_keyvalue ENABLE TRIGGER ALL;
980 ALTER table forum_action ENABLE TRIGGER ALL;
981 ALTER table forum_actionrepute ENABLE TRIGGER ALL;
982 ALTER table forum_subscriptionsettings ENABLE TRIGGER ALL;
983 ALTER table forum_validationhash ENABLE TRIGGER ALL;
984 ALTER table forum_authkeyuserassociation ENABLE TRIGGER ALL;
985 ALTER table forum_tag ENABLE TRIGGER ALL;
986 ALTER table forum_markedtag ENABLE TRIGGER ALL;
987 ALTER table forum_node ENABLE TRIGGER ALL;
988 ALTER table forum_nodestate ENABLE TRIGGER ALL;
989 ALTER table forum_node_tags ENABLE TRIGGER ALL;
990 ALTER table forum_noderevision ENABLE TRIGGER ALL;
991 ALTER table forum_node_tags ENABLE TRIGGER ALL;
992 ALTER table forum_questionsubscription ENABLE TRIGGER ALL;
993 ALTER table forum_vote ENABLE TRIGGER ALL;
994 ALTER table forum_flag ENABLE TRIGGER ALL;
995 ALTER table forum_badge ENABLE TRIGGER ALL;
996 ALTER table forum_award ENABLE TRIGGER ALL;
997 ALTER table forum_openidnonce ENABLE TRIGGER ALL;
998 ALTER table forum_openidassociation ENABLE TRIGGER ALL;
999 """
1000
1001 PG_SEQUENCE_RESETS = """
1002 SELECT setval('"auth_user_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "auth_user";
1003 SELECT setval('"auth_user_groups_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "auth_user_groups";
1004 SELECT setval('"auth_user_user_permissions_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "auth_user_user_permissions";
1005 SELECT setval('"forum_keyvalue_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_keyvalue";
1006 SELECT setval('"forum_action_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_action";
1007 SELECT setval('"forum_actionrepute_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_actionrepute";
1008 SELECT setval('"forum_subscriptionsettings_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_subscriptionsettings";
1009 SELECT setval('"forum_validationhash_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_validationhash";
1010 SELECT setval('"forum_authkeyuserassociation_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_authkeyuserassociation";
1011 SELECT setval('"forum_tag_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_tag";
1012 SELECT setval('"forum_markedtag_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_markedtag";
1013 SELECT setval('"forum_node_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_node";
1014 SELECT setval('"forum_nodestate_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_nodestate";
1015 SELECT setval('"forum_node_tags_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_node_tags";
1016 SELECT setval('"forum_noderevision_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_noderevision";
1017 SELECT setval('"forum_node_tags_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_node_tags";
1018 SELECT setval('"forum_questionsubscription_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_questionsubscription";
1019 SELECT setval('"forum_vote_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_vote";
1020 SELECT setval('"forum_flag_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_flag";
1021 SELECT setval('"forum_badge_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_badge";
1022 SELECT setval('"forum_award_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_award";
1023 SELECT setval('"forum_openidnonce_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_openidnonce";
1024 SELECT setval('"forum_openidassociation_id_seq"', coalesce(max("id"), 1) + 2, max("id") IS NOT null) FROM "forum_openidassociation";
1025 """
1026
1027
1028     
1029