Migrar un foro de vBulletin 4 a Discourse

Esta guía cubre la migración de un foro de vBulletin 4 a Discourse con el script de importación en script/import_scripts/vbulletin.rb.

:warning: Espere tener que ajustar el script. Cada instalación de vBulletin tiene sus propios plugins, campos personalizados y peculiaridades de BBCode. La mayoría de las importaciones reales requieren pequeños cambios en el script. Realice una importación de prueba completa en una máquina de desarrollo antes de tocar la producción.

¿Qué importador debo usar?

Foro Script
vBulletin 4 script/import_scripts/vbulletin.rb (esta guía)
vBulletin 3 script/import_scripts/vbulletin3.rb (mismos pasos, nombre de script diferente)
vBulletin 5 script/import_scripts/vbulletin5.rb
Foros muy grandes (millones de publicaciones) script/bulk_import/vbulletin.rb (mucho más rápido, pero tiene menos funciones y es más difícil de personalizar)

Qué se importa

  • Grupos
  • Usuarios (los usuarios baneados se convierten en usuarios suspendidos)
  • Foros: cada foro padre y foro hijo se convierte en una categoría y subcategoría
  • Temas
  • Hilo fijado → tema fijado
  • Hilo cerrado → tema cerrado
  • Hilo eliminado suavemente o moderado → tema no listado
  • Publicaciones
  • Mensajes privados
  • Adjuntos
  • Avatares (solo si están almacenados en la base de datos, vea más abajo)
  • Enlaces permanentes (permalinks) para temas

Advertencias

  • Puede reanudar una importación interrumpida y ejecutarla nuevamente contra una copia de seguridad de la base de datos más reciente para recuperar nuevo contenido. El contenido que ya fue importado no se actualizará con ediciones posteriores.

  • Discourse admite dos niveles de categorías. Los foros anidados con mayor profundidad se aplanan.

  • Las listas de BBCode ([ul], [ol], [li]) no se convierten completamente y pueden necesitar limpieza manual.

Antes de exportar

Si vBulletin almacena avatares en el sistema de archivos, el importador no los encontrará. Visite /admincp/avatar.php?do=storage en su sitio de vBulletin y mueva los avatares a la base de datos antes de exportarla.

Luego exporte la base de datos en el servidor de vBulletin:

mysqldump -u NOMBRE_DE_USUARIO -p NOMBRE_DE_BASE_DE_DATOS | gzip > vb4_dump.sql.gz

Copie el volcado y la carpeta de adjuntos a la máquina en la que realizará la importación (por ejemplo, con scp o rsync). Su configuración de administrador de vBulletin muestra dónde se almacenan los adjuntos.

Opción A: Importar en una máquina de desarrollo (recomendado)

Importar localmente le permite iterar rápidamente y descartar intentos fallidos. Cuando el resultado se vea correcto, haga una copia de seguridad del sitio y restaurélo en producción.

  1. Configure un entorno de desarrollo de Discourse siguiendo la guía para Ubuntu/Debian o macOS.

  2. Instale MariaDB. Es un reemplazo directo de MySQL, y los paquetes de MySQL 5.7 ya no están disponibles en las distribuciones actuales.

    # Ubuntu/Debian
    sudo apt-get update
    sudo apt-get install mariadb-server libmariadb-dev
    sudo service mariadb start
    
     # macOS
     brew install mariadb
     brew services start mariadb
    
  3. Instale las gems del importador. mysql2 se incluye cuando se establece IMPORT=1. php-serialize necesita agregarse:

    cd ~/discourse
    echo "gem 'php-serialize', require: false" >> Gemfile
    IMPORT=1 bundle install
    
  4. Cargue la base de datos de vBulletin:

    sudo mysql -e "CREATE DATABASE vb4"
    gunzip < vb4_dump.sql.gz | sudo mysql vb4
    
  5. Comience con una base de datos de Discourse vacía:

    bin/rails db:drop db:create db:migrate
    
  6. Ejecute el importador. Puede detenerlo y reiniciarlo en cualquier momento, ya que omite el contenido que ya se ha importado.

    export DB_HOST="localhost"  
    export DB_NAME="vb4"
    export DB_USER="root"
    export DB_PW=""                                # Contraseña root de MariaDB, si la configuró
    export TABLE_PREFIX="vb_"                      # Su prefijo de tabla, o "" si no hay ninguno
    export ATTACHMENT_DIR="/path/to/attachments"   # La carpeta de adjuntos que copió
    export TIMEZONE="America/Los_Angeles"          # La zona horaria que usó vBulletin
    
    IMPORT=1 bundle exec ruby script/import_scripts/vbulletin.rb
    
  7. Inicie Discourse y deje que los procesos en segundo plano terminen. Ejecute bin/dev, y en una segunda terminal ejecute bundle exec sidekiq. La reprocesamiento de publicaciones y el procesamiento de imágenes pueden tardar mucho tiempo en un foro grande. Puede seguir el progreso en http://localhost:4200/sidekiq.

  8. Pase a producción. Haga una copia de seguridad y restauréela en su sitio de producción siguiendo Mover un sitio de Discourse a otro VPS.

