1 import os, tarfile, datetime, logging, re, ConfigParser, shutil, zipfile
3 from django.core.cache import cache
4 from django.utils.translation import ugettext as _
5 from forum.models import *
6 from forum.settings import APP_URL
7 from forum.templatetags.extra_tags import diff_date
8 import xml.etree.ElementTree
9 from xml.etree import ElementTree as ET
10 from xml.etree.ElementTree import Comment, _encode, ProcessingInstruction, QName, fixtag, _escape_attrib, _escape_cdata
11 from forum import settings
12 from django.conf import settings as djsettings
13 import settings as selfsettings
15 # Try to import the with statement
17 from __future__ import with_statement
21 CACHE_KEY = "%s_exporter_state" % APP_URL
24 TMP_FOLDER = os.path.join(os.path.dirname(__file__), 'tmp')
26 DATE_AND_AUTHOR_INF_SECTION = 'DateAndAuthor'
27 OPTIONS_INF_SECTION = 'Options'
28 META_INF_SECTION = 'Meta'
30 DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
31 DATE_FORMAT = "%Y-%m-%d"
33 def Etree_pretty__write(self, file, node, encoding, namespaces,
34 level=0, identator=" "):
37 file.write(level * identator + "<!-- %s -->" % _escape_cdata(node.text, encoding))
38 elif tag is ProcessingInstruction:
39 file.write("<?%s?>" % _escape_cdata(node.text, encoding))
42 xmlns_items = [] # new namespaces in this scope
44 if isinstance(tag, QName) or tag[:1] == "{":
45 tag, xmlns = fixtag(tag, namespaces)
46 if xmlns: xmlns_items.append(xmlns)
48 raise #_raise_serialization_error(tag)
49 file.write("\n" + level * identator + "<" + _encode(tag, encoding))
50 if items or xmlns_items:
51 items.sort() # lexical order
54 if isinstance(k, QName) or k[:1] == "{":
55 k, xmlns = fixtag(k, namespaces)
56 if xmlns: xmlns_items.append(xmlns)
58 raise #_raise_serialization_error(k)
60 if isinstance(v, QName):
61 v, xmlns = fixtag(v, namespaces)
62 if xmlns: xmlns_items.append(xmlns)
64 raise #_raise_serialization_error(v)
65 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
66 _escape_attrib(v, encoding)))
67 for k, v in xmlns_items:
68 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
69 _escape_attrib(v, encoding)))
70 if node.text or len(node):
73 file.write(_escape_cdata(node.text, encoding))
75 self._write(file, n, encoding, namespaces, level + 1, identator)
76 if node.text and len(node.text) < 125:
77 file.write("</" + _encode(tag, encoding) + ">")
79 file.write("\n" + level * identator + "</" + _encode(tag, encoding) + ">")
82 for k, v in xmlns_items:
85 file.write(_escape_cdata(node.tail.replace("\n", (level * identator )+ "\n"), encoding))
87 def make_date(date, with_time=True):
89 return date.strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
91 return date.replace(year=1900).strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
94 def ET_Element_add_tag(el, tag_name, content = None, **attrs):
95 tag = ET.SubElement(el, tag_name)
99 tag.text = unicode(content)
103 for k, v in attrs.items():
104 tag.set(k, unicode(v))
108 GOOD_TAG_NAME = re.compile("^\w+$")
110 def make_extra(el, v):
115 if isinstance(v, (int, long, str, unicode, float, bool, dict, list, tuple)):
116 if isinstance(v, tuple):
119 t = v.__class__.__name__
123 value = el.add('value', type=t)
125 if isinstance(v, (list, tuple)):
127 item = value.add('item')
130 elif isinstance(v, dict):
131 for k, i in v.items():
132 item = value.add('item', key=k)
135 value.text = unicode(v)
137 def write_to_file(root, tmp, filename):
138 tree = ET.ElementTree(root)
139 tree.write(os.path.join(tmp, filename), encoding='UTF-8')
141 def create_targz(tmp, files, start_time, options, user, state, set_state, file_format):
142 now = datetime.datetime.now()
143 domain = re.match('[\w-]+\.[\w-]+(\.[\w-]+)*', djsettings.APP_URL)
145 domain = '_'.join(domain.get(0).split('.'))
149 fname = "%s-%s" % (domain, now.strftime('%Y%m%d%H%M'))
150 if file_format == 'zip':
151 full_fname = "%s.zip" % fname
153 full_fname = "%s.tar.gz" % fname
155 if file_format == 'zip':
156 t = zipfile.ZipFile(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), 'w')
158 def add_to_file(f, a):
161 t = tarfile.open(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), mode = 'w:gz')
163 def add_to_file(f, a):
166 state['overall']['status'] = _('Compressing xml files')
170 add_to_file(os.path.join(tmp, f), "/%s" % f)
172 if options.get('uplodaded_files', False):
173 state['overall']['status'] = _('Importing uploaded files')
177 if options.get('import_skins_folder', False):
178 state['overall']['status'] = _('Importing skins folder')
180 export_skinsfolder(t)
182 state['overall']['status'] = _('Writing inf file.')
185 inf = ConfigParser.SafeConfigParser()
187 inf.add_section(DATE_AND_AUTHOR_INF_SECTION)
189 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'file-name', full_fname)
190 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'author', unicode(user.id))
191 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'site', djsettings.APP_URL)
192 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'started', start_time.strftime(DATETIME_FORMAT))
193 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'finished', now.strftime(DATETIME_FORMAT))
195 inf.add_section(OPTIONS_INF_SECTION)
196 inf.set(OPTIONS_INF_SECTION, 'anon-data', str(options.get('anon_data', False)))
197 inf.set(OPTIONS_INF_SECTION, 'with-upfiles', str(options.get('uplodaded_files', False)))
198 inf.set(OPTIONS_INF_SECTION, 'with-skins', str(options.get('import_skins_folder', False)))
200 inf.add_section(META_INF_SECTION)
202 for id, s in state.items():
203 inf.set(META_INF_SECTION, id, str(s['count']))
205 with open(os.path.join(tmp, '%s.backup.inf' % fname), 'wb') as inffile:
208 add_to_file(os.path.join(tmp, '%s.backup.inf' % fname), '/backup.inf')
209 state['overall']['status'] = _('Saving backup file')
215 def export_upfiles(tf):
216 folder = str(settings.UPFILES_FOLDER)
218 if os.path.exists(folder):
219 tf.add(folder, arcname='/upfiles')
222 def export_skinsfolder(tf):
223 folder = djsettings.TEMPLATE_DIRS[0]
225 if os.path.exists(folder):
226 tf.add(folder, arcname='/skins')
229 def export(options, user):
230 original__write = xml.etree.ElementTree.ElementTree._write
231 xml.etree.ElementTree.ElementTree._write = Etree_pretty__write
232 xml.etree.ElementTree._ElementInterface.add = ET_Element_add_tag
234 start_time = datetime.datetime.now()
236 anon_data = options.get('anon_data', False)
238 steps = [s for s in EXPORT_STEPS if not (anon_data and s['fn'].is_user_data())]
240 state = dict([(s['id'], {
241 'status': _('Queued'), 'count': s['fn'].count(start_time), 'parsed': 0
242 }) for s in steps] + [
244 'status': _('Starting'), 'count': sum([s['fn'].count(start_time) for s in steps]), 'parsed': 0
248 full_state = dict(running=True, state=state, time_started="")
251 full_state['time_started'] = diff_date(start_time)
252 cache.set(CACHE_KEY, full_state)
256 def ping_state(name):
257 state[name]['parsed'] += 1
258 state['overall']['parsed'] += 1
265 state['overall']['status'] = _('Exporting %s') % s['name']
266 state[name]['status'] = _('Exporting')
268 root, fname = fn(ping, start_time, anon_data)
270 state[name]['status'] = _('Writing temp file')
271 state['overall']['status'] = _('Writing %s temp file') % s['name']
275 write_to_file(root, tmp, fname)
276 state[name]['status'] = _('Done')
286 dump_files.append(run(s['fn'], s['id']))
288 state['overall']['status'] = _('Compressing files')
291 fname = create_targz(tmp, dump_files, start_time, options, user, state, set_state, options['file_format'])
292 full_state['running'] = False
293 full_state['errors'] = False
294 state['overall']['status'] = _('Done')
295 state['overall']['fname'] = fname
299 full_state['running'] = False
300 full_state['errors'] = "%s: %s" % (e.__class__.__name__, unicode(e))
304 logging.error("Error executing xml backup: \n %s" % (traceback.format_exc()))
306 xml.etree.ElementTree.ElementTree._write = original__write
307 del xml.etree.ElementTree._ElementInterface.add
310 def exporter_step(queryset, root_tag_name, el_tag_name, name, date_lock=None, user_data=False):
315 return queryset.filter(**{"%s__lte" % date_lock: lock})
318 def decorated(ping, lock, anon_data):
319 root = ET.Element(root_tag_name)
321 for item in qs(lock).order_by('id').select_related():
322 el = root.add(el_tag_name)
323 fn(item, el, anon_data)
326 return root, "%s.xml" % root_tag_name
329 return qs(lock).count()
334 decorated.count = count
335 decorated.is_user_data = is_user_data
337 EXPORT_STEPS.append(dict(id=root_tag_name, name=name, fn=decorated))
343 @exporter_step(Tag.objects.all(), 'tags', 'tag', _('Tags'))
344 def export_tags(t, el, anon_data):
345 el.add('name', t.name)
347 el.add('author', t.created_by.id)
348 el.add('used', t.used_count)
351 @exporter_step(User.objects.all(), 'users', 'user', _('Users'), 'date_joined', True)
352 def export_users(u, el, anon_data):
354 el.add('username', u.username)
355 el.add('password', u.password)
356 el.add('email', u.email, validated=u.email_isvalid and 'true' or 'false')
357 el.add('reputation', u.reputation)
358 el.add('badges', bronze=u.bronze, silver=u.silver, gold=u.gold)
359 el.add('joindate', make_date(u.date_joined))
360 el.add('active', u.is_active and 'true' or 'false')
362 el.add('realname', u.real_name)
363 el.add('bio', u.about)
364 el.add('location', u.location)
365 el.add('website', u.website)
366 el.add('birthdate', u.date_of_birth and make_date(u.date_of_birth, with_time=False) or "")
368 roles = el.add('roles')
371 roles.add('role', 'superuser')
374 roles.add('role', 'moderator')
376 auth = el.add('authKeys')
377 for a in u.auth_keys.all():
378 key = auth.add('key')
379 key.add('provider', a.provider)
380 key.add('key', a.key)
383 ss = u.subscription_settings
385 notify = el.add('notifications', enabled=ss.enable_notifications and 'true' or 'false')
387 notify.add('notify', **dict([(t, ss.__dict__.get(t, 'n') == 'i' and 'true' or 'false') for t in ['member_joins', 'new_question', 'new_question_watched_tags', 'subscribed_questions']]))
389 notify.add('autoSubscribe', **dict([(t, ss.__dict__.get(t, False) and 'true' or 'false') for t in [
390 'all_questions', 'all_questions_watched_tags', 'questions_asked', 'questions_answered', 'questions_commented', 'questions_viewed']]))
392 notify.add('notifyOnSubscribed', **dict([(t, ss.__dict__.get("notify_%s" % t, False) and 'true' or 'false') for t in [
393 'answers', 'reply_to_comments', 'comments_own_post', 'comments', 'accepted']]))
395 notify.add('digest', ss.send_digest and 'on' or 'off')
397 watched = el.add('watchedTags')
398 rejected = el.add('rejectedTags')
400 for m in u.tag_selections.all():
401 if m.reason == 'good':
402 watched.add('tag', m.tag.name)
404 rejected.add('tag', m.tag.name)
408 @exporter_step(Node.objects.all(), 'nodes', 'node', _('Nodes'), 'added_at')
409 def export_nodes(n, el, anon_data):
411 el.add('type', n.node_type)
414 el.add('author', n.author.id)
415 el.add('date', make_date(n.added_at))
416 el.add('parent', n.parent and n.parent.id or "")
417 el.add('absparent', n.abs_parent and n.abs_parent or "")
419 act = el.add('lastactivity')
420 act.add('by', n.last_activity_by and n.last_activity_by.id or "")
421 act.add('at', n.last_activity_at and make_date(n.last_activity_at) or "")
423 el.add('title', n.title)
424 el.add('body', n.body)
426 el.add('score', n.score)
428 tags = el.add('tags')
430 for t in n.tagname_list():
434 active = n.active_revision and n.active_revision.revision or n.revisions.order_by('revision')[0].revision
438 revs = el.add('revisions', active=active)
440 for r in n.revisions.order_by('revision'):
441 rev = revs.add('revision')
442 rev.add('number', r.revision)
443 rev.add('summary', r.summary)
445 rev.add('author', r.author.id)
446 rev.add('date', make_date(r.revised_at))
448 rev.add('title', r.title)
449 rev.add('body', r.body)
450 rev.add('tags', ", ".join(r.tagname_list()))
452 el.add('marked', n.marked and 'true' or 'false')
453 el.add('extraRef', n.extra_ref and n.extra_ref.id or "")
454 make_extra(el.add('extraData'), n.extra)
455 el.add('extraCount', n.extra_count and n.extra_count or "")
458 @exporter_step(Action.objects.all(), 'actions', 'action', _('Actions'), 'action_date')
459 def export_actions(a, el, anon_data):
461 el.add('type', a.action_type)
462 el.add('date', make_date(a.action_date))
465 el.add('user', a.user.id)
466 el.add('realUser', a.real_user and a.real_user.id or "")
468 el.add('node', a.node and a.node.id or "")
470 make_extra(el.add('extraData'), a.extra)
472 canceled = el.add('canceled', state=a.canceled and 'true' or 'false')
476 canceled.add('user', a.canceled_by.id)
477 canceled.add('ip', a.canceled_ip)
479 canceled.add('date', make_date(a.canceled_at))
482 reputes = el.add('reputes')
484 for r in a.reputes.all():
485 repute = reputes.add('repute', byCanceled=r.by_canceled and 'true' or 'false')
486 repute.add('user', r.user.id)
487 repute.add('value', r.value)
490 #@exporter_step(NodeState.objects.all(), 'states', 'state', _('Node states'), 'action__action_date')
491 #def export_states(s, el, anon_data):
492 # el.add('type', s.state_type)
493 # el.add('node', s.node.id)
494 # el.add('trigger', s.action.id)
497 #@exporter_step(Badge.objects.all(), 'badges', 'badge', _('Badges'), user_data=True)
498 #def export_badges(b, el, anon_data):
499 # el.add('type', ["", 'gold', 'silver', 'bronze'][b.type])
500 # el.add('name', b.cls)
501 # el.add('count', b.awarded_count)
504 @exporter_step(Award.objects.all(), 'awards', 'award', _('Awards'), 'awarded_at', True)
505 def export_awards(a, el, anon_data):
506 el.add('badge', a.badge.cls)
507 el.add('user', a.user.id)
508 el.add('node', a.node and a.node.id or "")
509 el.add('trigger', a.trigger and a.trigger.id or "")
510 el.add('action', a.action.id)
512 @exporter_step(KeyValue.objects.all(), 'settings', 'setting', _('Settings'))
513 def export_settings(s, el, anon_data):
515 make_extra(el.add('value'), s.value)