Import upload modifica

Tradotto da: meta:Help:Import

Caricare dati d'importazione modifica

Come esportare e il formato delle pagine esportate è descritto in meta:Help:export. Normalmente ogni utente può esportare le pagine wiki in un file, ma per importare le pagine in un wiki da un file, è necessario disporre dei privilegi di 'Amministratore' su quel wiki. Quindi, se si dispone di un'installazione personalizzata di MediaWiki, allora si dovrebbe essere in grado di vedere lì la pagina 'Speciale:Importa'. All'interno della famiglia dei progetti wiki della Wikimedia Foundation, solo gli utenti con il diritto di importupload possono importare le pagine in un wiki da un file, questo include solo i membri del gruppo "Importatore" e steward.

Per importare pagine wiki dal tuo computer è sufficiente fare clic su Sfoglia per individuare il file nel file di sistema locale.

Modificare il file d'importazione modifica

Nel caso di importazione di caricamenti, dato il semplice formato file XML, il file è facilmente leggibile e può essere modificato tra esportazione e importazione. Questo dovrebbe essere fatto con cautela e consapevolezza, si può antedatare le modifiche e utilizzare falsi nomi utente e in combinazione con l'eliminazione, si può "cambiare la storia". Le modifiche che si possono fare su questi file includono:

  • aggiungere una nota all'oggetto della modifica sull'importazione
  • modificare nomi utente e/o nomi pagina per evitare conflitti di nomi (solo tra le etichette del titolo e quelle del nome utente o anche nei collegamenti e firme)
  • cambiare i nomi dei namespace in generici o in quelli applicabili (idem)

Si noti che se due versioni della pagina hanno la stessa data e ora (perché uno è stato caricato con la stessa data e ora della versione preesistente), la versione importata più tardi verrà visualizzata nella cronologia, ma non nella stessa pagina.

Vedi Manipolazione file d'importazione XML in CSharp per un esempio di lavoro con questi file XML in Visual Studio .NET C#.

Unire le cronologie e altre complicazioni modifica

Tradotto da: meta:Help:Import

Se l'importazione include informazioni nella cronologia e le modifiche hanno coinvolto un utenza che nel progetto in cui viene importata la pagina viene utilizzato da qualcun latro, allora dovrebbe essere applicata l'importazione di caricamenti e sostituite tutte le occorrenze del nome utente nel file XML con un altro nome (per evitare ambiguità). Se il nome utente non è stato ancora utilizzato nel progetto in cui viene importata la pagina allora i contributi degli utenti saranno comunque disponibili, anche se l'account non viene creato automaticamente.

Proprio come quando una pagina è riferita ad un link, e/o messa in un URL, i nomi dei namespace generici vengono convertiti automaticamente, e anche se il prefisso non è uguale al nome del namespace, la pagina raggiungerà il namespace principale. Tuttavia, ad esempio "Meta:" può essere ignorato in un progetto che utilizza quel prefisso come interwiki di collegamento. Può essere opportuno cambiarlo nel file XML in "Project:" prima dell'importazione.

Se il nome di una pagina è già esistente, l'importazione delle revisioni di una pagina con quelo stesso nome fa sì che le storie della pagina si uniscano. Si noti che dopo l'inserimento di una revisione tra due revisioni esistenti nella cronologia della pagina, la modifica apportata da parte dell'utente che ha effettuato la modifica successiva sembra diversa da quella che effettivamente è stata: per vedere la variazione effettiva fatta da un utente devi fare il diff tra le due versioni già esistenti, non il diff rispetto a quello inserito. Quindi questa unione di cronologie non dovrebbe essere fatta se non per ricostruire la vera storia della pagina.

Una revisione non viene importata se esiste già una versione uguale a questa per data e ora e anche secondo. In pratica, ciò si verifica solo quando la revisione è già stata importata prima, o quando la revisione che si cerca di importare è stato importata al contrario o entrambe sono state importate da un terzo sito.

Un oggetto della modifica può fare riferimento a, ed eventualmente collegare, un'altra pagina. Ciò può essere fonte di confusione quando la pagina è stata importata ma la pagina di destinazione no.