Opción B: Importar directamente en el contenedor de producción

  1. Instale Discourse con la guía de instalación estándar.

  2. Ajuste la configuración del sitio (vea Configuraciones del sitio recomendadas más abajo).

  3. Copie el volcado y los adjuntos en /var/discourse/shared/standalone/ en el host. Dentro del contenedor aparecen bajo /shared/, y los archivos allí sobreviven a una reconstrucción del contenedor.

  4. Entre al contenedor e instale MariaDB:

    cd /var/discourse
    ./launcher enter app
    apt-get update
    apt-get install -y mariadb-server libmariadb-dev
    service mariadb start
    
  5. Instale las gems del importador:

    cd /var/www/discourse
    echo "gem 'php-serialize', require: false" >> Gemfile
    su discourse -c 'bundle config set --local deployment false && bundle config set --local frozen false'
    su discourse -c 'IMPORT=1 bundle install'
    
  6. Cargue la base de datos de vBulletin:

    mysql -e "CREATE DATABASE vb4"
    gunzip < /shared/vb4_dump.sql.gz | mysql vb4
    
  7. Ejecute el importador. Ejecútelo dentro de tmux o screen para que una desconexión SSH no lo mate.

    cd /var/www/discourse
    su discourse -c 'DB_NAME=vb4 DB_USER=root DB_PW="" TABLE_PREFIX=vb_ \
    ATTACHMENT_DIR=/shared/attachments TIMEZONE=America/Los_Angeles \
    IMPORT=1 bundle exec ruby script/import_scripts/vbulletin.rb'
    
  8. Limpie. Elimine los archivos que copió en /shared, luego reconstruya el contenedor. La reconstrucción elimina MariaDB y las gems adicionales y restaura el Gemfile original.

    exit
    cd /var/discourse
    ./launcher rebuild app
    

Configuraciones del sitio recomendadas

Establezca estas antes de importar. También puede establecerlas en get_site_settings_for_import en script/import_scripts/base.rb, lo cual ayuda cuando ejecuta importaciones de prueba repetidamente.

  • login_required: active esto hasta que la importación esté terminada y revisada.

  • slug_generation_method: establezca en encoded si su foro no está en inglés, para que las URLs de los temas conserven sus títulos no ASCII.

  • download_remote_images_to_local: desactive esto si no desea que Discourse descargue las imágenes enlazadas directamente (hotlinked) en las publicaciones antiguas.

  • disable_system_edit_notifications: active esto para que los usuarios no sean notificados sobre cada publicación que el sistema edita mientras procesa las imágenes.

Problemas conocidos

  • Integer values are not supported (ArgumentError) en parse_timestamp. Esto afecta a copias antiguas del script que se ejecutan con versiones más nuevas de tzinfo. Actualice a la última versión de Discourse, o cambie `parse_timestamp` a:

    def parse_timestamp(timestamp)
    return nil if timestamp.blank?
       Time.zone.at(@tz.utc_to_local(Time.at(timestamp.to_i)))
    end
    
  • Las citas con nombres de usuario que tienen espacios, o citas anidadas, no se convierten. Vea esta respuesta para obtener expresiones regulares mejoradas.

  • Can't connect to local server through socket. MariaDB no se está ejecutando. Inícielo con service mariadb start.

21 Me gusta

The script will now import avatars, but they must be embedded into the database. To do so, I’m told that you visit /admincp/avatar.php?do=storage and do something there. It seemed to work for the last client I did an import for.

Hey, @erlend_sh, make this a wiki and I’ll add to it in a few days when I submit a PR for this importer.

6 Me gusta

I was following your guide to import my vBulletin forum to Discourse. I am using a docker container for Discourse. I ran the following command:

I got a long list of errors:

sudo: no tty present and no askpass program specified
sudo: no tty present and no askpass program specified
[...]
sudo: no tty present and no askpass program specified
sudo: no tty present and no askpass program specified

