"""Generate a WordPress eXtended RSS (WXR) export from this blog's data. The output is a standard WXR 1.2 feed — the same format WordPress's own "Import" tool reads. Posts become elements; categories and tags are expressed as / domain="post_tag">; comments appear as blocks inside their post's item. Only published posts are exported (option a: text only, images left in place — their URLs keep pointing at the source host). Pure logic, stdlib only, so it can be unit-tested without an HTTP server or database. """ import re from datetime import datetime, timezone # Characters that are not legal in XML 1.0: a body pasted from another system # could contain them and make the exported file unparseable. _INVALID_XML = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f]") # WXR namespaces. The order here controls prefix order in the emitted output. NS = [ ("excerpt", "http://wordpress.org/export/1.2/excerpt/"), ("content", "http://purl.org/rss/1.0/modules/content/"), ("wfw", "http://wellformedweb.org/CommentAPI/"), ("dc", "http://purl.org/dc/elements/1.1/"), ("wp", "http://wordpress.com/export/1.2/"), ("slash", "http://slashworks.org/rss/1.0/"), ] def _xml_escape(value): """Escape a value for use as element text (not attributes).""" if value is None: return "" return (_INVALID_XML.sub("", str(value)) .replace("&", "&") .replace("<", "<") .replace(">", ">")) def _attr_escape(value): """Escape a value for use inside an attribute.""" if value is None: return "" return (_INVALID_XML.sub("", str(value)) .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace('"', """) .replace("'", "'")) def _rfc822(dt): """Format a datetime as an RFC 822 date, as / expect.""" return dt.strftime("%a, %d %b %Y %H:%M:%S +0000") def _post_url(site_url, slug): return f"{site_url.rstrip('/')}/post/{slug}" def _comment_dt(comment): """A comment's own timestamp. Every comment used to carry the *post's* date, which made the exported feed claim all comments were written when the post was published. """ try: return datetime.strptime(comment["created_at"], "%Y-%m-%d %H:%M:%S") except (KeyError, ValueError, TypeError): return datetime.now(timezone.utc).replace(tzinfo=None) def build_wxr(db, site_title, site_url, site_description): """Return the WXR document as a string. `db` must be an open sqlite3 connection; `site_title`, `site_url` and `site_description` describe the channel (the WordPress importer needs them). """ posts = db.execute( "SELECT * FROM posts WHERE status = 'published' ORDER BY created_at DESC" ).fetchall() # name -> slug, for turning WXR category names back into our category slugs. cat_by_name = {slug: name for slug, name in db.execute("SELECT slug, name FROM categories").fetchall()} # Channel metadata comes first (WordPress's importer needs it before any # ), so build everything into one list in document order. out = [] out.append('') out.append( '' ) out.append(" ") out.append(f" {_xml_escape(site_title)}") out.append(f" {_xml_escape(site_url.rstrip('/'))}") out.append(f" {_xml_escape(site_description)}") out.append(' en_US') out.append(' http://blogs.law.harvard.edu/tech/rss') out.append(' Simple Blog WXR Export') for p in posts: url = _post_url(site_url, p["slug"]) created = datetime.strptime(p["created_at"], "%Y-%m-%d %H:%M:%S") out.append(" ") wxr_status = "publish" if p["status"] == "published" else "draft" out.append(f' {_xml_escape(wxr_status)}') out.append(f' {_xml_escape(p["slug"])}') out.append(f" {_xml_escape(p['title'])}") out.append(f" {_xml_escape(url)}") out.append(f' {_xml_escape(url)}') out.append( f' {_xml_escape(p["author"] or "editor")}' ) out.append(f" {_rfc822(created)}") out.append(f" {_rfc822(created)}") categories, tags = [], [] for cat in (p["category"] or "").split(","): cat = cat.strip() if not cat: continue slug_ = cat_by_name.get(cat, cat) categories.append(slug_) for tag in (p["tags"] or "").split(","): tag = tag.strip() if tag: tags.append(tag) for slug_ in categories: out.append( f' {_xml_escape(slug_)}' ) for tag in tags: out.append( f' {_xml_escape(tag)}' ) # Comments attached to this post. comments = db.execute( "SELECT * FROM comments WHERE object_type = 'post' AND object_id = ? " "ORDER BY created_at", (p["id"],)).fetchall() for c in comments: comment_link = url + f"#c{c['id']}" attrs = [ f'ID="{c["id"]}"', f'author="{_attr_escape(c["author"] or "")}"', f'author_email="{_attr_escape(c["email"] or "")}"', 'author_url=""', f'date_time_gmt="{_rfc822(_comment_dt(c))}"', 'comment_type=""', 'status="approved"', f'permalink="{_attr_escape(comment_link)}"', ] out.append(' ') out.append(f" {_xml_escape(c['body'])}") out.append(" ") out.append(f' {_xml_escape(url + "#comments")}') out.append(f" {len(comments)}") out.append(f" {_xml_escape(p['body'])}") out.append(" ") out.append(" ") out.append("") return "\n".join(out)