L'oggetto della modifica non mostra automaticamente che la pagina è stata importata, ma nel caso di importazioni di caricamenti può essere aggiunto agli oggetti delle modifiche del file XML prima di importarlo. Questo può evitare alcune potenziali fonti di ambiguità e/o confusione. Quando si modifica il file XML con trova/sostituisci, si noti che l'aggiunta del testo dell'oggetto della modifica richiede una distinzione tra le modifiche che già dispongono di un oggetto della modifica, cioè le etichette di commento nel file XML, e quelle senza queste etichette. Se ci sono più coppie di etichette di commento solo l'ultima è quella effettiva.

Manipolazione file d'importazione XML in CSharp modifica

ORIGINALE

TRADUZIONE

Panoramica modifica

Questa pagina mostra come utilizzare lo schema MediaWiki con Visual Studio. NET C # per manipolare un Media Wiki file di importazione XML nel codice utilizzando programmazione orientata agli oggetti invece di lavorare direttamente con il formato XML.

This page shows how to use the MediaWiki schema with Visual Studio .NET C# to manipulate a Media Wiki XML import file in code using object-oriented programming instead of working directly with raw XML.


Un caso d'uso è che si potrebbe avere un certo numero di pagine di un sito wiki che devono essere modificati. Un modo per farlo è quello di esportarli in un file XML, quindi modificare il file XML, e quindi importare il file XML di ritorno. Naturalmente, si dovrebbe essere sicuri che gli utenti non possono modificare questi file durante l'intervallo tra l'esportazione e la reimportazione. Per i siti con uso moderato, questo approccio potrebbe essere appropriato.

One use case for this is that you might have a number of pages in a wiki site that need to be modified. One way to do this is to export them to an XML file, then manipulate the XML file, and then import the XML file back. Of course, you should be sure that users cannot modify these files during the span between export and re-import. For sites with moderate usage, this approach might be appropriate.

Schema modifica

Come mostrato in questo esempio abbreviato di un file di importazione XML di seguito, la schemaLocation del file XML è http://www.mediawiki.org/xml/export-0.3.xsd:

As shown in this abbreviated example of an XML import file below, the schemaLocation of the XML file is at http://www.mediawiki.org/xml/export-0.3.xsd:

<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" 
version="0.3" 
xml:lang="en">
  <siteinfo>...</siteinfo>
  <page>...</page>
  <page>...</page>
  <page>...</page>
</mediawiki>

In primo luogo, scaricare lo schema Wiki Media presso http://www.mediawiki.org/xml/export-0.3.xsd. Inserire il file di schema in una. Cartella del progetto NET, e prendere in considerazione rinominare il file in qualcosa di più intuitivo, come MediaWikiExport.xsd. Utilizzando Visual Studio.NET 's strumento xsd.exe, è possibile generare un file di .NET di classe sulla base di questo schema utilizzando questa linea di VS.NET prompt dei comandi:

First, download the Media Wiki schema at http://www.mediawiki.org/xml/export-0.3.xsd. Place the schema file in a .NET project folder, and consider renaming the file to something more intuitive such as MediaWikiExport.xsd. Using Visual Studio.NET's xsd.exe tool, you can generate a .NET class file based on this schema using this VS.NET command line prompt:

xsd c:/inetpub/wwwroot/MyProject/MediaWikiExport.xsd /c

Questo comando creerà un file di classe denominato MediaWikiExport.cs.

This command will create a class file named MediaWikiExport.cs.

Diagramma della Classe modifica

Il file auto-generato Classe sarà simile a questa:

The auto-generated Class file will look like this:

 
Auto-generated VS.NET C# class file based on the Media Wiki import schema


Diagramma dello Schema modifica

Lo schema sarà simile a questo:

 
Media Wiki import file schema


.NET Project modifica

Dopo aver aggiunto il nuovo file auto-generato di classe, aggiungere il file nel vostro. NET progetto, ad esempio un progetto di applicazione console.

After you add your new auto-generated class file, add the file into your .NET project, such as a console application project.


In questo esempio di codice, vedrete esempi di come lavorare con il file XML in un modo orientato agli oggetti, invece di analizzare il formato XML. Si noti che questo esempio di codice riportato di seguito è stato utilizzato per la versione 1.13.2 di Media Wiki.