Bundler::SudoNotPermittedError: Bundler requires sudo access to install at the moment. Try installing again, granting Bundler sudo access when
prompted, or installing into a different path.
An error occurred while installing rake (11.2.2), and Bundler cannot continue.
Make sure that `gem install rake -v '11.2.2'` succeeds before bundling.

I am new to ruby on rails and dockers. I do understand the concept of gems and Bundler.
What do these errors mean and how can I resolve them?

1 me gusta

Ok so basically I had to install all the necessary gems.
The script worked quite well.

However, I am not able to login with one of the users I created on my vBulletin forum just before importing the database over to discourse.

1 me gusta

You’ll need to set passwords. The script doesn’t import them (last I looked).

And even if it did, you’d need to install a plugin to make them work.

1 me gusta

I am planning to write a script that will import the passwords for my case.
I know the mysql tables I need to consider for vBulletin. What is the table in PostgreSQL for Discourse that stores passwords and is used during login?

Prakarsh would you be able to share the forum url that you are trying to switch from? The vBulletin one. Will the Discourse one have the same URL?

Yes. Here it is: Brainstorm

Our plan is to keep the URL same for now. I cannot say when it will be live. Probably by end of next week if everything goes right :stuck_out_tongue:

1 me gusta

Before you do that, you should read this topic.

You don’t want to directly touch the Discourse tables. You want a script like this. When I last used it and tried to import the passwords, it ran really slowly. I’m not sure why, but after reading this I decided that it’s probably not a bad idea to make people change their passwords.

3 Me gusta

@pfaffman - You mentioned you used import_pass field in your import script.
Where exactly do you put the import_pass field? And how do you use it?
If you could share it would be great help.

I have tried using this script but it failed 90% into the import of the users:

su discourse -c 'RAILS_ENV=production ruby script/import_scripts/vbulletin.rb'
root:XXXX@localhost wants vb4
loading existing groups...
loading existing users...
loading existing categories...
loading existing posts...
loading existing topics...

importing groups...
        6 / 19 ( 31.6%)  Failed to create group id 7 Moderators: ["Name has already been taken"]
       19 / 19 (100.0%)  
