Справка:Импорт

From Meta, a Wikimedia project coordination wiki
This page is a translated version of the page Help:Import and the translation is 55% complete.
Outdated translations are marked like this.

Meta-Wiki Importer icon
Meta-Wiki Importer icon

Есть два типа импорта, и оба они доступны через Special:Import:

  • трансвики-импорт, или интервики-импорт: импортировать страницы непосредственно из другой вики; настройки вики, в которую импортируется содержимое, определяют, из каких вики можно импортировать. Появляется message with id 'import-interwiki-text' (talk). После «Transfer pages into namespace» можно указать целевое пространство имён: настройка «все» на самом деле обозначает «в то же пространство, в каком оригинал».
  • импорт загрузкой: импорт файла в особом XML-формате, полученном посредством экспорта из другой вики; появляется message with id 'importtext' (talk).

См. страницу Importer с описанием того, какие группы участников могут выполнять подобные действия.

Трансвики-импорт

На многих вики-проектах Викимедиа трансвики-импорт отключён, попытка выдаст message with id 'importnosources' (talk): "No wikis from which to import have been defined and direct history uploads are disabled.". Однако страницы Викисклада, сайта Фонда, английского, чешского и французского разделов Википедии в настоящее время могут быть импортированы на Мету, а страницы Меты - на сайт MediaWiki. Произведённое импортирование фиксируется в истории правок и в соответствующем журнале.

Если импортируемая страница называется так же, как и существующая страница в целевой вики, то такая страница перезаписывается, если импортируемая страница новее (согласно отметкам о времени последнего изменения). Если произошла ошибка при импорте, то импорт может пройти частично (импортированы некоторые страницы, но не все). Поскольку страницы перезаписываются, то обычно можно просто попробовать импортировать ещё раз.

Если вы выставили настройку о включении информации об истории правок, то вы также должны увидеть историю правок как в «истории» импортированных страниц, так и во вкладе участников. Такие правки не появятся в журнале свежих правок (ни на дату/время импорта, ни на дату/время исходных правок). Похожее явление происходит при полном слиянии истории правок; впоследствии может быть довольно трудно определить, какие именно правки были импортированы.

Есть опция для включения всех шаблонов, при которой импортируются все шаблоны, используемые на импортируемой странице. Если этой опцией не воспользоваться, то ссылки на несуществующие шаблоны (в целевой вики) останутся в импортируемой статье в виде красных ссылок. Если опцией воспользоваться, то существующие шаблоны с тем же именем будут перезаписаны; важно, что импорт будет включать также все шаблоны, которыми пользуются шаблоны, рекурсивно. Можно импортировать несколько страниц: специально создать включающую их страницу и импортировать её, установив опцию включения шаблонов. Импортируйте внимательно, чтобы не импортировать слишком много.

Импорт полезен в следующих случаях:

  • когда страница была перемещена в другую вики и там поправлена — чтобы получить её историю в исходной вики; это особенно полезно, если саму страницу трудно найти, т. к. её переименовывали и т. п.;
  • сохранение истории страницы при её перемещении в другую вики (с удалением в исходной вики);
  • добавление в целевую вики шаблонов, которые есть в исходной;
  • в некоторых проектах, таких как Викисловать и Викитека, для добавления в новые языковые подразделы многоязычных материалов.

Реализация

Чтобы проверить, настроено ли в вашей вики право трансвики, и как оно настроено, в какие вики, можно сделать запрос к своей вики через API.

Настройки отобразятся в виде <param name="interwikisource" description="For interwiki imports: wiki to import from"> …

Также можно проверить глобальные настройки по ссылке http://noc.wikimedia.org/conf/highlight.php?file=InitialiseSettings.php (см. блок wgImportSources).

Если трансвики-импорт не настроен, то для его добавления нужно обратиться за поддержкой к локальному сообществу и выяснить, из каких вики его можно импортировать. Тогда запросы на изменение конфигурации можно добавлять в Багзиллу, где вы можете добавить новый запрос в разделе Wikimedia:. В запросе нужно указать ссылку на локальное обсуждение вопроса.

Запрос по API в вашей локальной вики также покажет права группы пользователей (см. тег <add>)

Присвоение права на трансвики-импорт

Most transwiki rights are assigned to users following a successful discussion in their community's wiki, followed up by a request to stewards at Steward requests/Permission. Some wikis have requested and been granted that local bureaucrats be able to assign this right, check with your wiki for the current situation there.

Импорт загрузкой