In this code sample, you will see examples of how to work with the XML file in an object-oriented way instead of parsing the raw XML. Note that this code sample below was used for the 1.13.2 version of Media Wiki.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace WikiFileManipulation
{
    class Program
    {
        static void Main(string[] args)
        {
            // name of the exported wiki file
            string file = "ExportedWikiPages.xml";

            // instantiate MediaWikiType object
            MediaWikiType mw = new MediaWikiType();

            // Open XML file containing exported wiki pages
            System.Xml.XmlDataDocument xml = new System.Xml.XmlDataDocument();
            xml.Load(file);

            // Deserialize the XML file into the MediaWikiType object
            XmlSerializer serializer = new XmlSerializer(typeof(MediaWikiType));
            System.Xml.XmlNodeReader oReader = new System.Xml.XmlNodeReader(xml);
            mw = (MediaWikiType)serializer.Deserialize(oReader);

            // Loop through all the Pages in the MediaWikiType object
            foreach (PageType p in mw.page)
            {
                foreach (object o in p.Items)
                {
                    // Examine the RevisionType
                    if (o is RevisionType)
                    {
                        // Cast to RevisionType object
                        RevisionType r = o as RevisionType;

                        // if you increment "timestamp" by one minute, then you'll be able to re-import file
                        r.timestamp = r.timestamp.AddMinutes(1);

                        // Update the value of the "text" of the revision
                        // this is the page text
                        TextType text = r.text as TextType;
                        text.Value = text.Value.Replace("oldvalue", "newvalue");
                    }
                }
            }

            //serialize the updated object back to the original file with the corrections/additions
            System.IO.TextWriter writer = new System.IO.StreamWriter(file);
            serializer.Serialize(writer, mw);
            writer.Close();
        }
    }
}

Versione C# 3.0 modifica

Ecco lo stesso esempio usando le funzioni di C# 3.0, tra cui l'inferenza dei tipi e un'espressione lambda.

using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;

namespace WikiFileManipulation {
    class Program {
        static void Main(string[] args) {

            // name of the exported wiki file
            var file = "ExportedWikiPages.xml";
 
            // Open XML file containing exported wiki pages
            var xml =new XmlDataDocument();
            xml.Load(file);
 
            // Deserialize the XML file into the MediaWikiType object
            var serializer = new XmlSerializer(typeof(MediaWikiType));
            var nodeReader = new XmlNodeReader(xml);
            var mw = (MediaWikiType)serializer.Deserialize(nodeReader);
            
            // Loop through all the RevisionType Items from each Page
            foreach (var r in mw.page.SelectMany(p=>p.Items.OfType<RevisionType>())) { 
                // increment the "timestamp" in order to re-import file
                r.timestamp = r.timestamp.AddMinutes(1);
 
                // Update each revision's text
                r.text.Value = r.text.Value.Replace("oldvalue", "newvalue");
            }
 
            // serialize the updates back to the same file
            var writer = new StreamWriter(file);
            serializer.Serialize(writer, mw);
            writer.Close();
        }
    }
}

Importare dump XML modifica

ORIGINALE

TRADUZIONE

This page describes methods to import XML dumps.

The Special:Export page of any mediawiki, including any Wikimedia site and wikipedia, create a XML file (content dump). See meta:Data dumps and Manual:DumpBackup.php. XML files are explained more on meta:Help:Export.

There are several methods for importing these XML dumps:

Come importare? modifica

Usare Speciale:Importa modifica

Special:Import can be used by wiki users with import permission (by default this is users in the sysop group) to import a small number of pages (about 100 should be safe). Trying to import large dumps this way may result in timeouts or connection failures. See meta:Help:Import for a detailed description.

See Manual:XML Import file manipulation in CSharp for a C# code sample that manipulates an XML import file.

Cambiare i permessi modifica

See Manual:User_rights

To allow all registered editors to import (not recommended) the line added to localsettings.php would be:

$wgGroupPermissions['user']['import'] = true;
$wgGroupPermissions['user']['importupload'] = true;

Problemi Possibili modifica

