We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
import_wordpress problem with php code in blogpost
```
$ nikola import_wordpress /Users/davidak/Downloads/davidakweblog.wordpress.2016-02-23.xml
[2016-02-23T17:06:37Z] NOTICE: Nikola: The folder new_site already exists - assuming that this is a already existing Nikola site.
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/doit/doit_cmd.py", line 168, in run
    return command.parse_execute(args)
  File "/usr/local/lib/python3.5/site-packages/doit/cmd_base.py", line 122, in parse_execute
    return self.execute(params, args)
  File "/usr/local/lib/python3.5/site-packages/nikola/plugin_categories.py", line 124, in execute
    return self._execute(options, args)
  File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 332, in _execute
    self.import_posts(channel)
  File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 1015, in import_posts
    self.process_item_if_post_or_page(item)
  File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 996, in process_item_if_post_or_page
    out_folder_slug = self.import_postpage_item(item, wordpress_namespace, 'posts', attachments)
  File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 938, in import_postpage_item
    rewrite_html)
  File "/usr/local/lib/python3.5/site-packages/nikola/plugins/basic_import.py", line 130, in write_content
    doc = html.document_fromstring(content)
  File "/usr/local/lib/python3.5/site-packages/lxml/html/__init__.py", line 755, in document_fromstring
    "Document is empty")
lxml.etree.ParserError: Document is empty
```

wordpress export of the post:

```
<?xml version="1.0" encoding="UTF-8" ?>
<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->
<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->
<!-- You may use this file to transfer that content from one site to another. -->
<!-- This file is not intended to serve as a complete backup of your site. -->

<!-- To import this information into a WordPress site follow these steps: -->
<!-- 1. Log in to that site as an administrator. -->
<!-- 2. Go to Tools: Import in the WordPress admin panel. -->
<!-- 3. Install the "WordPress" importer from the list. -->
<!-- 4. Activate & Run Importer. -->
<!-- 5. Upload this file using the form provided on that page. -->
<!-- 6. You will first be asked to map the authors in this export file to users -->
<!--    on the site. For each author, you may choose to map to an -->
<!--    existing user on the site or to create a new user. -->
<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->
<!--    contained in this file into your site. -->

<!-- generator="WordPress/4.4.2" created="2016-02-23 17:01" -->
<rss version="2.0"
    xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:wp="http://wordpress.org/export/1.2/"
>

<channel>
    <title>davidak Weblog</title>
    <link>http://davidak.de/blog</link>
    <description></description>
    <pubDate>Tue, 23 Feb 2016 17:01:21 +0000</pubDate>
    <language>de-DE</language>
    <wp:wxr_version>1.2</wp:wxr_version>
    <wp:base_site_url>http://davidak.de/blog</wp:base_site_url>
    <wp:base_blog_url>http://davidak.de/blog</wp:base_blog_url>

    <wp:author><wp:author_id>3</wp:author_id><wp:author_login><![CDATA[davidak]]></wp:author_login><wp:author_email><![CDATA[post@davidak.de]]></wp:author_email><wp:author_display_name><![CDATA[davidak]]></wp:author_display_name><wp:author_first_name><![CDATA[David]]></wp:author_first_name><wp:author_last_name><![CDATA[Kleuker]]></wp:author_last_name></wp:author>

    <wp:category><wp:term_id>12</wp:term_id><wp:category_nicename><![CDATA[podcasts]]></wp:category_nicename><wp:category_parent><![CDATA[]]></wp:category_parent><wp:cat_name><![CDATA[Podcasts]]></wp:cat_name></wp:category>

    <generator>https://wordpress.org/?v=4.4.2</generator>

    <item>
        <title>Umfrage: Podcasts?</title>
        <link>http://davidak.de/blog/170-umfrage-podcasts/</link>
        <pubDate>Wed, 27 Jun 2007 13:59:10 +0000</pubDate>
        <dc:creator><![CDATA[davidak]]></dc:creator>
        <guid isPermaLink="false">http://davidak.de/blog/?p=170</guid>
        <description></description>
        <content:encoded><![CDATA[<?php get_poll(6);?>
]]></content:encoded>
        <excerpt:encoded><![CDATA[]]></excerpt:encoded>
        <wp:post_id>170</wp:post_id>
        <wp:post_date><![CDATA[2007-06-27 15:59:10]]></wp:post_date>
        <wp:post_date_gmt><![CDATA[2007-06-27 13:59:10]]></wp:post_date_gmt>
        <wp:comment_status><![CDATA[open]]></wp:comment_status>
        <wp:ping_status><![CDATA[open]]></wp:ping_status>
        <wp:post_name><![CDATA[umfrage-podcasts]]></wp:post_name>
        <wp:status><![CDATA[publish]]></wp:status>
        <wp:post_parent>0</wp:post_parent>
        <wp:menu_order>0</wp:menu_order>
        <wp:post_type><![CDATA[post]]></wp:post_type>
        <wp:post_password><![CDATA[]]></wp:post_password>
        <wp:is_sticky>0</wp:is_sticky>
        <category domain="category" nicename="internet"><![CDATA[Internet]]></category>
        <category domain="post_tag" nicename="podcasting"><![CDATA[podcasting]]></category>
        <category domain="category" nicename="podcasts"><![CDATA[Podcasts]]></category>
        <category domain="post_tag" nicename="podcasts"><![CDATA[Podcasts]]></category>
        <category domain="post_tag" nicename="umfrage"><![CDATA[umfrage]]></category>
        <wp:postmeta>
            <wp:meta_key><![CDATA[runphp]]></wp:meta_key>
            <wp:meta_value><![CDATA[1]]></wp:meta_value>
        </wp:postmeta>
    </item>

</channel>
</rss>

```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nikola/plugins/basic_import.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Copyright © 2012-2016 Roberto Alsina and others.
4 
5 # Permission is hereby granted, free of charge, to any
6 # person obtaining a copy of this software and associated
7 # documentation files (the "Software"), to deal in the
8 # Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the
11 # Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice
15 # shall be included in all copies or substantial portions of
16 # the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
19 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
20 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
21 # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
22 # OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
23 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24 # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 
27 """Mixin for importer plugins."""
28 
29 from __future__ import unicode_literals, print_function
30 import io
31 import csv
32 import datetime
33 import os
34 import sys
35 from pkg_resources import resource_filename
36 
37 try:
38     from urlparse import urlparse
39 except ImportError:
40     from urllib.parse import urlparse  # NOQA
41 
42 from lxml import etree, html
43 from mako.template import Template
44 
45 from nikola import utils
46 
47 links = {}
48 
49 
50 class ImportMixin(object):
51     """Mixin with common used methods."""
52 
53     name = "import_mixin"
54     needs_config = False
55     doc_usage = "[options] export_file"
56     doc_purpose = "import a dump from a different engine."
57     cmd_options = [
58         {
59             'name': 'output_folder',
60             'long': 'output-folder',
61             'short': 'o',
62             'default': 'new_site',
63             'help': 'Location to write imported content.'
64         },
65     ]
66 
67     def _execute(self, options={}, args=[]):
68         """Import a blog from an export into a Nikola site."""
69         raise NotImplementedError("Must be implemented by a subclass.")
70 
71     @classmethod
72     def get_channel_from_file(cls, filename):
73         """Get channel from XML file."""
74         tree = etree.fromstring(cls.read_xml_file(filename))
75         channel = tree.find('channel')
76         return channel
77 
78     @staticmethod
79     def configure_redirections(url_map, base_dir=''):
80         """Configure redirections from an url_map."""
81         index = base_dir + 'index.html'
82         if index.startswith('/'):
83             index = index[1:]
84         redirections = []
85         for k, v in url_map.items():
86             if not k[-1] == '/':
87                 k = k + '/'
88 
89             # remove the initial "/" because src is a relative file path
90             src = (urlparse(k).path + 'index.html')[1:]
91             dst = (urlparse(v).path)
92             if src == index:
93                 utils.LOGGER.warn("Can't do a redirect for: {0!r}".format(k))
94             else:
95                 redirections.append((src, dst))
96         return redirections
97 
98     def generate_base_site(self):
99         """Generate a base Nikola site."""
100         if not os.path.exists(self.output_folder):
101             os.system('nikola init -q ' + self.output_folder)
102         else:
103             self.import_into_existing_site = True
104             utils.LOGGER.notice('The folder {0} already exists - assuming that this is a '
105                                 'already existing Nikola site.'.format(self.output_folder))
106 
107         filename = resource_filename('nikola', 'conf.py.in')
108         # The 'strict_undefined=True' will give the missing symbol name if any,
109         # (ex: NameError: 'THEME' is not defined )
110         # for other errors from mako/runtime.py, you can add format_extensions=True ,
111         # then more info will be writen to *somefile* (most probably conf.py)
112         conf_template = Template(filename=filename, strict_undefined=True)
113 
114         return conf_template
115 
116     @staticmethod
117     def populate_context(channel):
118         """Populate context with settings."""
119         raise NotImplementedError("Must be implemented by a subclass.")
120 
121     @classmethod
122     def transform_content(cls, content):
123         """Transform content to a Nikola-friendly format."""
124         return content
125 
126     @classmethod
127     def write_content(cls, filename, content, rewrite_html=True):
128         """Write content to file."""
129         if rewrite_html:
130             doc = html.document_fromstring(content)
131             doc.rewrite_links(replacer)
132             content = html.tostring(doc, encoding='utf8')
133         else:
134             content = content.encode('utf-8')
135 
136         utils.makedirs(os.path.dirname(filename))
137         with open(filename, "wb+") as fd:
138             fd.write(content)
139 
140     @staticmethod
141     def write_metadata(filename, title, slug, post_date, description, tags, **kwargs):
142         """Write metadata to meta file."""
143         if not description:
144             description = ""
145 
146         utils.makedirs(os.path.dirname(filename))
147         with io.open(filename, "w+", encoding="utf8") as fd:
148             data = {'title': title, 'slug': slug, 'date': post_date, 'tags': ','.join(tags), 'description': description}
149             data.update(kwargs)
150             fd.write(utils.write_metadata(data))
151 
152     @staticmethod
153     def write_urlmap_csv(output_file, url_map):
154         """Write urlmap to csv file."""
155         utils.makedirs(os.path.dirname(output_file))
156         fmode = 'wb+' if sys.version_info[0] == 2 else 'w+'
157         with io.open(output_file, fmode) as fd:
158             csv_writer = csv.writer(fd)
159             for item in url_map.items():
160                 csv_writer.writerow(item)
161 
162     def get_configuration_output_path(self):
163         """Get path for the output configuration file."""
164         if not self.import_into_existing_site:
165             filename = 'conf.py'
166         else:
167             filename = 'conf.py.{name}-{time}'.format(
168                 time=datetime.datetime.now().strftime('%Y%m%d_%H%M%S'),
169                 name=self.name)
170         config_output_path = os.path.join(self.output_folder, filename)
171         utils.LOGGER.info('Configuration will be written to: {0}'.format(config_output_path))
172 
173         return config_output_path
174 
175     @staticmethod
176     def write_configuration(filename, rendered_template):
177         """Write the configuration file."""
178         utils.makedirs(os.path.dirname(filename))
179         with io.open(filename, 'w+', encoding='utf8') as fd:
180             fd.write(rendered_template)
181 
182 
183 def replacer(dst):
184     """Replace links."""
185     return links.get(dst, dst)
186
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/nikola/plugins/basic_import.py b/nikola/plugins/basic_import.py
--- a/nikola/plugins/basic_import.py
+++ b/nikola/plugins/basic_import.py
@@ -127,9 +127,12 @@
     def write_content(cls, filename, content, rewrite_html=True):
         """Write content to file."""
         if rewrite_html:
-            doc = html.document_fromstring(content)
-            doc.rewrite_links(replacer)
-            content = html.tostring(doc, encoding='utf8')
+            try:
+                doc = html.document_fromstring(content)
+                doc.rewrite_links(replacer)
+                content = html.tostring(doc, encoding='utf8')
+            except etree.ParserError:
+                content = content.encode('utf-8')
         else:
             content = content.encode('utf-8')

{"golden_diff": "diff --git a/nikola/plugins/basic_import.py b/nikola/plugins/basic_import.py\n--- a/nikola/plugins/basic_import.py\n+++ b/nikola/plugins/basic_import.py\n@@ -127,9 +127,12 @@\n     def write_content(cls, filename, content, rewrite_html=True):\n         \"\"\"Write content to file.\"\"\"\n         if rewrite_html:\n-            doc = html.document_fromstring(content)\n-            doc.rewrite_links(replacer)\n-            content = html.tostring(doc, encoding='utf8')\n+            try:\n+                doc = html.document_fromstring(content)\n+                doc.rewrite_links(replacer)\n+                content = html.tostring(doc, encoding='utf8')\n+            except etree.ParserError:\n+                content = content.encode('utf-8')\n         else:\n             content = content.encode('utf-8')\n", "issue": "import_wordpress problem with php code in blogpost\n```\n$ nikola import_wordpress /Users/davidak/Downloads/davidakweblog.wordpress.2016-02-23.xml\n[2016-02-23T17:06:37Z] NOTICE: Nikola: The folder new_site already exists - assuming that this is a already existing Nikola site.\nTraceback (most recent call last):\n  File \"/usr/local/lib/python3.5/site-packages/doit/doit_cmd.py\", line 168, in run\n    return command.parse_execute(args)\n  File \"/usr/local/lib/python3.5/site-packages/doit/cmd_base.py\", line 122, in parse_execute\n    return self.execute(params, args)\n  File \"/usr/local/lib/python3.5/site-packages/nikola/plugin_categories.py\", line 124, in execute\n    return self._execute(options, args)\n  File \"/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py\", line 332, in _execute\n    self.import_posts(channel)\n  File \"/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py\", line 1015, in import_posts\n    self.process_item_if_post_or_page(item)\n  File \"/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py\", line 996, in process_item_if_post_or_page\n    out_folder_slug = self.import_postpage_item(item, wordpress_namespace, 'posts', attachments)\n  File \"/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py\", line 938, in import_postpage_item\n    rewrite_html)\n  File \"/usr/local/lib/python3.5/site-packages/nikola/plugins/basic_import.py\", line 130, in write_content\n    doc = html.document_fromstring(content)\n  File \"/usr/local/lib/python3.5/site-packages/lxml/html/__init__.py\", line 755, in document_fromstring\n    \"Document is empty\")\nlxml.etree.ParserError: Document is empty\n```\n\nwordpress export of the post:\n\n```\n<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->\n<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->\n<!-- You may use this file to transfer that content from one site to another. -->\n<!-- This file is not intended to serve as a complete backup of your site. -->\n\n<!-- To import this information into a WordPress site follow these steps: -->\n<!-- 1. Log in to that site as an administrator. -->\n<!-- 2. Go to Tools: Import in the WordPress admin panel. -->\n<!-- 3. Install the \"WordPress\" importer from the list. -->\n<!-- 4. Activate & Run Importer. -->\n<!-- 5. Upload this file using the form provided on that page. -->\n<!-- 6. You will first be asked to map the authors in this export file to users -->\n<!--    on the site. For each author, you may choose to map to an -->\n<!--    existing user on the site or to create a new user. -->\n<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->\n<!--    contained in this file into your site. -->\n\n<!-- generator=\"WordPress/4.4.2\" created=\"2016-02-23 17:01\" -->\n<rss version=\"2.0\"\n    xmlns:excerpt=\"http://wordpress.org/export/1.2/excerpt/\"\n    xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n    xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n    xmlns:wp=\"http://wordpress.org/export/1.2/\"\n>\n\n<channel>\n    <title>davidak Weblog</title>\n    <link>http://davidak.de/blog</link>\n    <description></description>\n    <pubDate>Tue, 23 Feb 2016 17:01:21 +0000</pubDate>\n    <language>de-DE</language>\n    <wp:wxr_version>1.2</wp:wxr_version>\n    <wp:base_site_url>http://davidak.de/blog</wp:base_site_url>\n    <wp:base_blog_url>http://davidak.de/blog</wp:base_blog_url>\n\n    <wp:author><wp:author_id>3</wp:author_id><wp:author_login><![CDATA[davidak]]></wp:author_login><wp:author_email><![CDATA[post@davidak.de]]></wp:author_email><wp:author_display_name><![CDATA[davidak]]></wp:author_display_name><wp:author_first_name><![CDATA[David]]></wp:author_first_name><wp:author_last_name><![CDATA[Kleuker]]></wp:author_last_name></wp:author>\n\n    <wp:category><wp:term_id>12</wp:term_id><wp:category_nicename><![CDATA[podcasts]]></wp:category_nicename><wp:category_parent><![CDATA[]]></wp:category_parent><wp:cat_name><![CDATA[Podcasts]]></wp:cat_name></wp:category>\n\n    <generator>https://wordpress.org/?v=4.4.2</generator>\n\n    <item>\n        <title>Umfrage: Podcasts?</title>\n        <link>http://davidak.de/blog/170-umfrage-podcasts/</link>\n        <pubDate>Wed, 27 Jun 2007 13:59:10 +0000</pubDate>\n        <dc:creator><![CDATA[davidak]]></dc:creator>\n        <guid isPermaLink=\"false\">http://davidak.de/blog/?p=170</guid>\n        <description></description>\n        <content:encoded><![CDATA[<?php get_poll(6);?>\n]]></content:encoded>\n        <excerpt:encoded><![CDATA[]]></excerpt:encoded>\n        <wp:post_id>170</wp:post_id>\n        <wp:post_date><![CDATA[2007-06-27 15:59:10]]></wp:post_date>\n        <wp:post_date_gmt><![CDATA[2007-06-27 13:59:10]]></wp:post_date_gmt>\n        <wp:comment_status><![CDATA[open]]></wp:comment_status>\n        <wp:ping_status><![CDATA[open]]></wp:ping_status>\n        <wp:post_name><![CDATA[umfrage-podcasts]]></wp:post_name>\n        <wp:status><![CDATA[publish]]></wp:status>\n        <wp:post_parent>0</wp:post_parent>\n        <wp:menu_order>0</wp:menu_order>\n        <wp:post_type><![CDATA[post]]></wp:post_type>\n        <wp:post_password><![CDATA[]]></wp:post_password>\n        <wp:is_sticky>0</wp:is_sticky>\n        <category domain=\"category\" nicename=\"internet\"><![CDATA[Internet]]></category>\n        <category domain=\"post_tag\" nicename=\"podcasting\"><![CDATA[podcasting]]></category>\n        <category domain=\"category\" nicename=\"podcasts\"><![CDATA[Podcasts]]></category>\n        <category domain=\"post_tag\" nicename=\"podcasts\"><![CDATA[Podcasts]]></category>\n        <category domain=\"post_tag\" nicename=\"umfrage\"><![CDATA[umfrage]]></category>\n        <wp:postmeta>\n            <wp:meta_key><![CDATA[runphp]]></wp:meta_key>\n            <wp:meta_value><![CDATA[1]]></wp:meta_value>\n        </wp:postmeta>\n    </item>\n\n</channel>\n</rss>\n\n```\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2016 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"Mixin for importer plugins.\"\"\"\n\nfrom __future__ import unicode_literals, print_function\nimport io\nimport csv\nimport datetime\nimport os\nimport sys\nfrom pkg_resources import resource_filename\n\ntry:\n    from urlparse import urlparse\nexcept ImportError:\n    from urllib.parse import urlparse  # NOQA\n\nfrom lxml import etree, html\nfrom mako.template import Template\n\nfrom nikola import utils\n\nlinks = {}\n\n\nclass ImportMixin(object):\n    \"\"\"Mixin with common used methods.\"\"\"\n\n    name = \"import_mixin\"\n    needs_config = False\n    doc_usage = \"[options] export_file\"\n    doc_purpose = \"import a dump from a different engine.\"\n    cmd_options = [\n        {\n            'name': 'output_folder',\n            'long': 'output-folder',\n            'short': 'o',\n            'default': 'new_site',\n            'help': 'Location to write imported content.'\n        },\n    ]\n\n    def _execute(self, options={}, args=[]):\n        \"\"\"Import a blog from an export into a Nikola site.\"\"\"\n        raise NotImplementedError(\"Must be implemented by a subclass.\")\n\n    @classmethod\n    def get_channel_from_file(cls, filename):\n        \"\"\"Get channel from XML file.\"\"\"\n        tree = etree.fromstring(cls.read_xml_file(filename))\n        channel = tree.find('channel')\n        return channel\n\n    @staticmethod\n    def configure_redirections(url_map, base_dir=''):\n        \"\"\"Configure redirections from an url_map.\"\"\"\n        index = base_dir + 'index.html'\n        if index.startswith('/'):\n            index = index[1:]\n        redirections = []\n        for k, v in url_map.items():\n            if not k[-1] == '/':\n                k = k + '/'\n\n            # remove the initial \"/\" because src is a relative file path\n            src = (urlparse(k).path + 'index.html')[1:]\n            dst = (urlparse(v).path)\n            if src == index:\n                utils.LOGGER.warn(\"Can't do a redirect for: {0!r}\".format(k))\n            else:\n                redirections.append((src, dst))\n        return redirections\n\n    def generate_base_site(self):\n        \"\"\"Generate a base Nikola site.\"\"\"\n        if not os.path.exists(self.output_folder):\n            os.system('nikola init -q ' + self.output_folder)\n        else:\n            self.import_into_existing_site = True\n            utils.LOGGER.notice('The folder {0} already exists - assuming that this is a '\n                                'already existing Nikola site.'.format(self.output_folder))\n\n        filename = resource_filename('nikola', 'conf.py.in')\n        # The 'strict_undefined=True' will give the missing symbol name if any,\n        # (ex: NameError: 'THEME' is not defined )\n        # for other errors from mako/runtime.py, you can add format_extensions=True ,\n        # then more info will be writen to *somefile* (most probably conf.py)\n        conf_template = Template(filename=filename, strict_undefined=True)\n\n        return conf_template\n\n    @staticmethod\n    def populate_context(channel):\n        \"\"\"Populate context with settings.\"\"\"\n        raise NotImplementedError(\"Must be implemented by a subclass.\")\n\n    @classmethod\n    def transform_content(cls, content):\n        \"\"\"Transform content to a Nikola-friendly format.\"\"\"\n        return content\n\n    @classmethod\n    def write_content(cls, filename, content, rewrite_html=True):\n        \"\"\"Write content to file.\"\"\"\n        if rewrite_html:\n            doc = html.document_fromstring(content)\n            doc.rewrite_links(replacer)\n            content = html.tostring(doc, encoding='utf8')\n        else:\n            content = content.encode('utf-8')\n\n        utils.makedirs(os.path.dirname(filename))\n        with open(filename, \"wb+\") as fd:\n            fd.write(content)\n\n    @staticmethod\n    def write_metadata(filename, title, slug, post_date, description, tags, **kwargs):\n        \"\"\"Write metadata to meta file.\"\"\"\n        if not description:\n            description = \"\"\n\n        utils.makedirs(os.path.dirname(filename))\n        with io.open(filename, \"w+\", encoding=\"utf8\") as fd:\n            data = {'title': title, 'slug': slug, 'date': post_date, 'tags': ','.join(tags), 'description': description}\n            data.update(kwargs)\n            fd.write(utils.write_metadata(data))\n\n    @staticmethod\n    def write_urlmap_csv(output_file, url_map):\n        \"\"\"Write urlmap to csv file.\"\"\"\n        utils.makedirs(os.path.dirname(output_file))\n        fmode = 'wb+' if sys.version_info[0] == 2 else 'w+'\n        with io.open(output_file, fmode) as fd:\n            csv_writer = csv.writer(fd)\n            for item in url_map.items():\n                csv_writer.writerow(item)\n\n    def get_configuration_output_path(self):\n        \"\"\"Get path for the output configuration file.\"\"\"\n        if not self.import_into_existing_site:\n            filename = 'conf.py'\n        else:\n            filename = 'conf.py.{name}-{time}'.format(\n                time=datetime.datetime.now().strftime('%Y%m%d_%H%M%S'),\n                name=self.name)\n        config_output_path = os.path.join(self.output_folder, filename)\n        utils.LOGGER.info('Configuration will be written to: {0}'.format(config_output_path))\n\n        return config_output_path\n\n    @staticmethod\n    def write_configuration(filename, rendered_template):\n        \"\"\"Write the configuration file.\"\"\"\n        utils.makedirs(os.path.dirname(filename))\n        with io.open(filename, 'w+', encoding='utf8') as fd:\n            fd.write(rendered_template)\n\n\ndef replacer(dst):\n    \"\"\"Replace links.\"\"\"\n    return links.get(dst, dst)\n", "path": "nikola/plugins/basic_import.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2016 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"Mixin for importer plugins.\"\"\"\n\nfrom __future__ import unicode_literals, print_function\nimport io\nimport csv\nimport datetime\nimport os\nimport sys\nfrom pkg_resources import resource_filename\n\ntry:\n    from urlparse import urlparse\nexcept ImportError:\n    from urllib.parse import urlparse  # NOQA\n\nfrom lxml import etree, html\nfrom mako.template import Template\n\nfrom nikola import utils\n\nlinks = {}\n\n\nclass ImportMixin(object):\n    \"\"\"Mixin with common used methods.\"\"\"\n\n    name = \"import_mixin\"\n    needs_config = False\n    doc_usage = \"[options] export_file\"\n    doc_purpose = \"import a dump from a different engine.\"\n    cmd_options = [\n        {\n            'name': 'output_folder',\n            'long': 'output-folder',\n            'short': 'o',\n            'default': 'new_site',\n            'help': 'Location to write imported content.'\n        },\n    ]\n\n    def _execute(self, options={}, args=[]):\n        \"\"\"Import a blog from an export into a Nikola site.\"\"\"\n        raise NotImplementedError(\"Must be implemented by a subclass.\")\n\n    @classmethod\n    def get_channel_from_file(cls, filename):\n        \"\"\"Get channel from XML file.\"\"\"\n        tree = etree.fromstring(cls.read_xml_file(filename))\n        channel = tree.find('channel')\n        return channel\n\n    @staticmethod\n    def configure_redirections(url_map, base_dir=''):\n        \"\"\"Configure redirections from an url_map.\"\"\"\n        index = base_dir + 'index.html'\n        if index.startswith('/'):\n            index = index[1:]\n        redirections = []\n        for k, v in url_map.items():\n            if not k[-1] == '/':\n                k = k + '/'\n\n            # remove the initial \"/\" because src is a relative file path\n            src = (urlparse(k).path + 'index.html')[1:]\n            dst = (urlparse(v).path)\n            if src == index:\n                utils.LOGGER.warn(\"Can't do a redirect for: {0!r}\".format(k))\n            else:\n                redirections.append((src, dst))\n        return redirections\n\n    def generate_base_site(self):\n        \"\"\"Generate a base Nikola site.\"\"\"\n        if not os.path.exists(self.output_folder):\n            os.system('nikola init -q ' + self.output_folder)\n        else:\n            self.import_into_existing_site = True\n            utils.LOGGER.notice('The folder {0} already exists - assuming that this is a '\n                                'already existing Nikola site.'.format(self.output_folder))\n\n        filename = resource_filename('nikola', 'conf.py.in')\n        # The 'strict_undefined=True' will give the missing symbol name if any,\n        # (ex: NameError: 'THEME' is not defined )\n        # for other errors from mako/runtime.py, you can add format_extensions=True ,\n        # then more info will be writen to *somefile* (most probably conf.py)\n        conf_template = Template(filename=filename, strict_undefined=True)\n\n        return conf_template\n\n    @staticmethod\n    def populate_context(channel):\n        \"\"\"Populate context with settings.\"\"\"\n        raise NotImplementedError(\"Must be implemented by a subclass.\")\n\n    @classmethod\n    def transform_content(cls, content):\n        \"\"\"Transform content to a Nikola-friendly format.\"\"\"\n        return content\n\n    @classmethod\n    def write_content(cls, filename, content, rewrite_html=True):\n        \"\"\"Write content to file.\"\"\"\n        if rewrite_html:\n            try:\n                doc = html.document_fromstring(content)\n                doc.rewrite_links(replacer)\n                content = html.tostring(doc, encoding='utf8')\n            except etree.ParserError:\n                content = content.encode('utf-8')\n        else:\n            content = content.encode('utf-8')\n\n        utils.makedirs(os.path.dirname(filename))\n        with open(filename, \"wb+\") as fd:\n            fd.write(content)\n\n    @staticmethod\n    def write_metadata(filename, title, slug, post_date, description, tags, **kwargs):\n        \"\"\"Write metadata to meta file.\"\"\"\n        if not description:\n            description = \"\"\n\n        utils.makedirs(os.path.dirname(filename))\n        with io.open(filename, \"w+\", encoding=\"utf8\") as fd:\n            data = {'title': title, 'slug': slug, 'date': post_date, 'tags': ','.join(tags), 'description': description}\n            data.update(kwargs)\n            fd.write(utils.write_metadata(data))\n\n    @staticmethod\n    def write_urlmap_csv(output_file, url_map):\n        \"\"\"Write urlmap to csv file.\"\"\"\n        utils.makedirs(os.path.dirname(output_file))\n        fmode = 'wb+' if sys.version_info[0] == 2 else 'w+'\n        with io.open(output_file, fmode) as fd:\n            csv_writer = csv.writer(fd)\n            for item in url_map.items():\n                csv_writer.writerow(item)\n\n    def get_configuration_output_path(self):\n        \"\"\"Get path for the output configuration file.\"\"\"\n        if not self.import_into_existing_site:\n            filename = 'conf.py'\n        else:\n            filename = 'conf.py.{name}-{time}'.format(\n                time=datetime.datetime.now().strftime('%Y%m%d_%H%M%S'),\n                name=self.name)\n        config_output_path = os.path.join(self.output_folder, filename)\n        utils.LOGGER.info('Configuration will be written to: {0}'.format(config_output_path))\n\n        return config_output_path\n\n    @staticmethod\n    def write_configuration(filename, rendered_template):\n        \"\"\"Write the configuration file.\"\"\"\n        utils.makedirs(os.path.dirname(filename))\n        with io.open(filename, 'w+', encoding='utf8') as fd:\n            fd.write(rendered_template)\n\n\ndef replacer(dst):\n    \"\"\"Replace links.\"\"\"\n    return links.get(dst, dst)\n", "path": "nikola/plugins/basic_import.py"}]}