О том, как производится экспорт и в каком формате должны быть экспортируемые страницы, рассказывается в руководстве Help:Export. В общем случае любой участник может экспортировать вики-страницу в файл, но для того, чтобы импортировать страницу из файла в вики-проект, нужно иметь флаг администратора в том проекте. Если у вас установлен собственный сайт на движке MediaWiki, вам должна быть там доступна страница Special:Import. На вики-проектах Фонда Викимедиа только участники с правом importupload могут импортировать страницы из файла; таким правом обладают только члены группы "импортёров" и стюарды.

Чтобы импортировать вики-страницу с вашего компьютера, просто нажмите "Обзор" и выберите нужный файл.

Редактирование импортируемого файла

In the case of upload import, because of the simple readable file format the XML file can easily be edited between exporting and importing. This should be done with caution and integrity, one can make antedated edits and use false user names, and in combination with deletion, one can "change history". Applications of this editing include:

  • adding a note to the edit summary about the importing
  • changing user names and/or page names to avoid name conflicts (just between the title tags and between the username tags or also in links and signatures)
  • changing namespace names into the generic or the applicable ones (ditto)

Note that if two versions of the page have the same timestamp (because one was uploaded with the same timestamp as a preexisting version), the later (imported) version will show up in the edit history but not in the article itself.

Примеры работы с такими XML-файлами через Visual Studio .NET C# см. на странице mw:Manual:XML Import file manipulation in CSharp.

Объединение историй правок и другие сложности

См. также mw:Manual:Importing_XML_dumps#Troubleshooting.

Если импорт включает в себя историческую информацию, а в редактировании использовалось имя пользователя, которое в проекте импорта используется кем-то другим, то следует применить импорт загрузки, и имя пользователя в файле XML должно быть сначала заменены другим именем, чтобы избежать двусмысленности. Если имя пользователя еще не использовалось в импортируемом проекте, то вклады пользователей в любом случае доступны, хотя учетная запись не создается автоматически.

Just like when a page is referred to in a link, and/or put in a URL, generic namespace names are automatically converted, and if a prefix is not a namespace name the page will arrive in the main namespace. However, e.g. "Meta:" may be ignored (dropped) on a project that uses that prefix for interwiki linking. It may be desirable to change it in the XML file to "Project:" before importing.

If a page name exists already, importing revisions of a page with that name causes the page histories to be merged. Note that after inserting a revision between two existing revisions in the page history, the change made by the user who made the next edit seems different from what it actually has been: to see the actual change made by the user one has to take the diff between the two already existing revisions, not the diff with respect to the inserted one. Therefore this should not be done except to reconstruct the true page history.

A revision is not imported if a revision of the same page, date, and time (up to the exact second) exists already. In practice this occurs only when the revision has already been imported (either to the current wiki, or previously to the wiki from which the export was made, or both were imported from a third site).

An edit summary may refer to, and possibly link to, another page. This may be confusing when the page has been imported but the target page has not.

The edit summary does not automatically show that the page has been imported, but in the case of upload import that can be added to the edit summaries in the XML file before importing. That can avoid some potential sources of ambiguity and/or confusion. When editing the XML file with find/replace, note that adding a text to the edit summaries requires distinguishing between edits which already have an edit summary, hence comment tags in the XML file, and those without these tags. If there are multiple pairs of comment tags, only the last one is effective.

Вклад участника

Without provisions for user name conflicts, the user contributions list shows:

  • the edits by the person registered under the user name concerned on the project
  • for each wiki from which pages have been imported, the edits of imported pages before import, by the user who on the source project has the user name concerned

If at the time of import the page did not exist yet on the target site, the two can be distinguished by comparing the time of import with the time of the edit.

If the user page and user talk page do not have a user contributions link in the page margin then the user is not registered, so all their edits are imported.

Large-scale transfer

For a large-scale transfer, somebody with sufficient system privileges can move data within the server, which is more practical than sending large XML files from the server to a user's local computer and then back to the server.

Large files may be rejected for two reasons. The PHP upload limit, found in PHP configuration file php.ini:

 ; Maximum allowed size for uploaded files.
 upload_max_filesize = 20M

And also the hidden variable limiting the size in the input form. Found in the mediawiki source code

, includes/specials/SpecialImport.php:

   <input type='hidden' name='MAX_FILE_SIZE' value='20000000' /> 

Maybe you should change the following four directives in php.ini:

; Maximum size of POST data that PHP will accept.
post_max_size = 20M
max_execution_time = 1000  ; Maximum execution time of each script, in seconds
max_input_time = 2000	    ; Maximum amount of time each script may spend parsing request data
; Default timeout for socket based streams (seconds)
default_socket_timeout = 2000

См. также

  • data dumps describes the maintenance script maintenance/importDump.php which provides an alternate import mechanism, but hasn't always remained in working order with recent MediaWiki releases
  • Importer