For using Transwiki-Import PHP safe_mode must be off and open_basedir must be empty. Otherwise the import fails.

Usare importDump.php, se hai accesso alla shell modifica

Recommended method for general use, but slow for very big data sets. For very large amounts of data, such as a dump of a big Wikipedia, use mwdumper, and import the links tables as separate SQL dumps.

importDump.php is a command line script located in the maintenance folder of your MediaWiki installation. If you have shell access, you can call importdump.php like this (add paths as necesary):

php importDump.php --conf LocalSettings.php dumpfile.xml.gz wikidb

or this:

php importDump.php < dumpfile.xml

where dumpfile.xml is the name of the XML dump file. If the file is compressed and that has a .gz or .bz2 file extension, it is decompressed automatically.

Afterwards use ImportImages.php to import the images:

php importImages.php ../path_to/images
  • NOTA: If you are using WAMP installation, you can have troubles with the importing, due to innoDB settings (by default is this engine disabled in my.ini, so if you don't need troubles, use MyIsam engine)
  • NOTA: For Mediawikis older than version 1.16, to run importDump.php (or any other tool from the maintenance directory), you need to set up your AdminSettings.php file.
  • NOTA: running importDump.php can take quite a long time. For a large Wikipedia dump with millions of pages, it may take days, even on a fast server. Also note that the information in meta:Help:Import about merging histories, etc. also applies.

After running importDump.php, you may want to run rebuildrecentchanges.php in order to update the content of your Special:Recentchanges page.

FAQ modifica

How to setup debug mode?
Use command line option --debug.
How to make a dry run (no data added to the database)?
Use command line option --dry-run

Messaggi d'errore modifica

Typed
roots@hello:~# php importImages.php /maps gif bmp PNG JPG GIF BMP
Error
 
> PHP Deprecated:  Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/mcrypt.ini on line 1 in Unknown on line 0
> Could not open input file: importImages.php
Cause

Before running importImages.php you first need to change directories to the maintenance folder which has the importImages.php maintence script.


Error while running MAMP
DB connection error: No such file or directory (localhost)
Solution

Using specific database credentials

$wgDBserver         = "localhost:/Applications/MAMP/tmp/mysql/mysql.sock";
$wgDBadminuser      = "XXXX";
$wgDBadminpassword  = "XXXX";

Usare mwdumper modifica

mwdumper is a Java application that can be used to read, write and convert MediaWiki XML dumps. It can be used to generate a SQL dump from the XML file (for later use with mysql or phpmyadmin) as well as for importing into the database directly. It is a lot faster than importDump.php, however, it only imports the revisions (page contents), and does not update the internal link tables accordingly -- that means that category pages and many special pages will show incomplete or incorrect information unless you update those tables.

If available, you can fill the link tables by importing separate SQL dumps of these tables using the mysql command line client directly. For Wikimedia wikis, this data is available along with the XML dumps.

Otherwise, you can run rebuildall.php, which will take a long time, because it has to parse all pages. This is not recommended for large data sets.

Usare xml2sql modifica

Xml2sql (a multiplatform ANSI C program) converts a MediaWiki XML file into an SQL dump for use with mysql or phpmyadmin. Just like using mwdumper (see above), importing this way is fast, but does not update secondary data like link tables, so you need to run rebuildall.php, which nullifies that advantage.

ATTENZIONE xml2sql is not an official tool and not maintained by MediaWiki developers. It may become outdated and incompatible with the latest version of MediaWiki!

It already did. It's reporting "unexpected element <redirect>" just as the original 1.15 Import.php does (reported on 13 February 2010). (Tried on April 29th 2010 and getting same <redirect> issue). But You can use the perl script `xml2sql_helper.pl` in order to remove "<redirect />" and other new tags before running Xml2sql, see section Xml2sql at MySQL_import.

Usare pywikipediabot, pagefromfile.py e Nokogiri modifica

pywikipediabot is a collection of tools written in python that automate work on Wikipedia or other MediaWiki sites. Once installed on your computer, you can use the specific tool 'pagefromfile.py' which lets you upload a wiki file on Wikipedia or Mediawiki sites. The xml file created by dumpBackup.php can be transformed into a wiki file suitable to be processed by 'pagefromfile.py' using a simple Ruby program similar to the following (here the program will transform all xml files which are on the current directory which is needed if your mediawiki site is a family):

# -*- coding: utf-8 -*-
# dumpxml2wiki.rb

require 'rubygems'
require 'nokogiri'

# This program dumpxml2wiki reads mediawiki xml files dumped by dumpBackup.php
# on the current directory and transforms them into wiki files which can then 
# be modified and uploaded again by pywikipediabot using pagefromfile.py on a mediawiki family site.
# The text of each page is searched with xpath and its title is added on the first line as
# an html comment: this is required by pagefromfile.py.
# 
Dir.glob("*.xml").each do |filename|
  input = Nokogiri::XML(File.new(filename), nil, 'UTF-8')

  puts filename.to_s  # prints the name of each .xml file

  File.open("out_" + filename + ".wiki", 'w') {|f| 
    input.xpath("//xmlns:text").each {|n|
      pptitle = n.parent.parent.at_css "title" # searching for the title
      title = pptitle.content
      f.puts "\n{{-start-}}<!--'''" << title.to_s << "'''-->" << n.content  << "\n{{-stop-}}"
    }
  }
end

For example, here is an excerpt of a wiki file output by the command 'ruby dumpxml2wiki.rb' (two pages can then be uploaded by pagefromfile.py, a Template and a second page which is a redirect):

{{-start-}}<!--'''Template:Lang_translation_-pl'''--><includeonly>Tłumaczenie</includeonly>
{{-stop-}}

{{-start-}}#REDIRECT[[badania demograficzne]]<!--'''ilościowa demografia'''-->
<noinclude>
[[Category:Termin wielojęzycznego słownika demograficznego (pierwsze wydanie)|ilościowa demografia]]
[[Category:Termin wielojęzycznego słownika demograficznego (pierwsze wydanie) (redirect)]]
[[Category:10]]</noinclude>
{{-stop-}}

The program accesses each xml file, extracts the texts within <text> </text> markups of each page, searches the corresponding title as a parent and enclosed it with the paired {{-start-}}<!--'''Title of the page'''--> {{-stop-}} commands used by 'pagefromfile' to create or update a page. The name of the page is in an html comment and separated by three quotes on the same first start line. Please notice that the name of the page can be written in Unicode. Sometimes it is important that the page starts directly with the command, like for a #REDIRECT; thus the comment giving the name of the page must be after the command but still on the first line.

Please remark that the xml dump files produced by dumpBackup.php are prefixed by a namespace:

<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.4/">

In order to access the text node using Nokogiri, you need to prefix your path with 'xmlns':

input.xpath("//xmlns:text")

. Nokogiri is an HTML, XML, SAX, & Reader parser with the ability to search documents via XPath or CSS3 selectors from the last generation of XML parsers using Ruby.

Example of the use of 'pagefromfile' to upload the output wiki text file:

python pagefromfile.py -file:out_filename.wiki -summary:"Reason for changes" -lang:pl -putthrottle:01

Interwiki modifica

If you get the message

Page "meta:Blah blah" is not imported because its name is reserved for external linking (interwiki).

the problem is that some pages to be imported have a prefix that is used for interwiki linking. For example, ones with a prefix of 'Meta:' would conflict with the interwiki prefix meta: which by default links to http://meta.wikimedia.org.

You can do any of the following.

  • Remove the prefix from the interwiki table. This will preserve page titles, but prevent interwiki linking through that prefix.
    Example: you will preserve page titles 'Meta:Blah blah' but will not be able to use the prefix 'meta:' to link to meta.wikimedia.org (although it will be possible through a different prefix).
    How to do it: before importing the dump, run the query DELETE FROM interwiki WHERE iw_prefix='prefix' (note: do not include the colon in the prefix)
  • Replace the unwanted prefix in the XML file to "Project:" before importing. This will preserve the functionality of the prefix as an interlink, but will replace the prefix in the page titles with the name of the wiki where they're imported into, and might be quite a pain to do on large dumps.
    Example: replace all 'Meta:' to 'Project:' in the XML file. MediaWiki will then replace 'Project:' to the name of your wiki during importing.