1 from __future__ import with_statement
3 import os, tarfile, datetime, logging, re, ConfigParser, shutil, zipfile
5 from django.core.cache import cache
6 from django.utils.translation import ugettext as _
7 from forum.models import *
8 from forum.settings import APP_URL
9 from forum.templatetags.extra_tags import diff_date
10 import xml.etree.ElementTree
11 from xml.etree import ElementTree as ET
12 from xml.etree.ElementTree import Comment, _encode, ProcessingInstruction, QName, _escape_attrib, _escape_cdata, _namespace_map
13 from forum import settings
14 from django.conf import settings as djsettings
15 import settings as selfsettings
19 from xml.etree.ElementTree import fixtag
21 def fixtag(tag, namespaces):
22 # given a decorated tag (of the form {uri}tag), return prefixed
23 # tag and namespace declaration, if any
24 if isinstance(tag, QName):
26 namespace_uri, tag = string.split(tag[1:], "}", 1)
27 prefix = namespaces.get(namespace_uri)
29 prefix = _namespace_map.get(namespace_uri)
31 prefix = "ns%d" % len(namespaces)
32 namespaces[namespace_uri] = prefix
36 xmlns = ("xmlns:%s" % prefix, namespace_uri)
39 return "%s:%s" % (prefix, tag), xmlns
41 CACHE_KEY = "%s_exporter_state" % APP_URL
44 TMP_FOLDER = os.path.join(os.path.dirname(__file__), 'tmp')
46 DATE_AND_AUTHOR_INF_SECTION = 'DateAndAuthor'
47 OPTIONS_INF_SECTION = 'Options'
48 META_INF_SECTION = 'Meta'
50 DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
51 DATE_FORMAT = "%Y-%m-%d"
53 def Etree_pretty__write(self, file, node, encoding, namespaces,
54 level=0, identator=" "):
57 file.write(level * identator + "<!-- %s -->" % _escape_cdata(node.text, encoding))
58 elif tag is ProcessingInstruction:
59 file.write("<?%s?>" % _escape_cdata(node.text, encoding))
62 xmlns_items = [] # new namespaces in this scope
64 if isinstance(tag, QName) or tag[:1] == "{":
65 tag, xmlns = fixtag(tag, namespaces)
66 if xmlns: xmlns_items.append(xmlns)
68 raise #_raise_serialization_error(tag)
69 file.write("\n" + level * identator + "<" + _encode(tag, encoding))
70 if items or xmlns_items:
71 items.sort() # lexical order
74 if isinstance(k, QName) or k[:1] == "{":
75 k, xmlns = fixtag(k, namespaces)
76 if xmlns: xmlns_items.append(xmlns)
78 raise #_raise_serialization_error(k)
80 if isinstance(v, QName):
81 v, xmlns = fixtag(v, namespaces)
82 if xmlns: xmlns_items.append(xmlns)
84 raise #_raise_serialization_error(v)
85 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
86 _escape_attrib(v, encoding)))
87 for k, v in xmlns_items:
88 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
89 _escape_attrib(v, encoding)))
90 if node.text or len(node):
93 file.write(_escape_cdata(node.text, encoding))
95 self._write(file, n, encoding, namespaces, level + 1, identator)
96 if node.text and len(node.text) < 125:
97 file.write("</" + _encode(tag, encoding) + ">")
99 file.write("\n" + level * identator + "</" + _encode(tag, encoding) + ">")
102 for k, v in xmlns_items:
105 file.write(_escape_cdata(node.tail.replace("\n", (level * identator )+ "\n"), encoding))
107 def make_date(date, with_time=True):
109 return date.strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
110 except ValueError, e:
111 return date.replace(year=1900).strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
114 def ET_Element_add_tag(el, tag_name, content = None, **attrs):
115 tag = ET.SubElement(el, tag_name)
119 tag.text = unicode(content)
121 #logging.error('error converting unicode characters')
123 #logging.error(traceback.print_exc())
126 tag.text = unicode("".join([c for c in content if c in string.printable]))
128 for k, v in attrs.items():
129 tag.set(k, unicode(v))
133 GOOD_TAG_NAME = re.compile("^\w+$")
135 def make_extra(el, v):
140 if isinstance(v, (int, long, str, unicode, float, bool, dict, list, tuple)):
141 if isinstance(v, tuple):
144 t = v.__class__.__name__
148 value = el.add('value', type=t)
150 if isinstance(v, (list, tuple)):
152 item = value.add('item')
155 elif isinstance(v, dict):
156 for k, i in v.items():
157 item = value.add('item', key=k)
160 value.text = unicode(v)
162 def write_to_file(root, tmp, filename):
163 tree = ET.ElementTree(root)
164 tree.write(os.path.join(tmp, filename), encoding='UTF-8')
166 def create_targz(tmp, files, start_time, options, user, state, set_state, file_format):
167 now = datetime.datetime.now()
168 domain = re.match('[\w-]+\.[\w-]+(\.[\w-]+)*', djsettings.APP_URL)
170 domain = '_'.join(domain.get(0).split('.'))
174 fname = "%s-%s" % (domain, now.strftime('%Y%m%d%H%M'))
175 if file_format == 'zip':
176 full_fname = "%s.zip" % fname
178 full_fname = "%s.tar.gz" % fname
180 if file_format == 'zip':
181 t = zipfile.ZipFile(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), 'w')
183 def add_to_file(f, a):
186 t = tarfile.open(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), mode = 'w:gz')
188 def add_to_file(f, a):
191 state['overall']['status'] = _('Compressing xml files')
195 add_to_file(os.path.join(tmp, f), "/%s" % f)
197 if options.get('uplodaded_files', False):
198 state['overall']['status'] = _('Importing uploaded files')
202 if options.get('import_skins_folder', False):
203 state['overall']['status'] = _('Importing skins folder')
205 export_skinsfolder(t)
207 state['overall']['status'] = _('Writing inf file.')
210 inf = ConfigParser.SafeConfigParser()
212 inf.add_section(DATE_AND_AUTHOR_INF_SECTION)
214 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'file-name', full_fname)
215 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'author', unicode(user.id))
216 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'site', djsettings.APP_URL)
217 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'started', start_time.strftime(DATETIME_FORMAT))
218 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'finished', now.strftime(DATETIME_FORMAT))
220 inf.add_section(OPTIONS_INF_SECTION)
221 inf.set(OPTIONS_INF_SECTION, 'anon-data', str(options.get('anon_data', False)))
222 inf.set(OPTIONS_INF_SECTION, 'with-upfiles', str(options.get('uplodaded_files', False)))
223 inf.set(OPTIONS_INF_SECTION, 'with-skins', str(options.get('import_skins_folder', False)))
225 inf.add_section(META_INF_SECTION)
227 for id, s in state.items():
228 inf.set(META_INF_SECTION, id, str(s['count']))
230 with open(os.path.join(tmp, '%s.backup.inf' % fname), 'wb') as inffile:
233 add_to_file(os.path.join(tmp, '%s.backup.inf' % fname), '/backup.inf')
234 state['overall']['status'] = _('Saving backup file')
240 def export_upfiles(tf):
241 folder = str(settings.UPFILES_FOLDER)
243 if os.path.exists(folder):
244 tf.add(folder, arcname='/upfiles')
247 def export_skinsfolder(tf):
248 folder = djsettings.TEMPLATE_DIRS[0]
250 if os.path.exists(folder):
251 tf.add(folder, arcname='/skins')
254 def export(options, user):
255 original__write = xml.etree.ElementTree.ElementTree.write
256 xml.etree.ElementTree.ElementTree._write = Etree_pretty__write
257 xml.etree.ElementTree._ElementInterface.add = ET_Element_add_tag
259 start_time = datetime.datetime.now()
261 anon_data = options.get('anon_data', False)
263 steps = [s for s in EXPORT_STEPS if not (anon_data and s['fn'].is_user_data())]
265 state = dict([(s['id'], {
266 'status': _('Queued'), 'count': s['fn'].count(start_time), 'parsed': 0
267 }) for s in steps] + [
269 'status': _('Starting'), 'count': sum([s['fn'].count(start_time) for s in steps]), 'parsed': 0
273 full_state = dict(running=True, state=state, time_started="")
276 full_state['time_started'] = diff_date(start_time)
277 cache.set(CACHE_KEY, full_state)
281 def ping_state(name):
282 state[name]['parsed'] += 1
283 state['overall']['parsed'] += 1
290 state['overall']['status'] = _('Exporting %s') % s['name']
291 state[name]['status'] = _('Exporting')
293 root, fname = fn(ping, start_time, anon_data)
295 state[name]['status'] = _('Writing temp file')
296 state['overall']['status'] = _('Writing %s temp file') % s['name']
300 write_to_file(root, tmp, fname)
301 state[name]['status'] = _('Done')
311 dump_files.append(run(s['fn'], s['id']))
313 state['overall']['status'] = _('Compressing files')
316 fname = create_targz(tmp, dump_files, start_time, options, user, state, set_state, options['file_format'])
317 full_state['running'] = False
318 full_state['errors'] = False
319 state['overall']['status'] = _('Done')
320 state['overall']['fname'] = fname
324 full_state['running'] = False
325 full_state['errors'] = "%s: %s" % (e.__class__.__name__, unicode(e))
329 logging.error("Error executing xml backup: \n %s" % (traceback.format_exc()))
331 xml.etree.ElementTree.ElementTree._write = original__write
332 del xml.etree.ElementTree._ElementInterface.add
335 def exporter_step(queryset, root_tag_name, el_tag_name, name, date_lock=None, user_data=False):
340 return queryset.filter(**{"%s__lte" % date_lock: lock})
343 def decorated(ping, lock, anon_data):
344 root = ET.Element(root_tag_name)
346 for item in qs(lock).order_by('id').select_related():
347 el = root.add(el_tag_name)
348 fn(item, el, anon_data)
351 return root, "%s.xml" % root_tag_name
354 return qs(lock).count()
359 decorated.count = count
360 decorated.is_user_data = is_user_data
362 EXPORT_STEPS.append(dict(id=root_tag_name, name=name, fn=decorated))
368 @exporter_step(Tag.objects.all(), 'tags', 'tag', _('Tags'))
369 def export_tags(t, el, anon_data):
370 el.add('name', t.name)
372 el.add('author', t.created_by.id)
373 el.add('used', t.used_count)
376 @exporter_step(User.objects.all(), 'users', 'user', _('Users'), 'date_joined', True)
377 def export_users(u, el, anon_data):
379 el.add('username', u.username)
380 el.add('password', u.password)
381 el.add('email', u.email, validated=u.email_isvalid and 'true' or 'false')
382 el.add('reputation', u.reputation)
383 el.add('badges', bronze=u.bronze, silver=u.silver, gold=u.gold)
384 el.add('joindate', make_date(u.date_joined))
385 el.add('active', u.is_active and 'true' or 'false')
387 el.add('realname', u.real_name)
388 el.add('bio', u.about)
389 el.add('location', u.location)
390 el.add('website', u.website)
391 el.add('birthdate', u.date_of_birth and make_date(u.date_of_birth, with_time=False) or "")
393 roles = el.add('roles')
396 roles.add('role', 'superuser')
399 roles.add('role', 'moderator')
401 auth = el.add('authKeys')
402 for a in u.auth_keys.all():
403 key = auth.add('key')
404 key.add('provider', a.provider)
405 key.add('key', a.key)
408 ss = u.subscription_settings
410 notify = el.add('notifications', enabled=ss.enable_notifications and 'true' or 'false')
412 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']]))
414 notify.add('autoSubscribe', **dict([(t, ss.__dict__.get(t, False) and 'true' or 'false') for t in [
415 'all_questions', 'all_questions_watched_tags', 'questions_asked', 'questions_answered', 'questions_commented', 'questions_viewed']]))
417 notify.add('notifyOnSubscribed', **dict([(t, ss.__dict__.get("notify_%s" % t, False) and 'true' or 'false') for t in [
418 'answers', 'reply_to_comments', 'comments_own_post', 'comments', 'accepted']]))
420 notify.add('digest', ss.send_digest and 'on' or 'off')
421 except SubscriptionSettings.DoesNotExist:
424 watched = el.add('watchedTags')
425 rejected = el.add('rejectedTags')
427 for m in u.tag_selections.all():
428 if m.reason == 'good':
429 watched.add('tag', m.tag.name)
431 rejected.add('tag', m.tag.name)
435 @exporter_step(Node.objects.all(), 'nodes', 'node', _('Nodes'), 'added_at')
436 def export_nodes(n, el, anon_data):
438 el.add('type', n.node_type)
441 el.add('author', n.author.id)
442 el.add('date', make_date(n.added_at))
443 el.add('parent', n.parent and n.parent.id or "")
444 el.add('absparent', n.abs_parent and n.abs_parent.id or "")
446 act = el.add('lastactivity')
447 act.add('by', n.last_activity_by and n.last_activity_by.id or "")
448 act.add('at', n.last_activity_at and make_date(n.last_activity_at) or "")
450 el.add('title', n.title)
451 el.add('body', n.body)
453 el.add('score', n.score)
455 tags = el.add('tags')
457 for t in n.tagname_list():
461 active = n.active_revision and n.active_revision.revision or n.revisions.order_by('revision')[0].revision
465 revs = el.add('revisions', active=active)
467 for r in n.revisions.order_by('revision'):
468 rev = revs.add('revision')
469 rev.add('number', r.revision)
470 rev.add('summary', r.summary)
472 rev.add('author', r.author.id)
473 rev.add('date', make_date(r.revised_at))
475 rev.add('title', r.title)
476 rev.add('body', r.body)
477 rev.add('tags', ", ".join(r.tagname_list()))
479 el.add('marked', n.marked and 'true' or 'false')
480 el.add('wiki', n.nis.wiki and 'true' or 'false')
481 el.add('extraRef', n.extra_ref and n.extra_ref.id or "")
482 make_extra(el.add('extraData'), n.extra)
483 el.add('extraCount', n.extra_count and n.extra_count or "")
486 @exporter_step(Action.objects.all(), 'actions', 'action', _('Actions'), 'action_date')
487 def export_actions(a, el, anon_data):
489 el.add('type', a.action_type)
490 el.add('date', make_date(a.action_date))
493 el.add('user', a.user.id)
494 el.add('realUser', a.real_user and a.real_user.id or "")
496 el.add('node', a.node and a.node.id or "")
498 make_extra(el.add('extraData'), a.extra)
500 canceled = el.add('canceled', state=a.canceled and 'true' or 'false')
504 canceled.add('user', a.canceled_by.id)
505 canceled.add('ip', a.canceled_ip)
507 canceled.add('date', make_date(a.canceled_at))
510 reputes = el.add('reputes')
512 for r in a.reputes.all():
513 repute = reputes.add('repute', byCanceled=r.by_canceled and 'true' or 'false')
514 repute.add('user', r.user.id)
515 repute.add('value', r.value)
518 #@exporter_step(NodeState.objects.all(), 'states', 'state', _('Node states'), 'action__action_date')
519 #def export_states(s, el, anon_data):
520 # el.add('type', s.state_type)
521 # el.add('node', s.node.id)
522 # el.add('trigger', s.action.id)
525 #@exporter_step(Badge.objects.all(), 'badges', 'badge', _('Badges'), user_data=True)
526 #def export_badges(b, el, anon_data):
527 # el.add('type', ["", 'gold', 'silver', 'bronze'][b.type])
528 # el.add('name', b.cls)
529 # el.add('count', b.awarded_count)
532 @exporter_step(Award.objects.all(), 'awards', 'award', _('Awards'), 'awarded_at', True)
533 def export_awards(a, el, anon_data):
534 el.add('badge', a.badge.cls)
535 el.add('user', a.user.id)
536 el.add('node', a.node and a.node.id or "")
537 el.add('trigger', a.trigger and a.trigger.id or "")
538 el.add('action', a.action.id)
540 @exporter_step(KeyValue.objects.all(), 'settings', 'setting', _('Settings'))
541 def export_settings(s, el, anon_data):
543 make_extra(el.add('value'), s.value)