importing users
     2746 / 15319 ( 17.9%)  W, [2017-10-12T10:07:05.104837 #3578]  WARN -- : Bad date/time value "0000:00:00 00:00:00": mon out of range
W, [2017-10-12T10:07:05.106562 #3578]  WARN -- : Bad date/time value "0000:00:00 00:00:00": mon out of range
W, [2017-10-12T10:07:05.107305 #3578]  WARN -- : Bad date/time value "0000:00:00 00:00:00": mon out of range
    13901 / 15319 ( 90.7%)  script/import_scripts/vbulletin.rb:137:in `strip': invalid byte sequence in UTF-8 (ArgumentError)
        from script/import_scripts/vbulletin.rb:137:in `block (2 levels) in import_users'
        from /var/www/discourse/script/import_scripts/base.rb:226:in `block in create_users'
        from /var/www/discourse/script/import_scripts/base.rb:225:in `each'
        from /var/www/discourse/script/import_scripts/base.rb:225:in `create_users'
        from script/import_scripts/vbulletin.rb:133:in `block in import_users'
        from /var/www/discourse/script/import_scripts/base.rb:784:in `block in batches'
        from /var/www/discourse/script/import_scripts/base.rb:783:in `loop'
        from /var/www/discourse/script/import_scripts/base.rb:783:in `batches'
        from script/import_scripts/vbulletin.rb:117:in `import_users'
        from script/import_scripts/vbulletin.rb:78:in `execute'
        from /var/www/discourse/script/import_scripts/base.rb:45:in `perform'
        from script/import_scripts/vbulletin.rb:902:in `<main>'

Anyone have any suggestions regarding how to debug and fix this?

You have an encoding problem in your database.

The database claims is using one encoding, but some of the data is encoded some other way. A job I just did had a similar problem. UTF-8 likely does not exist when you started your forum.

This is probably a problem for stack exchange or a database person. It’s not a problem with the importer.

It’s the kind of problem that will take 10 minutes following a recipe that you don’t understand, ten hours looking for that recipe, or 100 hours fixing it by hand.

3 Me gusta

Cheers @pfaffman I was approaching the same conclusion… I started writing up the following before your comment…

It looks like it might be caused by non-ascii characters in usernames, so dumping the usernames into a text file and searching for UTF-8:

echo "select username from user" | mysql -p vb4 | grep --color='auto' -P -n "[^[:ascii:]]"

These were the entities this threw up:

’ ´ – é ã Ñ í ó 

So I used this page to generate encoded versions and updated the usernames in the database, for example:

UPDATE user SET username="&rsquo; &acute; &ndash; &eacute; &atilde; &Ntilde; &iacute; &oacute;" WHERE username="’ ´ – é ã Ñ í ó"

But the script still fails:

script/import_scripts/vbulletin.rb:137:in `strip': invalid byte sequence in UTF-8 (ArgumentError)
        from script/import_scripts/vbulletin.rb:137:in `block (2 levels) in import_users'
        from /var/www/discourse/script/import_scripts/base.rb:226:in `block in create_users'
        from /var/www/discourse/script/import_scripts/base.rb:225:in `each'
        from /var/www/discourse/script/import_scripts/base.rb:225:in `create_users'
        from script/import_scripts/vbulletin.rb:133:in `block in import_users'
        from /var/www/discourse/script/import_scripts/base.rb:784:in `block in batches'
        from /var/www/discourse/script/import_scripts/base.rb:783:in `loop'
        from /var/www/discourse/script/import_scripts/base.rb:783:in `batches'
        from script/import_scripts/vbulletin.rb:117:in `import_users'
        from script/import_scripts/vbulletin.rb:78:in `execute'
        from /var/www/discourse/script/import_scripts/base.rb:45:in `perform'
        from script/import_scripts/vbulletin.rb:902:in `<main>'

So I then dumped the whole users table into a text file:

echo "select * from user" | mysql -p vb4 > /tmp/allusers.txt

And then tried all the suggesting in this stackexchange thread for finding non-ascii characters and none were found, so now to search the whole database for the problem…

When I find a solution I’ll post it here in case it helps others…

2 Me gusta

The problem almost certainly exists in other tables.

You need to figure out what it’s encoded in and fix it.

Or, it could be that for some years it’s in one encoding and other years it’s another.

Best of luck. I was relieved they my client had engineers they solved the problem so I didn’t have to. I may have some notes that I’ll try to find when I get out of bed.

1 me gusta

The database on the old server was UTF-8 but clearly it has some non-UTF-8 in it, the site has been in use for a long time and has 13k users… so taking care with dumping the old database:

mysqldump -uroot -p database -r dump.sql

And trying various methods to check the encoding (thanks to Stackexchange):

file dump.sql 
  dump.sql: ASCII text, with very long lines

apt install uchardet 
uchardet dump.sql
  UTF-8

iconv -f utf-8 -t utf-8 dump.sql > dump.utf-8.sql
  iconv: illegal input sequence at position 29618109

apt install moreutils
isutf8 dump.sql 
  dump.sql: line 2995, char 42, byte 29618109: Expecting bytes in the following ranges: 00..7F C2..F4.

And this is a image line:

INSERT INTO `customavatar` VALUES (6355,'ÿØÿà\0^PJFIF\0^A^A\0\0^A\0^A\0\0ÿþ\0;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 75

And before I delete the line using vim I need to increase the size of the partitions as it is a 1.4G file and I’m running out of space when editing it…

1 me gusta

The problem was a user with &#55357;&#56444; in the username field, once the HTML entities were removed the import script ran, but there were a lot of errors like this:

ERR Error running script (call to f_b06356ba4628144e123b652c99605b873107c9be): @user_script:14: @user_script: 14: -MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error. 

Is this something that I should be concerned about and something that I should fix and then redo the import?

Are you out of disk space?

1 me gusta

Yes! I’m now spinning up a new virtual server with a huge amount of disk space, CPUs and RAM and I’m going to start from scratch…

By the way, I’m following the instructions above for the Docker version and found that I needed to add an additional step in the container

echo "discourse ALL = NOPASSWD: ALL" >> /etc/sudoers

Before running:

su discourse -c 'bundle install --no-deployment --without test --without development'

In the non-docker instructions above there is this step to delete data from the database before doing the import:

  • Clear existing data from your local Discourse instance
cd ~/discourse
bundle exec rake db:drop db:create db:migrate

Was this omitted from the Docker instructions on purpose?

1 me gusta

There are two, different, vbulletin import scripts, in the docker container:

cd /var/www/discourse
find ./ -name vbulletin.rb
./script/bulk_import/vbulletin.rb
./script/import_scripts/vbulletin.rb

The second one is twice the size of the first one and it is the one I have been using.