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 if isinstance(tf, zipfile.ZipFile):
245 tf.write(folder, arcname='/upfiles')
247 tf.add(folder, arcname='/upfiles')
250 def export_skinsfolder(tf):
251 folder = djsettings.TEMPLATE_DIRS[0]
253 if os.path.exists(folder):
254 if isinstance(tf, zipfile.ZipFile):
255 tf.write(folder, arcname='/skins')
257 tf.add(folder, arcname='/skins')
260 def export(options, user):
261 original__write = xml.etree.ElementTree.ElementTree.write
262 xml.etree.ElementTree.ElementTree._write = Etree_pretty__write
263 xml.etree.ElementTree._ElementInterface.add = ET_Element_add_tag
265 start_time = datetime.datetime.now()
267 anon_data = options.get('anon_data', False)
269 steps = [s for s in EXPORT_STEPS if not (anon_data and s['fn'].is_user_data())]
271 state = dict([(s['id'], {
272 'status': _('Queued'), 'count': s['fn'].count(start_time), 'parsed': 0
273 }) for s in steps] + [
275 'status': _('Starting'), 'count': sum([s['fn'].count(start_time) for s in steps]), 'parsed': 0
279 full_state = dict(running=True, state=state, time_started="")
282 full_state['time_started'] = diff_date(start_time)
283 cache.set(CACHE_KEY, full_state)
287 def ping_state(name):
288 state[name]['parsed'] += 1
289 state['overall']['parsed'] += 1
296 state['overall']['status'] = _('Exporting %s') % s['name']
297 state[name]['status'] = _('Exporting')
299 root, fname = fn(ping, start_time, anon_data)
301 state[name]['status'] = _('Writing temp file')
302 state['overall']['status'] = _('Writing %s temp file') % s['name']
306 write_to_file(root, tmp, fname)
307 state[name]['status'] = _('Done')
317 dump_files.append(run(s['fn'], s['id']))
319 state['overall']['status'] = _('Compressing files')
322 fname = create_targz(tmp, dump_files, start_time, options, user, state, set_state, options['file_format'])
323 full_state['running'] = False
324 full_state['errors'] = False
325 state['overall']['status'] = _('Done')
326 state['overall']['fname'] = fname
330 full_state['running'] = False
331 full_state['errors'] = "%s: %s" % (e.__class__.__name__, unicode(e))
335 logging.error("Error executing xml backup: \n %s" % (traceback.format_exc()))
337 xml.etree.ElementTree.ElementTree._write = original__write
338 del xml.etree.ElementTree._ElementInterface.add
341 def exporter_step(queryset, root_tag_name, el_tag_name, name, date_lock=None, user_data=False):
346 return queryset.filter(**{"%s__lte" % date_lock: lock})
349 def decorated(ping, lock, anon_data):
350 root = ET.Element(root_tag_name)
352 for item in qs(lock).order_by('id').select_related():
353 el = root.add(el_tag_name)
354 fn(item, el, anon_data)
357 return root, "%s.xml" % root_tag_name
360 return qs(lock).count()
365 decorated.count = count
366 decorated.is_user_data = is_user_data
368 EXPORT_STEPS.append(dict(id=root_tag_name, name=name, fn=decorated))
374 @exporter_step(Tag.objects.all(), 'tags', 'tag', _('Tags'))
375 def export_tags(t, el, anon_data):
376 el.add('name', t.name)
378 el.add('author', t.created_by.id)
379 el.add('used', t.used_count)
382 @exporter_step(User.objects.all(), 'users', 'user', _('Users'), 'date_joined', True)
383 def export_users(u, el, anon_data):
385 el.add('username', u.username)
386 el.add('password', u.password)
387 el.add('email', u.email, validated=u.email_isvalid and 'true' or 'false')
388 el.add('reputation', u.reputation)
389 el.add('badges', bronze=u.bronze, silver=u.silver, gold=u.gold)
390 el.add('joindate', make_date(u.date_joined))
391 el.add('active', u.is_active and 'true' or 'false')
393 el.add('realname', u.real_name)
394 el.add('bio', u.about)
395 el.add('location', u.location)
396 el.add('website', u.website)
397 el.add('birthdate', u.date_of_birth and make_date(u.date_of_birth, with_time=False) or "")
399 roles = el.add('roles')
402 roles.add('role', 'superuser')
405 roles.add('role', 'moderator')
407 auth = el.add('authKeys')
408 for a in u.auth_keys.all():
409 key = auth.add('key')
410 key.add('provider', a.provider)
411 key.add('key', a.key)
414 ss = u.subscription_settings
416 notify = el.add('notifications', enabled=ss.enable_notifications and 'true' or 'false')
418 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']]))
420 notify.add('autoSubscribe', **dict([(t, ss.__dict__.get(t, False) and 'true' or 'false') for t in [
421 'all_questions', 'all_questions_watched_tags', 'questions_asked', 'questions_answered', 'questions_commented', 'questions_viewed']]))
423 notify.add('notifyOnSubscribed', **dict([(t, ss.__dict__.get("notify_%s" % t, False) and 'true' or 'false') for t in [
424 'answers', 'reply_to_comments', 'comments_own_post', 'comments', 'accepted']]))
426 notify.add('digest', ss.send_digest and 'on' or 'off')
427 except SubscriptionSettings.DoesNotExist:
430 watched = el.add('watchedTags')
431 rejected = el.add('rejectedTags')
433 for m in u.tag_selections.all():
435 if m.reason == 'good':
436 watched.add('tag', m.tag.name)
438 rejected.add('tag', m.tag.name)
439 except Tag.DoesNotExist:
444 @exporter_step(Node.objects.all(), 'nodes', 'node', _('Nodes'), 'added_at')
445 def export_nodes(n, el, anon_data):
447 el.add('type', n.node_type)
450 el.add('author', n.author.id)
451 el.add('date', make_date(n.added_at))
452 el.add('parent', n.parent and n.parent.id or "")
453 el.add('absparent', n.abs_parent and n.abs_parent.id or "")
455 act = el.add('lastactivity')
456 act.add('by', n.last_activity_by and n.last_activity_by.id or "")
457 act.add('at', n.last_activity_at and make_date(n.last_activity_at) or "")
459 el.add('title', n.title)
460 el.add('body', n.body)
462 el.add('score', n.score)
464 tags = el.add('tags')
466 for t in n.tagname_list():
470 active = n.active_revision and n.active_revision.revision or n.revisions.order_by('revision')[0].revision
474 revs = el.add('revisions', active=active)
476 for r in n.revisions.order_by('revision'):
477 rev = revs.add('revision')
478 rev.add('number', r.revision)
479 rev.add('summary', r.summary)
481 rev.add('author', r.author.id)
482 rev.add('date', make_date(r.revised_at))
484 rev.add('title', r.title)
485 rev.add('body', r.body)
486 rev.add('tags', ", ".join(r.tagname_list()))
488 el.add('marked', n.marked and 'true' or 'false')
489 el.add('wiki', n.nis.wiki and 'true' or 'false')
490 el.add('extraRef', n.extra_ref and n.extra_ref.id or "")
491 make_extra(el.add('extraData'), n.extra)
492 el.add('extraCount', n.extra_count and n.extra_count or "")
495 @exporter_step(Action.objects.all(), 'actions', 'action', _('Actions'), 'action_date')
496 def export_actions(a, el, anon_data):
498 el.add('type', a.action_type)
499 el.add('date', make_date(a.action_date))
502 el.add('user', a.user.id)
503 el.add('realUser', a.real_user and a.real_user.id or "")
505 el.add('node', a.node and a.node.id or "")
507 make_extra(el.add('extraData'), a.extra)
509 canceled = el.add('canceled', state=a.canceled and 'true' or 'false')
513 canceled.add('user', a.canceled_by.id)
514 canceled.add('ip', a.canceled_ip)
516 canceled.add('date', make_date(a.canceled_at))
519 reputes = el.add('reputes')
521 for r in a.reputes.all():
522 repute = reputes.add('repute', byCanceled=r.by_canceled and 'true' or 'false')
523 repute.add('user', r.user.id)
524 repute.add('value', r.value)
527 #@exporter_step(NodeState.objects.all(), 'states', 'state', _('Node states'), 'action__action_date')
528 #def export_states(s, el, anon_data):
529 # el.add('type', s.state_type)
530 # el.add('node', s.node.id)
531 # el.add('trigger', s.action.id)
534 #@exporter_step(Badge.objects.all(), 'badges', 'badge', _('Badges'), user_data=True)
535 #def export_badges(b, el, anon_data):
536 # el.add('type', ["", 'gold', 'silver', 'bronze'][b.type])
537 # el.add('name', b.cls)
538 # el.add('count', b.awarded_count)
541 @exporter_step(Award.objects.all(), 'awards', 'award', _('Awards'), 'awarded_at', True)
542 def export_awards(a, el, anon_data):
543 el.add('badge', a.badge.cls)
544 el.add('user', a.user.id)
545 el.add('node', a.node and a.node.id or "")
546 el.add('trigger', a.trigger and a.trigger.id or "")
547 el.add('action', a.action.id)
549 @exporter_step(KeyValue.objects.all(), 'settings', 'setting', _('Settings'))
550 def export_settings(s, el, anon_data):
552 make_extra(el.add('value'), s.value)