A platform for community discussion. Free, open, simple.
DEV: Apply syntax_tree formatting to `script/*`
David Taylor436b3b392b9c
diff --git a/.streerc b/.streercindex 8a004597732..612e4b246dc 100644--- a/.streerc+++ b/.streerc@@ -5,5 +5,4 @@--ignore-files=config/*--ignore-files=db/*--ignore-files=lib/*---ignore-files=script/*--ignore-files=spec/*diff --git a/script/analyse_message_bus.rb b/script/analyse_message_bus.rbindex a65bd53f02f..ef3e0eacb33 100644--- a/script/analyse_message_bus.rb+++ b/script/analyse_message_bus.rb@@ -9,23 +9,24 @@ wait_seconds = ARGV[0]&.to_i || 10puts "Counting messages for #{wait_seconds} seconds..."-print 'Seen 0 messages'-t = Thread.new do- MessageBus.backend_instance.global_subscribe do |m|- channel = m.channel- if channel.start_with?("/distributed_hash")- payload = JSON.parse(m.data)["data"]- info = payload["hash_key"]- # info += ".#{payload["key"]}" # Uncomment if you need more granular info- channel += " (#{info})"- end+print "Seen 0 messages"+t =+ Thread.new do+ MessageBus.backend_instance.global_subscribe do |m|+ channel = m.channel+ if channel.start_with?("/distributed_hash")+ payload = JSON.parse(m.data)["data"]+ info = payload["hash_key"]+ # info += ".#{payload["key"]}" # Uncomment if you need more granular info+ channel += " (#{info})"+ end- channel_counters[channel] += 1- messages_seen += 1+ channel_counters[channel] += 1+ messages_seen += 1- print "\rSeen #{messages_seen} messages from #{channel_counters.size} channels"+ print "\rSeen #{messages_seen} messages from #{channel_counters.size} channels"+ endend-endsleep wait_seconds@@ -53,10 +54,12 @@ puts "| #{"channel".ljust(max_channel_name_length)} | #{"message count".rjust(maputs "|#{"-" * (max_channel_name_length + 2)}|#{"-" * (max_count_length + 2)}|"result_count = 10-sorted_results.first(result_count).each do |name, value|- name = "`#{name}`"- puts "| #{name.ljust(max_channel_name_length)} | #{value.to_s.rjust(max_count_length)} |"-end+sorted_results+ .first(result_count)+ .each do |name, value|+ name = "`#{name}`"+ puts "| #{name.ljust(max_channel_name_length)} | #{value.to_s.rjust(max_count_length)} |"+ endother_count = messages_seen - sorted_results.first(result_count).sum { |k, v| v }puts "| #{"(other)".ljust(max_channel_name_length)} | #{other_count.to_s.rjust(max_count_length)} |"puts "|#{" " * (max_channel_name_length + 2)}|#{" " * (max_count_length + 2)}|"diff --git a/script/analyze_sidekiq_queues.rb b/script/analyze_sidekiq_queues.rbindex fcb736d7624..d5e9c4fd34e 100644--- a/script/analyze_sidekiq_queues.rb+++ b/script/analyze_sidekiq_queues.rb@@ -2,17 +2,14 @@require File.expand_path("../../config/environment", __FILE__)-queues = %w{default low ultra_low critical}.map { |name| Sidekiq::Queue.new(name) }.lazy.flat_map(&:lazy)+queues =+ %w[default low ultra_low critical].map { |name| Sidekiq::Queue.new(name) }.lazy.flat_map(&:lazy)stats = Hash.new(0)-queues.each do |j|- stats[j.klass] += 1-end+queues.each { |j| stats[j.klass] += 1 }-stats.sort_by { |a, b| -b }.each do |name, count|- puts "#{name}: #{count}"-end+stats.sort_by { |a, b| -b }.each { |name, count| puts "#{name}: #{count}" }dupes = Hash.new([])queues.each do |j|diff --git a/script/bench.rb b/script/bench.rbindex e114cdd2cbf..6e10dcd1125 100644--- a/script/bench.rb+++ b/script/bench.rb@@ -19,46 +19,43 @@ require "uri"@skip_asset_bundle = false@unicorn_workers = 3-opts = OptionParser.new do |o|- o.banner = "Usage: ruby bench.rb [options]"-- o.on("-n", "--with_default_env", "Include recommended Discourse env") do- @include_env = true- end- o.on("-o", "--output [FILE]", "Output results to this file") do |f|- @result_file = f- end- o.on("-i", "--iterations [ITERATIONS]", "Number of iterations to run the bench for") do |i|- @iterations = i.to_i- end- o.on("-b", "--best_of [NUM]", "Number of times to run the bench taking best as result") do |i|- @best_of = i.to_i- end- o.on("-d", "--heap_dump") do- @dump_heap = true- # We need an env var for config/boot.rb to enable allocation tracing prior to framework init- ENV['DISCOURSE_DUMP_HEAP'] = "1"- end- o.on("-m", "--memory_stats") do- @mem_stats = true- end- o.on("-u", "--unicorn", "Use unicorn to serve pages as opposed to puma") do- @unicorn = true- end- o.on("-c", "--concurrency [NUM]", "Run benchmark with this number of concurrent requests (default: 1)") do |i|- @concurrency = i.to_i- end- o.on("-w", "--unicorn_workers [NUM]", "Run benchmark with this number of unicorn workers (default: 3)") do |i|- @unicorn_workers = i.to_i- end- o.on("-s", "--skip-bundle-assets", "Skip bundling assets") do- @skip_asset_bundle = true- end-- o.on("-t", "--tests [STRING]", "List of tests to run. Example: '--tests topic,categories')") do |i|- @tests = i.split(",")+opts =+ OptionParser.new do |o|+ o.banner = "Usage: ruby bench.rb [options]"++ o.on("-n", "--with_default_env", "Include recommended Discourse env") { @include_env = true }+ o.on("-o", "--output [FILE]", "Output results to this file") { |f| @result_file = f }+ o.on("-i", "--iterations [ITERATIONS]", "Number of iterations to run the bench for") do |i|+ @iterations = i.to_i+ end+ o.on("-b", "--best_of [NUM]", "Number of times to run the bench taking best as result") do |i|+ @best_of = i.to_i+ end+ o.on("-d", "--heap_dump") do+ @dump_heap = true+ # We need an env var for config/boot.rb to enable allocation tracing prior to framework init+ ENV["DISCOURSE_DUMP_HEAP"] = "1"+ end+ o.on("-m", "--memory_stats") { @mem_stats = true }+ o.on("-u", "--unicorn", "Use unicorn to serve pages as opposed to puma") { @unicorn = true }+ o.on(+ "-c",+ "--concurrency [NUM]",+ "Run benchmark with this number of concurrent requests (default: 1)",+ ) { |i| @concurrency = i.to_i }+ o.on(+ "-w",+ "--unicorn_workers [NUM]",+ "Run benchmark with this number of unicorn workers (default: 3)",+ ) { |i| @unicorn_workers = i.to_i }+ o.on("-s", "--skip-bundle-assets", "Skip bundling assets") { @skip_asset_bundle = true }++ o.on(+ "-t",+ "--tests [STRING]",+ "List of tests to run. Example: '--tests topic,categories')",+ ) { |i| @tests = i.split(",") }end-endopts.parse!def run(command, opt = nil)@@ -73,7 +70,7 @@ def run(command, opt = nil)endbegin- require 'facter'+ require "facter"raise LoadError if Gem::Version.new(Facter.version) < Gem::Version.new("4.0")rescue LoadErrorrun "gem install facter"@@ -113,7 +110,7 @@ endputs "Ensuring config is setup"-%x{which ab > /dev/null 2>&1}+`which ab > /dev/null 2>&1`unless $? == 0abort "Apache Bench is not installed. Try: apt-get install apache2-utils or brew install ab"end@@ -125,7 +122,7 @@ endENV["RAILS_ENV"] = "profile"-discourse_env_vars = %w(+discourse_env_vars = %w[DISCOURSE_DUMP_HEAPRUBY_GC_HEAP_INIT_SLOTSRUBY_GC_HEAP_FREE_SLOTS@@ -140,27 +137,22 @@ discourse_env_vars = %w(RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTORRUBY_GLOBAL_METHOD_CACHE_SIZELD_PRELOAD-)+]if @include_envputs "Running with tuned environment"- discourse_env_vars.each do |v|- ENV.delete v- end-- ENV['RUBY_GLOBAL_METHOD_CACHE_SIZE'] = '131072'- ENV['RUBY_GC_HEAP_GROWTH_MAX_SLOTS'] = '40000'- ENV['RUBY_GC_HEAP_INIT_SLOTS'] = '400000'- ENV['RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR'] = '1.5'+ discourse_env_vars.each { |v| ENV.delete v }+ ENV["RUBY_GLOBAL_METHOD_CACHE_SIZE"] = "131072"+ ENV["RUBY_GC_HEAP_GROWTH_MAX_SLOTS"] = "40000"+ ENV["RUBY_GC_HEAP_INIT_SLOTS"] = "400000"+ ENV["RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR"] = "1.5"else# clean envputs "Running with the following custom environment"end-discourse_env_vars.each do |w|- puts "#{w}: #{ENV[w]}" if ENV[w].to_s.length > 0-end+discourse_env_vars.each { |w| puts "#{w}: #{ENV[w]}" if ENV[w].to_s.length > 0 }def port_available?(port)server = TCPServer.open("0.0.0.0", port)@@ -170,20 +162,16 @@ rescue Errno::EADDRINUSEfalseend-@port = 60079+@port = 60_079-while !port_available? @port- @port += 1-end+@port += 1 while !port_available? @portputs "Ensuring profiling DB exists and is migrated"puts `bundle exec rake db:create``bundle exec rake db:migrate`puts "Timing loading Rails"-measure("load_rails") do- `bundle exec rake middleware`-end+measure("load_rails") { `bundle exec rake middleware` }puts "Populating Profile DB"run("bundle exec ruby script/profile_db_generator.rb")@@ -223,16 +211,21 @@ beginpid =if @unicorn- ENV['UNICORN_PORT'] = @port.to_s- ENV['UNICORN_WORKERS'] = @unicorn_workers.to_s- FileUtils.mkdir_p(File.join('tmp', 'pids'))+ ENV["UNICORN_PORT"] = @port.to_s+ ENV["UNICORN_WORKERS"] = @unicorn_workers.to_s+ FileUtils.mkdir_p(File.join("tmp", "pids"))unicorn_pid = spawn("bundle exec unicorn -c config/unicorn.conf.rb")- while (unicorn_master_pid = `ps aux | grep "unicorn master" | grep -v "grep" | awk '{print $2}'`.strip.to_i) == 0+ while (+ unicorn_master_pid =+ `ps aux | grep "unicorn master" | grep -v "grep" | awk '{print $2}'`.strip.to_i+ ) == 0sleep 1end- while `ps -f --ppid #{unicorn_master_pid} | grep worker | awk '{ print $2 }'`.split("\n").map(&:to_i).size != @unicorn_workers.to_i+ while `ps -f --ppid #{unicorn_master_pid} | grep worker | awk '{ print $2 }'`.split("\n")+ .map(&:to_i)+ .size != @unicorn_workers.to_isleep 1end@@ -241,48 +234,38 @@ beginspawn("bundle exec puma -p #{@port} -e production")end- while port_available? @port- sleep 1- end+ sleep 1 while port_available? @portputs "Starting benchmark..."- admin_headers = {- 'Api-Key' => admin_api_key,- 'Api-Username' => "admin1"- }+ admin_headers = { "Api-Key" => admin_api_key, "Api-Username" => "admin1" }- user_headers = {- 'User-Api-Key' => user_api_key- }+ user_headers = { "User-Api-Key" => user_api_key }# asset precompilation is a dog, wget to force itrun "curl -s -o /dev/null http://127.0.0.1:#{@port}/"redirect_response = `curl -s -I "http://127.0.0.1:#{@port}/t/i-am-a-topic-used-for-perf-tests"`- if redirect_response !~ /301 Moved Permanently/- raise "Unable to locate topic for perf tests"- end+ raise "Unable to locate topic for perf tests" if redirect_response !~ /301 Moved Permanently/- topic_url = redirect_response.match(/^location: .+(\/t\/i-am-a-topic-used-for-perf-tests\/.+)$/i)[1].strip+ topic_url =+ redirect_response.match(%r{^location: .+(/t/i-am-a-topic-used-for-perf-tests/.+)$}i)[1].stripall_tests = [- ["categories", "/categories"],- ["home", "/"],+ %w[categories /categories],+ %w[home /],["topic", topic_url],["topic.json", "#{topic_url}.json"],["user activity", "/u/admin1/activity"],]- @tests ||= %w{categories home topic}+ @tests ||= %w[categories home topic]- tests_to_run = all_tests.select do |test_name, path|- @tests.include?(test_name)- end+ tests_to_run = all_tests.select { |test_name, path| @tests.include?(test_name) }tests_to_run.concat(tests_to_run.map { |k, url| ["#{k} user", "#{url}", user_headers] },- tests_to_run.map { |k, url| ["#{k} admin", "#{url}", admin_headers] }+ tests_to_run.map { |k, url| ["#{k} admin", "#{url}", admin_headers] },)tests_to_run.each do |test_name, path, headers_for_path|@@ -290,15 +273,11 @@ beginhttp = Net::HTTP.new(uri.host, uri.port)request = Net::HTTP::Get.new(uri.request_uri)- headers_for_path&.each do |key, value|- request[key] = value- end+ headers_for_path&.each { |key, value| request[key] = value }response = http.request(request)- if response.code != "200"- raise "#{test_name} #{path} returned non 200 response code"- end+ raise "#{test_name} #{path} returned non 200 response code" if response.code != "200"end# NOTE: we run the most expensive page first in the bench@@ -335,11 +314,17 @@ beginFacter.resetfacts = Facter.to_hash- facts.delete_if { |k, v|- !["operatingsystem", "architecture", "kernelversion",- "memorysize", "physicalprocessorcount", "processor0",- "virtual"].include?(k)- }+ facts.delete_if do |k, v|+ !%w[+ operatingsystem+ architecture+ kernelversion+ memorysize+ physicalprocessorcount+ processor0+ virtual+ ].include?(k)+ endrun("RAILS_ENV=profile bundle exec rake assets:clean")@@ -349,10 +334,13 @@ beginmem = get_mem(pid)- results = results.merge("timings" => @timings,- "ruby-version" => "#{RUBY_DESCRIPTION}",- "rss_kb" => mem["rss_kb"],- "pss_kb" => mem["pss_kb"]).merge(facts)+ results =+ results.merge(+ "timings" => @timings,+ "ruby-version" => "#{RUBY_DESCRIPTION}",+ "rss_kb" => mem["rss_kb"],+ "pss_kb" => mem["pss_kb"],+ ).merge(facts)if @unicornchild_pids = `ps --ppid #{pid} | awk '{ print $1; }' | grep -v PID`.split("\n")@@ -375,12 +363,7 @@ beginputs open("http://127.0.0.1:#{@port}/admin/dump_heap", headers).readend- if @result_file- File.open(@result_file, "wb") do |f|- f.write(results)- end- end-+ File.open(@result_file, "wb") { |f| f.write(results) } if @result_fileensureProcess.kill "KILL", pidenddiff --git a/script/benchmarks/cache/bench.rb b/script/benchmarks/cache/bench.rbindex fad1b73607a..87d4a1e4d30 100644--- a/script/benchmarks/cache/bench.rb+++ b/script/benchmarks/cache/bench.rb@@ -1,10 +1,9 @@# frozen_string_literal: true-require 'benchmark/ips'-require File.expand_path('../../../../config/environment', __FILE__)+require "benchmark/ips"+require File.expand_path("../../../../config/environment", __FILE__)Benchmark.ips do |x|-x.report("redis setex string") do |times|while times > 0Discourse.redis.setex("test_key", 60, "test")diff --git a/script/benchmarks/markdown/bench.rb b/script/benchmarks/markdown/bench.rbindex 00bd7573d8d..5e54d61755b 100644--- a/script/benchmarks/markdown/bench.rb+++ b/script/benchmarks/markdown/bench.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require 'benchmark/ips'-require File.expand_path('../../../../config/environment', __FILE__)+require "benchmark/ips"+require File.expand_path("../../../../config/environment", __FILE__)# set any flags here# MiniRacer::Platform.set_flags! :noturbo@@ -10,7 +10,7 @@ tests = [["tiny post", "**hello**"],["giant post", File.read("giant_post.md")],["most features", File.read("most_features.md")],- ["lots of mentions", File.read("lots_of_mentions.md")]+ ["lots of mentions", File.read("lots_of_mentions.md")],]PrettyText.cook("")@@ -31,9 +31,7 @@ PrettyText.v8.eval("window.commonmark = window.markdownit('commonmark')")Benchmark.ips do |x|[true, false].each do |sanitize|tests.each do |test, text|- x.report("#{test} sanitize: #{sanitize}") do- PrettyText.markdown(text, sanitize: sanitize)- end+ x.report("#{test} sanitize: #{sanitize}") { PrettyText.markdown(text, sanitize: sanitize) }endenddiff --git a/script/benchmarks/middleware/test.rb b/script/benchmarks/middleware/test.rbindex 1432b9227e2..8b0cca5f6ea 100644--- a/script/benchmarks/middleware/test.rb+++ b/script/benchmarks/middleware/test.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require 'memory_profiler'-require 'benchmark/ips'+require "memory_profiler"+require "benchmark/ips"ENV["RAILS_ENV"] = "production"@@ -14,12 +14,10 @@ def req"timings[1]" => "1001","timings[2]" => "1001","timings[3]" => "1001",- "topic_id" => "490310"+ "topic_id" => "490310",}- data = data.map do |k, v|- "#{CGI.escape(k)}=#{v}"- end.join("&")+ data = data.map { |k, v| "#{CGI.escape(k)}=#{v}" }.join("&"){"REQUEST_METHOD" => "POST",@@ -33,7 +31,7 @@ def req"HTTP_COOKIE" => "_t=#{_t}","rack.input" => StringIO.new(data),"rack.version" => [1, 2],- "rack.url_scheme" => "http"+ "rack.url_scheme" => "http",}end@@ -45,11 +43,7 @@ endexit##-StackProf.run(mode: :wall, out: 'report.dump') do- 1000.times do- Rails.application.call(req)- end-end+StackProf.run(mode: :wall, out: "report.dump") { 1000.times { Rails.application.call(req) } }## MemoryProfiler.start# Rails.application.call(req)diff --git a/script/benchmarks/site_setting/bench.rb b/script/benchmarks/site_setting/bench.rbindex 5790b41ffa8..02676e8570d 100644--- a/script/benchmarks/site_setting/bench.rb+++ b/script/benchmarks/site_setting/bench.rb@@ -1,37 +1,32 @@# frozen_string_literal: true-require 'benchmark/ips'-require File.expand_path('../../../../config/environment', __FILE__)+require "benchmark/ips"+require File.expand_path("../../../../config/environment", __FILE__)# Put pre conditions here# Used db but it's OK in the most cases# build the cacheSiteSetting.title = SecureRandom.hex-SiteSetting.default_locale = SiteSetting.default_locale == 'en' ? 'zh_CN' : 'en'+SiteSetting.default_locale = SiteSetting.default_locale == "en" ? "zh_CN" : "en"SiteSetting.refresh!tests = [- ["current cache", lambda do- SiteSetting.title- SiteSetting.enable_discourse_connect- end+ [+ "current cache",+ lambda do+ SiteSetting.title+ SiteSetting.enable_discourse_connect+ end,],- ["change default locale with current cache refreshed", lambda do- SiteSetting.default_locale = SiteSetting.default_locale == 'en' ? 'zh_CN' : 'en'- end- ],- ["change site setting", lambda do- SiteSetting.title = SecureRandom.hex- end+ [+ "change default locale with current cache refreshed",+ lambda { SiteSetting.default_locale = SiteSetting.default_locale == "en" ? "zh_CN" : "en" },],+ ["change site setting", lambda { SiteSetting.title = SecureRandom.hex }],]-Benchmark.ips do |x|- tests.each do |test, proc|- x.report(test, proc)- end-end+Benchmark.ips { |x| tests.each { |test, proc| x.report(test, proc) } }# 2017-08-02 - Erick's Site Setting changediff --git a/script/benchmarks/site_setting/profile.rb b/script/benchmarks/site_setting/profile.rbindex a849a18a363..fea7977b866 100644--- a/script/benchmarks/site_setting/profile.rb+++ b/script/benchmarks/site_setting/profile.rb@@ -1,34 +1,26 @@# frozen_string_literal: true-require 'ruby-prof'+require "ruby-prof"def profile(&blk)result = RubyProf.profile(&blk)printer = RubyProf::GraphHtmlPrinter.new(result)printer.print(STDOUT)end-profile { '' } # loading profiler dependency+profile { "" } # loading profiler dependency-require File.expand_path('../../../../config/environment', __FILE__)+require File.expand_path("../../../../config/environment", __FILE__)# warming upSiteSetting.titleSiteSetting.enable_discourse_connect-SiteSetting.default_locale = SiteSetting.default_locale == 'en' ? 'zh_CN' : 'en'+SiteSetting.default_locale = SiteSetting.default_locale == "en" ? "zh_CN" : "en"SiteSetting.title = SecureRandom.hex-profile do- SiteSetting.title-end+profile { SiteSetting.title }-profile do- SiteSetting.enable_discourse_connect-end+profile { SiteSetting.enable_discourse_connect }-profile do- SiteSetting.default_locale = SiteSetting.default_locale == 'en' ? 'zh_CN' : 'en'-end+profile { SiteSetting.default_locale = SiteSetting.default_locale == "en" ? "zh_CN" : "en" }-profile do- SiteSetting.title = SecureRandom.hex-end+profile { SiteSetting.title = SecureRandom.hex }diff --git a/script/biggest_objects.rb b/script/biggest_objects.rbindex 3f99cf109b4..220fff3c00d 100644--- a/script/biggest_objects.rb+++ b/script/biggest_objects.rb@@ -2,35 +2,41 @@# simple script to measure largest objects in memory post boot-if ENV['RAILS_ENV'] != "production"- exec "RAILS_ENV=production ruby #{__FILE__}"-end+exec "RAILS_ENV=production ruby #{__FILE__}" if ENV["RAILS_ENV"] != "production"-require 'objspace'+require "objspace"ObjectSpace.trace_object_allocations do-require File.expand_path("../../config/environment", __FILE__)- Rails.application.routes.recognize_path('abc') rescue nil+ begin+ Rails.application.routes.recognize_path("abc")+ rescue StandardError+ nil+ end# load up the yaml for the localization bits, in master processI18n.t(:posts)RailsMultisite::ConnectionManagement.each_connection do(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|- table.classify.constantize.first rescue nil+ begin+ table.classify.constantize.first+ rescue StandardError+ nil+ endendend-end-5.times do- GC.start(full_mark: true, immediate_sweep: true)-end+5.times { GC.start(full_mark: true, immediate_sweep: true) }[String, Array, Hash].each do |klass|- ObjectSpace.each_object(klass).sort { |a, b| b.length <=> a.length }.first(50).each do |obj|- puts "#{klass} size: #{obj.length} #{ObjectSpace.allocation_sourcefile(obj)} #{ObjectSpace.allocation_sourceline(obj)}"- end+ ObjectSpace+ .each_object(klass)+ .sort { |a, b| b.length <=> a.length }+ .first(50)+ .each do |obj|+ puts "#{klass} size: #{obj.length} #{ObjectSpace.allocation_sourcefile(obj)} #{ObjectSpace.allocation_sourceline(obj)}"+ endenddiff --git a/script/boot_mem.rb b/script/boot_mem.rbindex 5780ae6058d..44fb2b84074 100644--- a/script/boot_mem.rb+++ b/script/boot_mem.rb@@ -2,22 +2,30 @@# simple script to measure memory at boot-if ENV['RAILS_ENV'] != "production"- exec "RAILS_ENV=production ruby #{__FILE__}"-end+exec "RAILS_ENV=production ruby #{__FILE__}" if ENV["RAILS_ENV"] != "production"-require 'memory_profiler'+require "memory_profiler"-MemoryProfiler.report do- require File.expand_path("../../config/environment", __FILE__)+MemoryProfiler+ .report do+ require File.expand_path("../../config/environment", __FILE__)- Rails.application.routes.recognize_path('abc') rescue nil+ begin+ Rails.application.routes.recognize_path("abc")+ rescue StandardError+ nil+ end- # load up the yaml for the localization bits, in master process- I18n.t(:posts)+ # load up the yaml for the localization bits, in master process+ I18n.t(:posts)- # load up all models and schema- (ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|- table.classify.constantize.first rescue nil+ # load up all models and schema+ (ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|+ begin+ table.classify.constantize.first+ rescue StandardError+ nil+ end+ endend-end.pretty_print+ .pretty_printdiff --git a/script/bulk_import/base.rb b/script/bulk_import/base.rbindex 767469a83bf..d92878b705b 100644--- a/script/bulk_import/base.rb+++ b/script/bulk_import/base.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-if ARGV.include?('bbcode-to-md')+if ARGV.include?("bbcode-to-md")# Replace (most) bbcode with markdown before creating posts.# This will dramatically clean up the final posts in Discourse.#@@ -10,7 +10,7 @@ if ARGV.include?('bbcode-to-md')# cd ruby-bbcode-to-md# gem build ruby-bbcode-to-md.gemspec# gem install ruby-bbcode-to-md-*.gem- require 'ruby-bbcode-to-md'+ require "ruby-bbcode-to-md"endrequire "pg"@@ -20,12 +20,12 @@ require "htmlentities"puts "Loading application..."require_relative "../../config/environment"-require_relative '../import_scripts/base/uploader'+require_relative "../import_scripts/base/uploader"-module BulkImport; end+module BulkImport+endclass BulkImport::Base-NOW ||= "now()"PRIVATE_OFFSET ||= 2**30@@ -33,41 +33,41 @@ class BulkImport::BaseCHARSET_MAP = {"armscii8" => nil,- "ascii" => Encoding::US_ASCII,- "big5" => Encoding::Big5,- "binary" => Encoding::ASCII_8BIT,- "cp1250" => Encoding::Windows_1250,- "cp1251" => Encoding::Windows_1251,- "cp1256" => Encoding::Windows_1256,- "cp1257" => Encoding::Windows_1257,- "cp850" => Encoding::CP850,- "cp852" => Encoding::CP852,- "cp866" => Encoding::IBM866,- "cp932" => Encoding::Windows_31J,- "dec8" => nil,- "eucjpms" => Encoding::EucJP_ms,- "euckr" => Encoding::EUC_KR,- "gb2312" => Encoding::EUC_CN,- "gbk" => Encoding::GBK,- "geostd8" => nil,- "greek" => Encoding::ISO_8859_7,- "hebrew" => Encoding::ISO_8859_8,- "hp8" => nil,- "keybcs2" => nil,- "koi8r" => Encoding::KOI8_R,- "koi8u" => Encoding::KOI8_U,- "latin1" => Encoding::ISO_8859_1,- "latin2" => Encoding::ISO_8859_2,- "latin5" => Encoding::ISO_8859_9,- "latin7" => Encoding::ISO_8859_13,- "macce" => Encoding::MacCentEuro,+ "ascii" => Encoding::US_ASCII,+ "big5" => Encoding::Big5,+ "binary" => Encoding::ASCII_8BIT,+ "cp1250" => Encoding::Windows_1250,+ "cp1251" => Encoding::Windows_1251,+ "cp1256" => Encoding::Windows_1256,+ "cp1257" => Encoding::Windows_1257,+ "cp850" => Encoding::CP850,+ "cp852" => Encoding::CP852,+ "cp866" => Encoding::IBM866,+ "cp932" => Encoding::Windows_31J,+ "dec8" => nil,+ "eucjpms" => Encoding::EucJP_ms,+ "euckr" => Encoding::EUC_KR,+ "gb2312" => Encoding::EUC_CN,+ "gbk" => Encoding::GBK,+ "geostd8" => nil,+ "greek" => Encoding::ISO_8859_7,+ "hebrew" => Encoding::ISO_8859_8,+ "hp8" => nil,+ "keybcs2" => nil,+ "koi8r" => Encoding::KOI8_R,+ "koi8u" => Encoding::KOI8_U,+ "latin1" => Encoding::ISO_8859_1,+ "latin2" => Encoding::ISO_8859_2,+ "latin5" => Encoding::ISO_8859_9,+ "latin7" => Encoding::ISO_8859_13,+ "macce" => Encoding::MacCentEuro,"macroman" => Encoding::MacRoman,- "sjis" => Encoding::SHIFT_JIS,- "swe7" => nil,- "tis620" => Encoding::TIS_620,- "ucs2" => Encoding::UTF_16BE,- "ujis" => Encoding::EucJP_ms,- "utf8" => Encoding::UTF_8,+ "sjis" => Encoding::SHIFT_JIS,+ "swe7" => nil,+ "tis620" => Encoding::TIS_620,+ "ucs2" => Encoding::UTF_16BE,+ "ujis" => Encoding::EucJP_ms,+ "utf8" => Encoding::UTF_8,}# rubocop:enable Layout/HashAlignment@@ -82,12 +82,13 @@ class BulkImport::Base@encoding = CHARSET_MAP[charset]@bbcode_to_md = true if use_bbcode_to_md?- @markdown = Redcarpet::Markdown.new(- Redcarpet::Render::HTML.new(hard_wrap: true),- no_intra_emphasis: true,- fenced_code_blocks: true,- autolink: true- )+ @markdown =+ Redcarpet::Markdown.new(+ Redcarpet::Render::HTML.new(hard_wrap: true),+ no_intra_emphasis: true,+ fenced_code_blocks: true,+ autolink: true,+ )enddef run@@ -132,7 +133,9 @@ class BulkImport::Basemap = []ids = []- @raw_connection.send_query("SELECT value, #{name}_id FROM #{name}_custom_fields WHERE name = 'import_id'")+ @raw_connection.send_query(+ "SELECT value, #{name}_id FROM #{name}_custom_fields WHERE name = 'import_id'",+ )@raw_connection.set_single_row_mode@raw_connection.get_result.stream_each do |row|@@ -163,12 +166,14 @@ class BulkImport::Baseputs "Loading imported topic ids..."@topics, imported_topic_ids = imported_ids("topic")@last_imported_topic_id = imported_topic_ids.select { |id| id < PRIVATE_OFFSET }.max || -1- @last_imported_private_topic_id = imported_topic_ids.select { |id| id > PRIVATE_OFFSET }.max || (PRIVATE_OFFSET - 1)+ @last_imported_private_topic_id =+ imported_topic_ids.select { |id| id > PRIVATE_OFFSET }.max || (PRIVATE_OFFSET - 1)puts "Loading imported post ids..."@posts, imported_post_ids = imported_ids("post")@last_imported_post_id = imported_post_ids.select { |id| id < PRIVATE_OFFSET }.max || -1- @last_imported_private_post_id = imported_post_ids.select { |id| id > PRIVATE_OFFSET }.max || (PRIVATE_OFFSET - 1)+ @last_imported_private_post_id =+ imported_post_ids.select { |id| id > PRIVATE_OFFSET }.max || (PRIVATE_OFFSET - 1)enddef last_id(klass)@@ -182,9 +187,7 @@ class BulkImport::Base@raw_connection.send_query("SELECT id, #{column} FROM #{name}")@raw_connection.set_single_row_mode- @raw_connection.get_result.stream_each do |row|- map[row["id"].to_i] = row[column].to_i- end+ @raw_connection.get_result.stream_each { |row| map[row["id"].to_i] = row[column].to_i }@raw_connection.get_result@@ -199,13 +202,24 @@ class BulkImport::Baseputs "Loading users indexes..."@last_user_id = last_id(User)@last_user_email_id = last_id(UserEmail)- @emails = User.unscoped.joins(:user_emails).pluck(:"user_emails.email", :"user_emails.user_id").to_h+ @emails =+ User.unscoped.joins(:user_emails).pluck(:"user_emails.email", :"user_emails.user_id").to_h@usernames_lower = User.unscoped.pluck(:username_lower).to_set- @mapped_usernames = UserCustomField.joins(:user).where(name: "import_username").pluck("user_custom_fields.value", "users.username").to_h+ @mapped_usernames =+ UserCustomField+ .joins(:user)+ .where(name: "import_username")+ .pluck("user_custom_fields.value", "users.username")+ .to_hputs "Loading categories indexes..."@last_category_id = last_id(Category)- @category_names = Category.unscoped.pluck(:parent_category_id, :name).map { |pci, name| "#{pci}-#{name}" }.to_set+ @category_names =+ Category+ .unscoped+ .pluck(:parent_category_id, :name)+ .map { |pci, name| "#{pci}-#{name}" }+ .to_setputs "Loading topics indexes..."@last_topic_id = last_id(Topic)@@ -233,13 +247,27 @@ class BulkImport::Basedef fix_primary_keysputs "Updating primary key sequences..."- @raw_connection.exec("SELECT setval('#{Group.sequence_name}', #{@last_group_id})") if @last_group_id > 0- @raw_connection.exec("SELECT setval('#{User.sequence_name}', #{@last_user_id})") if @last_user_id > 0- @raw_connection.exec("SELECT setval('#{UserEmail.sequence_name}', #{@last_user_email_id})") if @last_user_email_id > 0- @raw_connection.exec("SELECT setval('#{Category.sequence_name}', #{@last_category_id})") if @last_category_id > 0- @raw_connection.exec("SELECT setval('#{Topic.sequence_name}', #{@last_topic_id})") if @last_topic_id > 0- @raw_connection.exec("SELECT setval('#{Post.sequence_name}', #{@last_post_id})") if @last_post_id > 0- @raw_connection.exec("SELECT setval('#{PostAction.sequence_name}', #{@last_post_action_id})") if @last_post_action_id > 0+ if @last_group_id > 0+ @raw_connection.exec("SELECT setval('#{Group.sequence_name}', #{@last_group_id})")+ end+ if @last_user_id > 0+ @raw_connection.exec("SELECT setval('#{User.sequence_name}', #{@last_user_id})")+ end+ if @last_user_email_id > 0+ @raw_connection.exec("SELECT setval('#{UserEmail.sequence_name}', #{@last_user_email_id})")+ end+ if @last_category_id > 0+ @raw_connection.exec("SELECT setval('#{Category.sequence_name}', #{@last_category_id})")+ end+ if @last_topic_id > 0+ @raw_connection.exec("SELECT setval('#{Topic.sequence_name}', #{@last_topic_id})")+ end+ if @last_post_id > 0+ @raw_connection.exec("SELECT setval('#{Post.sequence_name}', #{@last_post_id})")+ end+ if @last_post_action_id > 0+ @raw_connection.exec("SELECT setval('#{PostAction.sequence_name}', #{@last_post_action_id})")+ endenddef group_id_from_imported_id(id)@@ -272,63 +300,124 @@ class BulkImport::Basepost_id && @topic_id_by_post_id[post_id]end- GROUP_COLUMNS ||= %i{- id name title bio_raw bio_cooked created_at updated_at- }-- USER_COLUMNS ||= %i{- id username username_lower name active trust_level admin moderator- date_of_birth ip_address registration_ip_address primary_group_id- suspended_at suspended_till last_emailed_at created_at updated_at- }-- USER_EMAIL_COLUMNS ||= %i{- id user_id email primary created_at updated_at- }-- USER_STAT_COLUMNS ||= %i{- user_id topics_entered time_read days_visited posts_read_count- likes_given likes_received new_since read_faq- first_post_created_at post_count topic_count bounce_score- reset_bounce_score_after digest_attempted_at- }-- USER_PROFILE_COLUMNS ||= %i{- user_id location website bio_raw bio_cooked views- }-- GROUP_USER_COLUMNS ||= %i{- group_id user_id created_at updated_at- }-- CATEGORY_COLUMNS ||= %i{- id name name_lower slug user_id description position parent_category_id- created_at updated_at- }-- TOPIC_COLUMNS ||= %i{- id archetype title fancy_title slug user_id last_post_user_id category_id- visible closed pinned_at views created_at bumped_at updated_at- }-- POST_COLUMNS ||= %i{- id user_id last_editor_id topic_id post_number sort_order reply_to_post_number- like_count raw cooked hidden word_count created_at last_version_at updated_at- }-- POST_ACTION_COLUMNS ||= %i{- id post_id user_id post_action_type_id deleted_at created_at updated_at- deleted_by_id related_post_id staff_took_action deferred_by_id targets_topic- agreed_at agreed_by_id deferred_at disagreed_at disagreed_by_id- }-- TOPIC_ALLOWED_USER_COLUMNS ||= %i{- topic_id user_id created_at updated_at- }+ GROUP_COLUMNS ||= %i[id name title bio_raw bio_cooked created_at updated_at]- TOPIC_TAG_COLUMNS ||= %i{- topic_id tag_id created_at updated_at- }+ USER_COLUMNS ||= %i[+ id+ username+ username_lower+ name+ active+ trust_level+ admin+ moderator+ date_of_birth+ ip_address+ registration_ip_address+ primary_group_id+ suspended_at+ suspended_till+ last_emailed_at+ created_at+ updated_at+ ]++ USER_EMAIL_COLUMNS ||= %i[id user_id email primary created_at updated_at]++ USER_STAT_COLUMNS ||= %i[+ user_id+ topics_entered+ time_read+ days_visited+ posts_read_count+ likes_given+ likes_received+ new_since+ read_faq+ first_post_created_at+ post_count+ topic_count+ bounce_score+ reset_bounce_score_after+ digest_attempted_at+ ]++ USER_PROFILE_COLUMNS ||= %i[user_id location website bio_raw bio_cooked views]++ GROUP_USER_COLUMNS ||= %i[group_id user_id created_at updated_at]++ CATEGORY_COLUMNS ||= %i[+ id+ name+ name_lower+ slug+ user_id+ description+ position+ parent_category_id+ created_at+ updated_at+ ]++ TOPIC_COLUMNS ||= %i[+ id+ archetype+ title+ fancy_title+ slug+ user_id+ last_post_user_id+ category_id+ visible+ closed+ pinned_at+ views+ created_at+ bumped_at+ updated_at+ ]++ POST_COLUMNS ||= %i[+ id+ user_id+ last_editor_id+ topic_id+ post_number+ sort_order+ reply_to_post_number+ like_count+ raw+ cooked+ hidden+ word_count+ created_at+ last_version_at+ updated_at+ ]++ POST_ACTION_COLUMNS ||= %i[+ id+ post_id+ user_id+ post_action_type_id+ deleted_at+ created_at+ updated_at+ deleted_by_id+ related_post_id+ staff_took_action+ deferred_by_id+ targets_topic+ agreed_at+ agreed_by_id+ deferred_at+ disagreed_at+ disagreed_by_id+ ]++ TOPIC_ALLOWED_USER_COLUMNS ||= %i[topic_id user_id created_at updated_at]++ TOPIC_TAG_COLUMNS ||= %i[topic_id tag_id created_at updated_at]def create_groups(rows, &block)create_records(rows, "group", GROUP_COLUMNS, &block)@@ -340,10 +429,7 @@ class BulkImport::Basecreate_records(rows, "user", USER_COLUMNS, &block)create_custom_fields("user", "username", @imported_usernames.keys) do |username|- {- record_id: @imported_usernames[username],- value: username,- }+ { record_id: @imported_usernames[username], value: username }endend@@ -389,8 +475,8 @@ class BulkImport::Basegroup[:name] = group_nameend- group[:title] = group[:title].scrub.strip.presence if group[:title].present?- group[:bio_raw] = group[:bio_raw].scrub.strip.presence if group[:bio_raw].present?+ group[:title] = group[:title].scrub.strip.presence if group[:title].present?+ group[:bio_raw] = group[:bio_raw].scrub.strip.presence if group[:bio_raw].present?group[:bio_cooked] = pre_cook(group[:bio_raw]) if group[:bio_raw].present?group[:created_at] ||= NOWgroup[:updated_at] ||= group[:created_at]@@ -456,7 +542,9 @@ class BulkImport::Baseuser_email[:email] ||= random_emailuser_email[:email].downcase!# unique email- user_email[:email] = random_email until EmailAddressValidator.valid_value?(user_email[:email]) && [email protected]_key?(user_email[:email])+ user_email[:email] = random_email until EmailAddressValidator.valid_value?(+ user_email[:email],+ ) && [email protected]_key?(user_email[:email])user_emailend@@ -539,7 +627,11 @@ class BulkImport::Basepost[:raw] = (post[:raw] || "").scrub.strip.presence || "<Empty imported post>"post[:raw] = process_raw post[:raw]if @bbcode_to_md- post[:raw] = post[:raw].bbcode_to_md(false, {}, :disable, :quote) rescue post[:raw]+ post[:raw] = begin+ post[:raw].bbcode_to_md(false, {}, :disable, :quote)+ rescue StandardError+ post[:raw]+ endendpost[:like_count] ||= 0post[:cooked] = pre_cook post[:raw]@@ -580,22 +672,22 @@ class BulkImport::Base# [HTML]...[/HTML]raw.gsub!(/\[HTML\]/i, "\n\n```html\n")- raw.gsub!(/\[\/HTML\]/i, "\n```\n\n")+ raw.gsub!(%r{\[/HTML\]}i, "\n```\n\n")# [PHP]...[/PHP]raw.gsub!(/\[PHP\]/i, "\n\n```php\n")- raw.gsub!(/\[\/PHP\]/i, "\n```\n\n")+ raw.gsub!(%r{\[/PHP\]}i, "\n```\n\n")# [HIGHLIGHT="..."]raw.gsub!(/\[HIGHLIGHT="?(\w+)"?\]/i) { "\n\n```#{$1.downcase}\n" }# [CODE]...[/CODE]# [HIGHLIGHT]...[/HIGHLIGHT]- raw.gsub!(/\[\/?CODE\]/i, "\n\n```\n\n")- raw.gsub!(/\[\/?HIGHLIGHT\]/i, "\n\n```\n\n")+ raw.gsub!(%r{\[/?CODE\]}i, "\n\n```\n\n")+ raw.gsub!(%r{\[/?HIGHLIGHT\]}i, "\n\n```\n\n")# [SAMP]...[/SAMP]- raw.gsub!(/\[\/?SAMP\]/i, "`")+ raw.gsub!(%r{\[/?SAMP\]}i, "`")# replace all chevrons with HTML entities# /!\ must be done /!\@@ -609,61 +701,61 @@ class BulkImport::Baseraw.gsub!(">", ">")raw.gsub!("\u2603", ">")- raw.gsub!(/\[\/?I\]/i, "*")- raw.gsub!(/\[\/?B\]/i, "**")- raw.gsub!(/\[\/?U\]/i, "")+ raw.gsub!(%r{\[/?I\]}i, "*")+ raw.gsub!(%r{\[/?B\]}i, "**")+ raw.gsub!(%r{\[/?U\]}i, "")- raw.gsub!(/\[\/?RED\]/i, "")- raw.gsub!(/\[\/?BLUE\]/i, "")+ raw.gsub!(%r{\[/?RED\]}i, "")+ raw.gsub!(%r{\[/?BLUE\]}i, "")- raw.gsub!(/\[AUTEUR\].+?\[\/AUTEUR\]/im, "")- raw.gsub!(/\[VOIRMSG\].+?\[\/VOIRMSG\]/im, "")- raw.gsub!(/\[PSEUDOID\].+?\[\/PSEUDOID\]/im, "")+ raw.gsub!(%r{\[AUTEUR\].+?\[/AUTEUR\]}im, "")+ raw.gsub!(%r{\[VOIRMSG\].+?\[/VOIRMSG\]}im, "")+ raw.gsub!(%r{\[PSEUDOID\].+?\[/PSEUDOID\]}im, "")# [IMG]...[/IMG]- raw.gsub!(/(?:\s*\[IMG\]\s*)+(.+?)(?:\s*\[\/IMG\]\s*)+/im) { "\n\n#{$1}\n\n" }+ raw.gsub!(%r{(?:\s*\[IMG\]\s*)+(.+?)(?:\s*\[/IMG\]\s*)+}im) { "\n\n#{$1}\n\n" }# [IMG=url]raw.gsub!(/\[IMG=([^\]]*)\]/im) { "\n\n#{$1}\n\n" }# [URL=...]...[/URL]- raw.gsub!(/\[URL="?(.+?)"?\](.+?)\[\/URL\]/im) { "[#{$2.strip}](#{$1})" }+ raw.gsub!(%r{\[URL="?(.+?)"?\](.+?)\[/URL\]}im) { "[#{$2.strip}](#{$1})" }# [URL]...[/URL]# [MP3]...[/MP3]# [EMAIL]...[/EMAIL]# [LEFT]...[/LEFT]- raw.gsub!(/\[\/?URL\]/i, "")- raw.gsub!(/\[\/?MP3\]/i, "")- raw.gsub!(/\[\/?EMAIL\]/i, "")- raw.gsub!(/\[\/?LEFT\]/i, "")+ raw.gsub!(%r{\[/?URL\]}i, "")+ raw.gsub!(%r{\[/?MP3\]}i, "")+ raw.gsub!(%r{\[/?EMAIL\]}i, "")+ raw.gsub!(%r{\[/?LEFT\]}i, "")# [FONT=blah] and [COLOR=blah]- raw.gsub!(/\[FONT=.*?\](.*?)\[\/FONT\]/im, "\\1")- raw.gsub!(/\[COLOR=.*?\](.*?)\[\/COLOR\]/im, "\\1")+ raw.gsub!(%r{\[FONT=.*?\](.*?)\[/FONT\]}im, "\\1")+ raw.gsub!(%r{\[COLOR=.*?\](.*?)\[/COLOR\]}im, "\\1")- raw.gsub!(/\[SIZE=.*?\](.*?)\[\/SIZE\]/im, "\\1")- raw.gsub!(/\[H=.*?\](.*?)\[\/H\]/im, "\\1")+ raw.gsub!(%r{\[SIZE=.*?\](.*?)\[/SIZE\]}im, "\\1")+ raw.gsub!(%r{\[H=.*?\](.*?)\[/H\]}im, "\\1")# [CENTER]...[/CENTER]- raw.gsub!(/\[CENTER\](.*?)\[\/CENTER\]/im, "\\1")+ raw.gsub!(%r{\[CENTER\](.*?)\[/CENTER\]}im, "\\1")# [INDENT]...[/INDENT]- raw.gsub!(/\[INDENT\](.*?)\[\/INDENT\]/im, "\\1")- raw.gsub!(/\[TABLE\](.*?)\[\/TABLE\]/im, "\\1")- raw.gsub!(/\[TR\](.*?)\[\/TR\]/im, "\\1")- raw.gsub!(/\[TD\](.*?)\[\/TD\]/im, "\\1")- raw.gsub!(/\[TD="?.*?"?\](.*?)\[\/TD\]/im, "\\1")+ raw.gsub!(%r{\[INDENT\](.*?)\[/INDENT\]}im, "\\1")+ raw.gsub!(%r{\[TABLE\](.*?)\[/TABLE\]}im, "\\1")+ raw.gsub!(%r{\[TR\](.*?)\[/TR\]}im, "\\1")+ raw.gsub!(%r{\[TD\](.*?)\[/TD\]}im, "\\1")+ raw.gsub!(%r{\[TD="?.*?"?\](.*?)\[/TD\]}im, "\\1")# [STRIKE]raw.gsub!(/\[STRIKE\]/i, "<s>")- raw.gsub!(/\[\/STRIKE\]/i, "</s>")+ raw.gsub!(%r{\[/STRIKE\]}i, "</s>")# [QUOTE]...[/QUOTE]raw.gsub!(/\[QUOTE="([^\]]+)"\]/i) { "[QUOTE=#{$1}]" }# Nested Quotes- raw.gsub!(/(\[\/?QUOTE.*?\])/mi) { |q| "\n#{q}\n" }+ raw.gsub!(%r{(\[/?QUOTE.*?\])}mi) { |q| "\n#{q}\n" }# raw.gsub!(/\[QUOTE\](.+?)\[\/QUOTE\]/im) { |quote|# quote.gsub!(/\[QUOTE\](.+?)\[\/QUOTE\]/im) { "\n#{$1}\n" }@@ -686,28 +778,36 @@ class BulkImport::Baseend# [YOUTUBE]<id>[/YOUTUBE]- raw.gsub!(/\[YOUTUBE\](.+?)\[\/YOUTUBE\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }- raw.gsub!(/\[DAILYMOTION\](.+?)\[\/DAILYMOTION\]/i) { "\nhttps://www.dailymotion.com/video/#{$1}\n" }+ raw.gsub!(%r{\[YOUTUBE\](.+?)\[/YOUTUBE\]}i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ raw.gsub!(%r{\[DAILYMOTION\](.+?)\[/DAILYMOTION\]}i) do+ "\nhttps://www.dailymotion.com/video/#{$1}\n"+ end# [VIDEO=youtube;<id>]...[/VIDEO]- raw.gsub!(/\[VIDEO=YOUTUBE;([^\]]+)\].*?\[\/VIDEO\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }- raw.gsub!(/\[VIDEO=DAILYMOTION;([^\]]+)\].*?\[\/VIDEO\]/i) { "\nhttps://www.dailymotion.com/video/#{$1}\n" }+ raw.gsub!(%r{\[VIDEO=YOUTUBE;([^\]]+)\].*?\[/VIDEO\]}i) do+ "\nhttps://www.youtube.com/watch?v=#{$1}\n"+ end+ raw.gsub!(%r{\[VIDEO=DAILYMOTION;([^\]]+)\].*?\[/VIDEO\]}i) do+ "\nhttps://www.dailymotion.com/video/#{$1}\n"+ end# [SPOILER=Some hidden stuff]SPOILER HERE!![/SPOILER]- raw.gsub!(/\[SPOILER="?(.+?)"?\](.+?)\[\/SPOILER\]/im) { "\n#{$1}\n[spoiler]#{$2}[/spoiler]\n" }+ raw.gsub!(%r{\[SPOILER="?(.+?)"?\](.+?)\[/SPOILER\]}im) do+ "\n#{$1}\n[spoiler]#{$2}[/spoiler]\n"+ end# convert list tags to ul and list=1 tags to ol# (basically, we're only missing list=a here...)# (https://meta.discourse.org/t/phpbb-3-importer-old/17397)- raw.gsub!(/\[list\](.*?)\[\/list\]/im, '[ul]\1[/ul]')- raw.gsub!(/\[list=1\|?[^\]]*\](.*?)\[\/list\]/im, '[ol]\1[/ol]')- raw.gsub!(/\[list\](.*?)\[\/list:u\]/im, '[ul]\1[/ul]')- raw.gsub!(/\[list=1\|?[^\]]*\](.*?)\[\/list:o\]/im, '[ol]\1[/ol]')+ raw.gsub!(%r{\[list\](.*?)\[/list\]}im, '[ul]\1[/ul]')+ raw.gsub!(%r{\[list=1\|?[^\]]*\](.*?)\[/list\]}im, '[ol]\1[/ol]')+ raw.gsub!(%r{\[list\](.*?)\[/list:u\]}im, '[ul]\1[/ul]')+ raw.gsub!(%r{\[list=1\|?[^\]]*\](.*?)\[/list:o\]}im, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:- raw.gsub!(/\[\*\]\n/, '')- raw.gsub!(/\[\*\](.*?)\[\/\*:m\]/, '[li]\1[/li]')+ raw.gsub!(/\[\*\]\n/, "")+ raw.gsub!(%r{\[\*\](.*?)\[/\*:m\]}, '[li]\1[/li]')raw.gsub!(/\[\*\](.*?)\n/, '[li]\1[/li]')- raw.gsub!(/\[\*=1\]/, '')+ raw.gsub!(/\[\*=1\]/, "")rawend@@ -728,7 +828,9 @@ class BulkImport::Baseimported_ids |= mapped[:imported_ids] unless mapped[:imported_ids].nil?@raw_connection.put_copy_data columns.map { |c| processed[c] } unless processed[:skip]rows_created += 1- print "\r%7d - %6d/sec" % [rows_created, rows_created.to_f / (Time.now - start)] if rows_created % 100 == 0+ if rows_created % 100 == 0+ print "\r%7d - %6d/sec" % [rows_created, rows_created.to_f / (Time.now - start)]+ endrescue => eputs "\n"puts "ERROR: #{e.message}"@@ -737,15 +839,14 @@ class BulkImport::Baseendend- print "\r%7d - %6d/sec\n" % [rows_created, rows_created.to_f / (Time.now - start)] if rows_created > 0+ if rows_created > 0+ print "\r%7d - %6d/sec\n" % [rows_created, rows_created.to_f / (Time.now - start)]+ endid_mapping_method_name = "#{name}_id_from_imported_id".freezereturn unless respond_to?(id_mapping_method_name)create_custom_fields(name, "id", imported_ids) do |imported_id|- {- record_id: send(id_mapping_method_name, imported_id),- value: imported_id,- }+ { record_id: send(id_mapping_method_name, imported_id), value: imported_id }endrescue => e# FIXME: errors catched here stop the rest of the COPY@@ -755,7 +856,8 @@ class BulkImport::Basedef create_custom_fields(table, name, rows)name = "import_#{name}"- sql = "COPY #{table}_custom_fields (#{table}_id, name, value, created_at, updated_at) FROM STDIN"+ sql =+ "COPY #{table}_custom_fields (#{table}_id, name, value, created_at, updated_at) FROM STDIN"@raw_connection.copy_data(sql, @encoder) dorows.each do |row|next unless cf = yield(row)@@ -797,7 +899,7 @@ class BulkImport::Basecooked = raw# Convert YouTube URLs to lazyYT DOMs before being transformed into links- cooked.gsub!(/\nhttps\:\/\/www.youtube.com\/watch\?v=(\w+)\n/) do+ cooked.gsub!(%r{\nhttps\://www.youtube.com/watch\?v=(\w+)\n}) dovideo_id = $1result = <<-HTML<div class="lazyYT" data-youtube-id="#{video_id}" data-width="480" data-height="270" data-parameters="feature=oembed&wmode=opaque"></div>@@ -807,7 +909,7 @@ class BulkImport::Basecooked = @markdown.render(cooked).scrub.strip- cooked.gsub!(/\[QUOTE="?([^,"]+)(?:, post:(\d+), topic:(\d+))?"?\](.+?)\[\/QUOTE\]/im) do+ cooked.gsub!(%r{\[QUOTE="?([^,"]+)(?:, post:(\d+), topic:(\d+))?"?\](.+?)\[/QUOTE\]}im) dousername, post_id, topic_id, quote = $1, $2, $3, $4quote = quote.scrub.strip@@ -860,5 +962,4 @@ class BulkImport::Basereturn text if @encoding == Encoding::UTF_8text && text.encode(@encoding).force_encoding(Encoding::UTF_8)end-enddiff --git a/script/bulk_import/discourse_merger.rb b/script/bulk_import/discourse_merger.rbindex dc555850b85..61106e6bf35 100644--- a/script/bulk_import/discourse_merger.rb+++ b/script/bulk_import/discourse_merger.rb@@ -3,9 +3,8 @@require_relative "base"class BulkImport::DiscourseMerger < BulkImport::Base-NOW ||= "now()"- CUSTOM_FIELDS = ['category', 'group', 'post', 'topic', 'user']+ CUSTOM_FIELDS = %w[category group post topic user]# DB_NAME: name of database being merged into the current local db# DB_HOST: hostname of database being merged@@ -17,31 +16,36 @@ class BulkImport::DiscourseMerger < BulkImport::Base# e.g. https://discourse-cdn-sjc1.com/business4def initialize- db_password = ENV["DB_PASS"] || 'import_password'+ db_password = ENV["DB_PASS"] || "import_password"local_db = ActiveRecord::Base.connection_db_config.configuration_hash- @raw_connection = PG.connect(dbname: local_db[:database], host: 'localhost', port: local_db[:port], user: 'postgres', password: db_password)+ @raw_connection =+ PG.connect(+ dbname: local_db[:database],+ host: "localhost",+ port: local_db[:port],+ user: "postgres",+ password: db_password,+ )@source_db_config = {- dbname: ENV["DB_NAME"] || 'dd_demo',- host: ENV["DB_HOST"] || 'localhost',- user: 'postgres',- password: db_password+ dbname: ENV["DB_NAME"] || "dd_demo",+ host: ENV["DB_HOST"] || "localhost",+ user: "postgres",+ password: db_password,}- raise "SOURCE_BASE_URL missing!" unless ENV['SOURCE_BASE_URL']+ raise "SOURCE_BASE_URL missing!" unless ENV["SOURCE_BASE_URL"]@source_base_url = ENV["SOURCE_BASE_URL"]- @uploads_path = ENV['UPLOADS_PATH']+ @uploads_path = ENV["UPLOADS_PATH"]@uploader = ImportScripts::Uploader.new- if ENV['SOURCE_CDN']- @source_cdn = ENV['SOURCE_CDN']- end+ @source_cdn = ENV["SOURCE_CDN"] if ENV["SOURCE_CDN"]local_version = @raw_connection.exec("select max(version) from schema_migrations")- local_version = local_version.first['max']+ local_version = local_version.first["max"]source_version = source_raw_connection.exec("select max(version) from schema_migrations")- source_version = source_version.first['max']+ source_version = source_version.first["max"]if local_version != source_versionraise "DB schema mismatch. Databases must be at the same migration version. Local is #{local_version}, other is #{source_version}"@@ -62,7 +66,7 @@ class BulkImport::DiscourseMerger < BulkImport::Base@auto_group_ids = Group::AUTO_GROUPS.values# add your authorized extensions here:- SiteSetting.authorized_extensions = ['jpg', 'jpeg', 'png', 'gif'].join('|')+ SiteSetting.authorized_extensions = %w[jpg jpeg png gif].join("|")@sequences = {}end@@ -99,7 +103,7 @@ class BulkImport::DiscourseMerger < BulkImport::Baseenddef copy_users- puts '', "merging users..."+ puts "", "merging users..."imported_ids = []@@ -109,34 +113,38 @@ class BulkImport::DiscourseMerger < BulkImport::Basesql = "COPY users (#{columns.map { |c| "\"#{c}\"" }.join(",")}) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- source_raw_connection.exec("SELECT #{columns.map { |c| "u.\"#{c}\"" }.join(",")}, e.email FROM users u INNER JOIN user_emails e ON (u.id = e.user_id AND e.primary = TRUE) WHERE u.id > 0").each do |row|- old_user_id = row['id']&.to_i- if existing = UserEmail.where(email: row.delete('email')).first&.user- # Merge these users- @users[old_user_id] = existing.id- @merged_user_ids << old_user_id- next- else- # New user- unless usernames_lower.add?(row['username_lower'])- username = row['username'] + "_1"- username.next! until usernames_lower.add?(username.downcase)- row['username'] = username- row['username_lower'] = row['username'].downcase- end+ source_raw_connection+ .exec(+ "SELECT #{columns.map { |c| "u.\"#{c}\"" }.join(",")}, e.email FROM users u INNER JOIN user_emails e ON (u.id = e.user_id AND e.primary = TRUE) WHERE u.id > 0",+ )+ .each do |row|+ old_user_id = row["id"]&.to_i+ if existing = UserEmail.where(email: row.delete("email")).first&.user+ # Merge these users+ @users[old_user_id] = existing.id+ @merged_user_ids << old_user_id+ next+ else+ # New user+ unless usernames_lower.add?(row["username_lower"])+ username = row["username"] + "_1"+ username.next! until usernames_lower.add?(username.downcase)+ row["username"] = username+ row["username_lower"] = row["username"].downcase+ end- row['id'] = (@last_user_id += 1)- @users[old_user_id] = row['id']+ row["id"] = (@last_user_id += 1)+ @users[old_user_id] = row["id"]- @raw_connection.put_copy_data row.values+ @raw_connection.put_copy_data row.values+ end+ imported_ids << old_user_idend- imported_ids << old_user_id- endend@sequences[User.sequence_name] = @last_user_id + 1 if @last_user_id- create_custom_fields('user', 'id', imported_ids) do |old_user_id|+ create_custom_fields("user", "id", imported_ids) do |old_user_id|{ value: old_user_id, record_id: user_id_from_imported_id(old_user_id) }endend@@ -147,28 +155,32 @@ class BulkImport::DiscourseMerger < BulkImport::Baseskip_if_merged: true,is_a_user_model: true,skip_processing: true,- mapping: @email_tokens+ mapping: @email_tokens,)[- UserEmail, UserStat, UserOption, UserProfile,- UserVisit, UserSearchData, GivenDailyLike, UserSecondFactor- ].each do |c|- copy_model(c, skip_if_merged: true, is_a_user_model: true, skip_processing: true)- end-- [UserAssociatedAccount, Oauth2UserInfo,- SingleSignOnRecord, EmailChangeRequest- ].each do |c|+ UserEmail,+ UserStat,+ UserOption,+ UserProfile,+ UserVisit,+ UserSearchData,+ GivenDailyLike,+ UserSecondFactor,+ ].each { |c| copy_model(c, skip_if_merged: true, is_a_user_model: true, skip_processing: true) }++ [UserAssociatedAccount, Oauth2UserInfo, SingleSignOnRecord, EmailChangeRequest].each do |c|copy_model(c, skip_if_merged: true, is_a_user_model: true)endenddef copy_groups- copy_model(Group,+ copy_model(+ Group,mapping: @groups,skip_processing: true,- select_sql: "SELECT #{Group.columns.map { |c| "\"#{c.name}\"" }.join(', ')} FROM groups WHERE automatic = false"+ select_sql:+ "SELECT #{Group.columns.map { |c| "\"#{c.name}\"" }.join(", ")} FROM groups WHERE automatic = false",)copy_model(GroupUser, skip_if_merged: true)@@ -181,11 +193,12 @@ class BulkImport::DiscourseMerger < BulkImport::Baseimported_ids = []last_id = Category.unscoped.maximum(:id) || 1- sql = "COPY categories (#{columns.map { |c| "\"#{c}\"" }.join(', ')}) FROM STDIN"+ sql = "COPY categories (#{columns.map { |c| "\"#{c}\"" }.join(", ")}) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- source_raw_connection.exec(+ source_raw_connection+ .exec("SELECT concat('/c/', x.parent_slug, '/', x.slug) as path,- #{columns.map { |c| "c.\"#{c}\"" }.join(', ')}+ #{columns.map { |c| "c.\"#{c}\"" }.join(", ")}FROM categories cINNER JOIN (SELECT c1.id AS id,@@ -194,61 +207,55 @@ class BulkImport::DiscourseMerger < BulkImport::BaseFROM categories c1LEFT OUTER JOIN categories c2 ON c1.parent_category_id = c2.id) x ON c.id = x.id- ORDER BY c.id"- ).each do |row|-- # using ORDER BY id to import categories in order of creation.- # this assumes parent categories were created prior to child categories- # and have a lower category id.- #- # without this definition, categories import in different orders in subsequent imports- # and can potentially mess up parent/child structure-- source_category_path = row.delete('path')&.squeeze('/')-- existing = Category.where(slug: row['slug']).first- parent_slug = existing&.parent_category&.slug- if existing &&- source_category_path == "/c/#{parent_slug}/#{existing.slug}".squeeze('/')- @categories[row['id'].to_i] = existing.id- next- elsif existing- # if not the exact path as the source,- # we still need to avoid a unique index conflict on the slug when importing- # if that's the case, we'll append the imported id- row['slug'] = "#{row['slug']}-#{row['id']}"- end+ ORDER BY c.id",+ )+ .each do |row|+ # using ORDER BY id to import categories in order of creation.+ # this assumes parent categories were created prior to child categories+ # and have a lower category id.+ #+ # without this definition, categories import in different orders in subsequent imports+ # and can potentially mess up parent/child structure++ source_category_path = row.delete("path")&.squeeze("/")++ existing = Category.where(slug: row["slug"]).first+ parent_slug = existing&.parent_category&.slug+ if existing && source_category_path == "/c/#{parent_slug}/#{existing.slug}".squeeze("/")+ @categories[row["id"].to_i] = existing.id+ next+ elsif existing+ # if not the exact path as the source,+ # we still need to avoid a unique index conflict on the slug when importing+ # if that's the case, we'll append the imported id+ row["slug"] = "#{row["slug"]}-#{row["id"]}"+ end- old_user_id = row['user_id'].to_i- if old_user_id >= 1- row['user_id'] = user_id_from_imported_id(old_user_id) || -1- end+ old_user_id = row["user_id"].to_i+ row["user_id"] = user_id_from_imported_id(old_user_id) || -1 if old_user_id >= 1- if row['parent_category_id']- row['parent_category_id'] = category_id_from_imported_id(row['parent_category_id'])- end+ if row["parent_category_id"]+ row["parent_category_id"] = category_id_from_imported_id(row["parent_category_id"])+ end- old_id = row['id'].to_i- row['id'] = (last_id += 1)- imported_ids << old_id- @categories[old_id] = row['id']+ old_id = row["id"].to_i+ row["id"] = (last_id += 1)+ imported_ids << old_id+ @categories[old_id] = row["id"]- @raw_connection.put_copy_data(row.values)- end+ @raw_connection.put_copy_data(row.values)+ endend@sequences[Category.sequence_name] = last_id + 1- create_custom_fields('category', 'id', imported_ids) do |imported_id|- {- record_id: category_id_from_imported_id(imported_id),- value: imported_id,- }+ create_custom_fields("category", "id", imported_ids) do |imported_id|+ { record_id: category_id_from_imported_id(imported_id), value: imported_id }endenddef fix_category_descriptions- puts 'updating category description topic ids...'+ puts "updating category description topic ids..."@categories.each do |old_id, new_id|category = Category.find(new_id) if new_id.present?@@ -261,19 +268,21 @@ class BulkImport::DiscourseMerger < BulkImport::Basedef copy_topicscopy_model(Topic, mapping: @topics)- [TopicAllowedGroup, TopicAllowedUser, TopicEmbed, TopicSearchData,- TopicTimer, TopicUser, TopicViewItem- ].each do |k|- copy_model(k, skip_processing: true)- end+ [+ TopicAllowedGroup,+ TopicAllowedUser,+ TopicEmbed,+ TopicSearchData,+ TopicTimer,+ TopicUser,+ TopicViewItem,+ ].each { |k| copy_model(k, skip_processing: true) }enddef copy_postscopy_model(Post, skip_processing: true, mapping: @posts)copy_model(PostAction, mapping: @post_actions)- [PostReply, TopicLink, UserAction, QuotedPost].each do |k|- copy_model(k)- end+ [PostReply, TopicLink, UserAction, QuotedPost].each { |k| copy_model(k) }[PostStat, IncomingEmail, PostDetail, PostRevision].each do |k|copy_model(k, skip_processing: true)end@@ -286,99 +295,101 @@ class BulkImport::DiscourseMerger < BulkImport::Baseimported_ids = []last_id = Tag.unscoped.maximum(:id) || 1- sql = "COPY tags (#{columns.map { |c| "\"#{c}\"" }.join(', ')}) FROM STDIN"+ sql = "COPY tags (#{columns.map { |c| "\"#{c}\"" }.join(", ")}) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- source_raw_connection.exec("SELECT #{columns.map { |c| "\"#{c}\"" }.join(', ')} FROM tags").each do |row|-- if existing = Tag.where_name(row['name']).first- @tags[row['id']] = existing.id- next- end+ source_raw_connection+ .exec("SELECT #{columns.map { |c| "\"#{c}\"" }.join(", ")} FROM tags")+ .each do |row|+ if existing = Tag.where_name(row["name"]).first+ @tags[row["id"]] = existing.id+ next+ end- old_id = row['id']- row['id'] = (last_id += 1)- @tags[old_id.to_s] = row['id']+ old_id = row["id"]+ row["id"] = (last_id += 1)+ @tags[old_id.to_s] = row["id"]- @raw_connection.put_copy_data(row.values)- end+ @raw_connection.put_copy_data(row.values)+ endend@sequences[Tag.sequence_name] = last_id + 1- [TagUser, TopicTag, CategoryTag, CategoryTagStat].each do |k|- copy_model(k)- end+ [TagUser, TopicTag, CategoryTag, CategoryTagStat].each { |k| copy_model(k) }copy_model(TagGroup, mapping: @tag_groups)- [TagGroupMembership, CategoryTagGroup].each do |k|- copy_model(k, skip_processing: true)- end+ [TagGroupMembership, CategoryTagGroup].each { |k| copy_model(k, skip_processing: true) }- col_list = TagGroupPermission.columns.map { |c| "\"#{c.name}\"" }.join(', ')- copy_model(TagGroupPermission,+ col_list = TagGroupPermission.columns.map { |c| "\"#{c.name}\"" }.join(", ")+ copy_model(+ TagGroupPermission,skip_processing: true,- select_sql: "SELECT #{col_list} FROM tag_group_permissions WHERE group_id NOT IN (#{@auto_group_ids.join(', ')})"+ select_sql:+ "SELECT #{col_list} FROM tag_group_permissions WHERE group_id NOT IN (#{@auto_group_ids.join(", ")})",)enddef copy_uploads- puts ''+ puts ""print "copying uploads..."FileUtils.cp_r(- File.join(@uploads_path, '.'),- File.join(Rails.root, 'public', 'uploads', 'default')+ File.join(@uploads_path, "."),+ File.join(Rails.root, "public", "uploads", "default"),)columns = Upload.columns.map(&:name)last_id = Upload.unscoped.maximum(:id) || 1- sql = "COPY uploads (#{columns.map { |c| "\"#{c}\"" }.join(', ')}) FROM STDIN"+ sql = "COPY uploads (#{columns.map { |c| "\"#{c}\"" }.join(", ")}) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- source_raw_connection.exec("SELECT #{columns.map { |c| "\"#{c}\"" }.join(', ')} FROM uploads").each do |row|-- next if Upload.where(sha1: row['sha1']).exists?-- # make sure to get a backup with uploads then convert them to local.- # when the backup is restored to a site with s3 uploads, it will upload the items- # to the bucket- rel_filename = row['url'].gsub(/^\/uploads\/[^\/]+\//, '')- # assumes if coming from amazonaws.com that we want to remove everything- # but the text after the last `/`, which should leave us the filename- rel_filename = rel_filename.gsub(/^\/\/[^\/]+\.amazonaws\.com\/\S+\//, '')- absolute_filename = File.join(@uploads_path, rel_filename)-- old_id = row['id']- if old_id && last_id- row['id'] = (last_id += 1)- @uploads[old_id.to_s] = row['id']- end+ source_raw_connection+ .exec("SELECT #{columns.map { |c| "\"#{c}\"" }.join(", ")} FROM uploads")+ .each do |row|+ next if Upload.where(sha1: row["sha1"]).exists?++ # make sure to get a backup with uploads then convert them to local.+ # when the backup is restored to a site with s3 uploads, it will upload the items+ # to the bucket+ rel_filename = row["url"].gsub(%r{^/uploads/[^/]+/}, "")+ # assumes if coming from amazonaws.com that we want to remove everything+ # but the text after the last `/`, which should leave us the filename+ rel_filename = rel_filename.gsub(%r{^//[^/]+\.amazonaws\.com/\S+/}, "")+ absolute_filename = File.join(@uploads_path, rel_filename)++ old_id = row["id"]+ if old_id && last_id+ row["id"] = (last_id += 1)+ @uploads[old_id.to_s] = row["id"]+ end- old_user_id = row['user_id'].to_i- if old_user_id >= 1- row['user_id'] = user_id_from_imported_id(old_user_id)- next if row['user_id'].nil?- end+ old_user_id = row["user_id"].to_i+ if old_user_id >= 1+ row["user_id"] = user_id_from_imported_id(old_user_id)+ next if row["user_id"].nil?+ end- row['url'] = "/uploads/default/#{rel_filename}" if File.exist?(absolute_filename)+ row["url"] = "/uploads/default/#{rel_filename}" if File.exist?(absolute_filename)- @raw_connection.put_copy_data(row.values)- end+ @raw_connection.put_copy_data(row.values)+ endend@sequences[Upload.sequence_name] = last_id + 1- puts ''+ puts ""copy_model(PostUpload)copy_model(UserAvatar)# Users have a column "uploaded_avatar_id" which needs to be mapped now.- User.where("id >= ?", @first_new_user_id).find_each do |u|- if u.uploaded_avatar_id- u.uploaded_avatar_id = upload_id_from_imported_id(u.uploaded_avatar_id)- u.save! unless u.uploaded_avatar_id.nil?+ User+ .where("id >= ?", @first_new_user_id)+ .find_each do |u|+ if u.uploaded_avatar_id+ u.uploaded_avatar_id = upload_id_from_imported_id(u.uploaded_avatar_id)+ u.save! unless u.uploaded_avatar_id.nil?+ endend- endenddef copy_everything_else@@ -386,16 +397,16 @@ class BulkImport::DiscourseMerger < BulkImport::Basecopy_model(k, skip_processing: true)end- [UserHistory, UserWarning, GroupArchivedMessage].each do |k|- copy_model(k)- end+ [UserHistory, UserWarning, GroupArchivedMessage].each { |k| copy_model(k) }copy_model(Notification, mapping: @notifications)[CategoryGroup, GroupHistory].each do |k|- col_list = k.columns.map { |c| "\"#{c.name}\"" }.join(', ')- copy_model(k,- select_sql: "SELECT #{col_list} FROM #{k.table_name} WHERE group_id NOT IN (#{@auto_group_ids.join(', ')})"+ col_list = k.columns.map { |c| "\"#{c.name}\"" }.join(", ")+ copy_model(+ k,+ select_sql:+ "SELECT #{col_list} FROM #{k.table_name} WHERE group_id NOT IN (#{@auto_group_ids.join(", ")})",)endend@@ -408,23 +419,26 @@ class BulkImport::DiscourseMerger < BulkImport::Baseimported_ids = []last_id = Badge.unscoped.maximum(:id) || 1- sql = "COPY badges (#{columns.map { |c| "\"#{c}\"" }.join(', ')}) FROM STDIN"+ sql = "COPY badges (#{columns.map { |c| "\"#{c}\"" }.join(", ")}) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- source_raw_connection.exec("SELECT #{columns.map { |c| "\"#{c}\"" }.join(', ')} FROM badges").each do |row|-- if existing = Badge.where(name: row['name']).first- @badges[row['id']] = existing.id- next- end+ source_raw_connection+ .exec("SELECT #{columns.map { |c| "\"#{c}\"" }.join(", ")} FROM badges")+ .each do |row|+ if existing = Badge.where(name: row["name"]).first+ @badges[row["id"]] = existing.id+ next+ end- old_id = row['id']- row['id'] = (last_id += 1)- @badges[old_id.to_s] = row['id']+ old_id = row["id"]+ row["id"] = (last_id += 1)+ @badges[old_id.to_s] = row["id"]- row['badge_grouping_id'] = @badge_groupings[row['badge_grouping_id']] if row['badge_grouping_id']+ row["badge_grouping_id"] = @badge_groupings[row["badge_grouping_id"]] if row[+ "badge_grouping_id"+ ]- @raw_connection.put_copy_data(row.values)- end+ @raw_connection.put_copy_data(row.values)+ endend@sequences[Badge.sequence_name] = last_id + 1@@ -432,72 +446,94 @@ class BulkImport::DiscourseMerger < BulkImport::Basecopy_model(UserBadge, is_a_user_model: true)end- def copy_model(klass, skip_if_merged: false, is_a_user_model: false, skip_processing: false, mapping: nil, select_sql: nil)-+ def copy_model(+ klass,+ skip_if_merged: false,+ is_a_user_model: false,+ skip_processing: false,+ mapping: nil,+ select_sql: nil+ )puts "copying #{klass.table_name}..."columns = klass.columns.map(&:name)has_custom_fields = CUSTOM_FIELDS.include?(klass.name.downcase)imported_ids = []- last_id = columns.include?('id') ? (klass.unscoped.maximum(:id) || 1) : nil+ last_id = columns.include?("id") ? (klass.unscoped.maximum(:id) || 1) : nil- sql = "COPY #{klass.table_name} (#{columns.map { |c| "\"#{c}\"" }.join(', ')}) FROM STDIN"+ sql = "COPY #{klass.table_name} (#{columns.map { |c| "\"#{c}\"" }.join(", ")}) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- source_raw_connection.exec(select_sql || "SELECT #{columns.map { |c| "\"#{c}\"" }.join(', ')} FROM #{klass.table_name}").each do |row|- if row['user_id']- old_user_id = row['user_id'].to_i+ source_raw_connection+ .exec(+ select_sql ||+ "SELECT #{columns.map { |c| "\"#{c}\"" }.join(", ")} FROM #{klass.table_name}",+ )+ .each do |row|+ if row["user_id"]+ old_user_id = row["user_id"].to_i- next if skip_if_merged && @merged_user_ids.include?(old_user_id)+ next if skip_if_merged && @merged_user_ids.include?(old_user_id)- if is_a_user_model- next if old_user_id < 1- next if user_id_from_imported_id(old_user_id).nil?- end+ if is_a_user_model+ next if old_user_id < 1+ next if user_id_from_imported_id(old_user_id).nil?+ end- if old_user_id >= 1- row['user_id'] = user_id_from_imported_id(old_user_id)- if is_a_user_model && row['user_id'].nil?- raise "user_id nil for user id '#{old_user_id}'"+ if old_user_id >= 1+ row["user_id"] = user_id_from_imported_id(old_user_id)+ if is_a_user_model && row["user_id"].nil?+ raise "user_id nil for user id '#{old_user_id}'"+ end+ next if row["user_id"].nil? # associated record for a deleted userend- next if row['user_id'].nil? # associated record for a deleted userend- end-- row['group_id'] = group_id_from_imported_id(row['group_id']) if row['group_id']- row['category_id'] = category_id_from_imported_id(row['category_id']) if row['category_id']- if row['topic_id'] && klass != Category- row['topic_id'] = topic_id_from_imported_id(row['topic_id'])- next if row['topic_id'].nil?- end- if row['post_id']- row['post_id'] = post_id_from_imported_id(row['post_id'])- next if row['post_id'].nil?- end- row['tag_id'] = tag_id_from_imported_id(row['tag_id']) if row['tag_id']- row['tag_group_id'] = tag_group_id_from_imported_id(row['tag_group_id']) if row['tag_group_id']- row['upload_id'] = upload_id_from_imported_id(row['upload_id']) if row['upload_id']- row['deleted_by_id'] = user_id_from_imported_id(row['deleted_by_id']) if row['deleted_by_id']- row['badge_id'] = badge_id_from_imported_id(row['badge_id']) if row['badge_id']-- old_id = row['id'].to_i- if old_id && last_id- row['id'] = (last_id += 1)- imported_ids << old_id if has_custom_fields- mapping[old_id] = row['id'] if mapping- end- if skip_processing- @raw_connection.put_copy_data(row.values)- else- process_method_name = "process_#{klass.name.underscore}"-- processed = respond_to?(process_method_name) ? send(process_method_name, HashWithIndifferentAccess.new(row)) : row+ row["group_id"] = group_id_from_imported_id(row["group_id"]) if row["group_id"]+ row["category_id"] = category_id_from_imported_id(row["category_id"]) if row[+ "category_id"+ ]+ if row["topic_id"] && klass != Category+ row["topic_id"] = topic_id_from_imported_id(row["topic_id"])+ next if row["topic_id"].nil?+ end+ if row["post_id"]+ row["post_id"] = post_id_from_imported_id(row["post_id"])+ next if row["post_id"].nil?+ end+ row["tag_id"] = tag_id_from_imported_id(row["tag_id"]) if row["tag_id"]+ row["tag_group_id"] = tag_group_id_from_imported_id(row["tag_group_id"]) if row[+ "tag_group_id"+ ]+ row["upload_id"] = upload_id_from_imported_id(row["upload_id"]) if row["upload_id"]+ row["deleted_by_id"] = user_id_from_imported_id(row["deleted_by_id"]) if row[+ "deleted_by_id"+ ]+ row["badge_id"] = badge_id_from_imported_id(row["badge_id"]) if row["badge_id"]++ old_id = row["id"].to_i+ if old_id && last_id+ row["id"] = (last_id += 1)+ imported_ids << old_id if has_custom_fields+ mapping[old_id] = row["id"] if mapping+ end- if processed- @raw_connection.put_copy_data columns.map { |c| processed[c] }+ if skip_processing+ @raw_connection.put_copy_data(row.values)+ else+ process_method_name = "process_#{klass.name.underscore}"++ processed =+ (+ if respond_to?(process_method_name)+ send(process_method_name, HashWithIndifferentAccess.new(row))+ else+ row+ end+ )++ @raw_connection.put_copy_data columns.map { |c| processed[c] } if processedendend- endend@sequences[klass.sequence_name] = last_id + 1 if last_id@@ -506,192 +542,248 @@ class BulkImport::DiscourseMerger < BulkImport::Baseid_mapping_method_name = "#{klass.name.downcase}_id_from_imported_id".freezereturn unless respond_to?(id_mapping_method_name)create_custom_fields(klass.name.downcase, "id", imported_ids) do |imported_id|- {- record_id: send(id_mapping_method_name, imported_id),- value: imported_id,- }+ { record_id: send(id_mapping_method_name, imported_id), value: imported_id }endendenddef process_topic(topic)- return nil if topic['category_id'].nil? && topic['archetype'] != Archetype.private_message- topic['last_post_user_id'] = user_id_from_imported_id(topic['last_post_user_id']) || -1- topic['featured_user1_id'] = user_id_from_imported_id(topic['featured_user1_id']) || -1- topic['featured_user2_id'] = user_id_from_imported_id(topic['featured_user2_id']) || -1- topic['featured_user3_id'] = user_id_from_imported_id(topic['featured_user3_id']) || -1- topic['featured_user4_id'] = user_id_from_imported_id(topic['featured_user4_id']) || -1+ return nil if topic["category_id"].nil? && topic["archetype"] != Archetype.private_message+ topic["last_post_user_id"] = user_id_from_imported_id(topic["last_post_user_id"]) || -1+ topic["featured_user1_id"] = user_id_from_imported_id(topic["featured_user1_id"]) || -1+ topic["featured_user2_id"] = user_id_from_imported_id(topic["featured_user2_id"]) || -1+ topic["featured_user3_id"] = user_id_from_imported_id(topic["featured_user3_id"]) || -1+ topic["featured_user4_id"] = user_id_from_imported_id(topic["featured_user4_id"]) || -1topicenddef process_post(post)- post['last_editor_id'] = user_id_from_imported_id(post['last_editor_id']) || -1- post['reply_to_user_id'] = user_id_from_imported_id(post['reply_to_user_id']) || -1- post['locked_by_id'] = user_id_from_imported_id(post['locked_by_id']) || -1+ post["last_editor_id"] = user_id_from_imported_id(post["last_editor_id"]) || -1+ post["reply_to_user_id"] = user_id_from_imported_id(post["reply_to_user_id"]) || -1+ post["locked_by_id"] = user_id_from_imported_id(post["locked_by_id"]) || -1@topic_id_by_post_id[post[:id]] = post[:topic_id]postenddef process_post_reply(post_reply)- post_reply['reply_post_id'] = post_id_from_imported_id(post_reply['reply_post_id']) if post_reply['reply_post_id']+ post_reply["reply_post_id"] = post_id_from_imported_id(+ post_reply["reply_post_id"],+ ) if post_reply["reply_post_id"]post_replyenddef process_quoted_post(quoted_post)- quoted_post['quoted_post_id'] = post_id_from_imported_id(quoted_post['quoted_post_id']) if quoted_post['quoted_post_id']- return nil if quoted_post['quoted_post_id'].nil?+ quoted_post["quoted_post_id"] = post_id_from_imported_id(+ quoted_post["quoted_post_id"],+ ) if quoted_post["quoted_post_id"]+ return nil if quoted_post["quoted_post_id"].nil?quoted_postenddef process_topic_link(topic_link)- old_topic_id = topic_link['link_topic_id']- topic_link['link_topic_id'] = topic_id_from_imported_id(topic_link['link_topic_id']) if topic_link['link_topic_id']- topic_link['link_post_id'] = post_id_from_imported_id(topic_link['link_post_id']) if topic_link['link_post_id']- return nil if topic_link['link_topic_id'].nil?+ old_topic_id = topic_link["link_topic_id"]+ topic_link["link_topic_id"] = topic_id_from_imported_id(+ topic_link["link_topic_id"],+ ) if topic_link["link_topic_id"]+ topic_link["link_post_id"] = post_id_from_imported_id(topic_link["link_post_id"]) if topic_link[+ "link_post_id"+ ]+ return nil if topic_link["link_topic_id"].nil?r = Regexp.new("^#{@source_base_url}/t/([^\/]+)/#{old_topic_id}(.*)")- if m = r.match(topic_link['url'])- topic_link['url'] = "#{@source_base_url}/t/#{m[1]}/#{topic_link['link_topic_id']}#{m[2]}"+ if m = r.match(topic_link["url"])+ topic_link["url"] = "#{@source_base_url}/t/#{m[1]}/#{topic_link["link_topic_id"]}#{m[2]}"endtopic_linkenddef process_post_action(post_action)- return nil unless post_action['post_id'].present?- post_action['related_post_id'] = post_id_from_imported_id(post_action['related_post_id'])- post_action['deferred_by_id'] = user_id_from_imported_id(post_action['deferred_by_id'])- post_action['agreed_by_id'] = user_id_from_imported_id(post_action['agreed_by_id'])- post_action['disagreed_by_id'] = user_id_from_imported_id(post_action['disagreed_by_id'])+ return nil unless post_action["post_id"].present?+ post_action["related_post_id"] = post_id_from_imported_id(post_action["related_post_id"])+ post_action["deferred_by_id"] = user_id_from_imported_id(post_action["deferred_by_id"])+ post_action["agreed_by_id"] = user_id_from_imported_id(post_action["agreed_by_id"])+ post_action["disagreed_by_id"] = user_id_from_imported_id(post_action["disagreed_by_id"])post_actionenddef process_user_action(user_action)- user_action['target_topic_id'] = topic_id_from_imported_id(user_action['target_topic_id']) if user_action['target_topic_id']- user_action['target_post_id'] = post_id_from_imported_id(user_action['target_post_id']) if user_action['target_post_id']- user_action['target_user_id'] = user_id_from_imported_id(user_action['target_user_id']) if user_action['target_user_id']- user_action['acting_user_id'] = user_id_from_imported_id(user_action['acting_user_id']) if user_action['acting_user_id']- user_action['queued_post_id'] = post_id_from_imported_id(user_action['queued_post_id']) if user_action['queued_post_id']+ user_action["target_topic_id"] = topic_id_from_imported_id(+ user_action["target_topic_id"],+ ) if user_action["target_topic_id"]+ user_action["target_post_id"] = post_id_from_imported_id(+ user_action["target_post_id"],+ ) if user_action["target_post_id"]+ user_action["target_user_id"] = user_id_from_imported_id(+ user_action["target_user_id"],+ ) if user_action["target_user_id"]+ user_action["acting_user_id"] = user_id_from_imported_id(+ user_action["acting_user_id"],+ ) if user_action["acting_user_id"]+ user_action["queued_post_id"] = post_id_from_imported_id(+ user_action["queued_post_id"],+ ) if user_action["queued_post_id"]user_actionenddef process_tag_group(tag_group)- tag_group['parent_tag_id'] = tag_id_from_imported_id(tag_group['parent_tag_id']) if tag_group['parent_tag_id']+ tag_group["parent_tag_id"] = tag_id_from_imported_id(tag_group["parent_tag_id"]) if tag_group[+ "parent_tag_id"+ ]tag_groupenddef process_category_group(category_group)- return nil if category_group['category_id'].nil? || category_group['group_id'].nil?+ return nil if category_group["category_id"].nil? || category_group["group_id"].nil?category_groupenddef process_group_user(group_user)- if @auto_group_ids.include?(group_user['group_id'].to_i) &&- @merged_user_ids.include?(group_user['user_id'].to_i)+ if @auto_group_ids.include?(group_user["group_id"].to_i) &&+ @merged_user_ids.include?(group_user["user_id"].to_i)return nilend- return nil if group_user['user_id'].to_i < 1+ return nil if group_user["user_id"].to_i < 1group_userenddef process_group_history(group_history)- group_history['acting_user_id'] = user_id_from_imported_id(group_history['acting_user_id']) if group_history['acting_user_id']- group_history['target_user_id'] = user_id_from_imported_id(group_history['target_user_id']) if group_history['target_user_id']+ group_history["acting_user_id"] = user_id_from_imported_id(+ group_history["acting_user_id"],+ ) if group_history["acting_user_id"]+ group_history["target_user_id"] = user_id_from_imported_id(+ group_history["target_user_id"],+ ) if group_history["target_user_id"]group_historyenddef process_group_archived_message(gam)- return nil unless gam['topic_id'].present? && gam['group_id'].present?+ return nil unless gam["topic_id"].present? && gam["group_id"].present?gamenddef process_topic_link(topic_link)- topic_link['link_topic_id'] = topic_id_from_imported_id(topic_link['link_topic_id']) if topic_link['link_topic_id']- topic_link['link_post_id'] = post_id_from_imported_id(topic_link['link_post_id']) if topic_link['link_post_id']+ topic_link["link_topic_id"] = topic_id_from_imported_id(+ topic_link["link_topic_id"],+ ) if topic_link["link_topic_id"]+ topic_link["link_post_id"] = post_id_from_imported_id(topic_link["link_post_id"]) if topic_link[+ "link_post_id"+ ]topic_linkenddef process_user_avatar(user_avatar)- user_avatar['custom_upload_id'] = upload_id_from_imported_id(user_avatar['custom_upload_id']) if user_avatar['custom_upload_id']- user_avatar['gravatar_upload_id'] = upload_id_from_imported_id(user_avatar['gravatar_upload_id']) if user_avatar['gravatar_upload_id']- return nil unless user_avatar['custom_upload_id'].present? || user_avatar['gravatar_upload_id'].present?+ user_avatar["custom_upload_id"] = upload_id_from_imported_id(+ user_avatar["custom_upload_id"],+ ) if user_avatar["custom_upload_id"]+ user_avatar["gravatar_upload_id"] = upload_id_from_imported_id(+ user_avatar["gravatar_upload_id"],+ ) if user_avatar["gravatar_upload_id"]+ unless user_avatar["custom_upload_id"].present? || user_avatar["gravatar_upload_id"].present?+ return nil+ enduser_avatarenddef process_user_history(user_history)- user_history['acting_user_id'] = user_id_from_imported_id(user_history['acting_user_id']) if user_history['acting_user_id']- user_history['target_user_id'] = user_id_from_imported_id(user_history['target_user_id']) if user_history['target_user_id']+ user_history["acting_user_id"] = user_id_from_imported_id(+ user_history["acting_user_id"],+ ) if user_history["acting_user_id"]+ user_history["target_user_id"] = user_id_from_imported_id(+ user_history["target_user_id"],+ ) if user_history["target_user_id"]user_historyenddef process_user_warning(user_warning)- user_warning['created_by_id'] = user_id_from_imported_id(user_warning['created_by_id']) if user_warning['created_by_id']+ user_warning["created_by_id"] = user_id_from_imported_id(+ user_warning["created_by_id"],+ ) if user_warning["created_by_id"]user_warningenddef process_post_upload(post_upload)- return nil unless post_upload['upload_id'].present?+ return nil unless post_upload["upload_id"].present?@imported_post_uploads ||= {}- return nil if @imported_post_uploads[post_upload['post_id']]&.include?(post_upload['upload_id'])- @imported_post_uploads[post_upload['post_id']] ||= []- @imported_post_uploads[post_upload['post_id']] << post_upload['upload_id']-- return nil if PostUpload.where(post_id: post_upload['post_id'], upload_id: post_upload['upload_id']).exists?+ return nil if @imported_post_uploads[post_upload["post_id"]]&.include?(post_upload["upload_id"])+ @imported_post_uploads[post_upload["post_id"]] ||= []+ @imported_post_uploads[post_upload["post_id"]] << post_upload["upload_id"]++ if PostUpload.where(+ post_id: post_upload["post_id"],+ upload_id: post_upload["upload_id"],+ ).exists?+ return nil+ endpost_uploadenddef process_notification(notification)- notification['post_action_id'] = post_action_id_from_imported_id(notification['post_action_id']) if notification['post_action_id']+ notification["post_action_id"] = post_action_id_from_imported_id(+ notification["post_action_id"],+ ) if notification["post_action_id"]notificationenddef process_oauth2_user_info(r)- return nil if Oauth2UserInfo.where(uid: r['uid'], provider: r['provider']).exists?+ return nil if Oauth2UserInfo.where(uid: r["uid"], provider: r["provider"]).exists?renddef process_user_associated_account(r)- return nil if UserAssociatedAccount.where(provider_uid: r['uid'], provider_name: r['provider']).exists?+ if UserAssociatedAccount.where(provider_uid: r["uid"], provider_name: r["provider"]).exists?+ return nil+ endrenddef process_single_sign_on_record(r)- return nil if SingleSignOnRecord.where(external_id: r['external_id']).exists?+ return nil if SingleSignOnRecord.where(external_id: r["external_id"]).exists?renddef process_user_badge(user_badge)- user_badge['granted_by_id'] = user_id_from_imported_id(user_badge['granted_by_id']) if user_badge['granted_by_id']- user_badge['notification_id'] = notification_id_from_imported_id(user_badge['notification_id']) if user_badge['notification_id']- return nil if UserBadge.where(user_id: user_badge['user_id'], badge_id: user_badge['badge_id']).exists?+ user_badge["granted_by_id"] = user_id_from_imported_id(+ user_badge["granted_by_id"],+ ) if user_badge["granted_by_id"]+ user_badge["notification_id"] = notification_id_from_imported_id(+ user_badge["notification_id"],+ ) if user_badge["notification_id"]+ if UserBadge.where(user_id: user_badge["user_id"], badge_id: user_badge["badge_id"]).exists?+ return nil+ enduser_badgeenddef process_email_change_request(ecr)- ecr['old_email_token_id'] = email_token_id_from_imported_id(ecr['old_email_token_id']) if ecr['old_email_token_id']- ecr['new_email_token_id'] = email_token_id_from_imported_id(ecr['new_email_token_id']) if ecr['new_email_token_id']+ ecr["old_email_token_id"] = email_token_id_from_imported_id(ecr["old_email_token_id"]) if ecr[+ "old_email_token_id"+ ]+ ecr["new_email_token_id"] = email_token_id_from_imported_id(ecr["new_email_token_id"]) if ecr[+ "new_email_token_id"+ ]ecrenddef process_tag_user(x)- return nil if TagUser.where(tag_id: x['tag_id'], user_id: x['user_id']).exists?+ return nil if TagUser.where(tag_id: x["tag_id"], user_id: x["user_id"]).exists?xenddef process_topic_tag(x)- return nil if TopicTag.where(topic_id: x['topic_id'], tag_id: x['tag_id']).exists?+ return nil if TopicTag.where(topic_id: x["topic_id"], tag_id: x["tag_id"]).exists?xenddef process_category_tag(x)- return nil if CategoryTag.where(category_id: x['category_id'], tag_id: x['tag_id']).exists?+ return nil if CategoryTag.where(category_id: x["category_id"], tag_id: x["tag_id"]).exists?xenddef process_category_tag_stat(x)- return nil if CategoryTagStat.where(category_id: x['category_id'], tag_id: x['tag_id']).exists?+ return nil if CategoryTagStat.where(category_id: x["category_id"], tag_id: x["tag_id"]).exists?xend@@ -744,27 +836,29 @@ class BulkImport::DiscourseMerger < BulkImport::Basedef fix_user_columnsputs "updating foreign keys in the users table..."- User.where('id >= ?', @first_new_user_id).find_each do |u|- arr = []- sql = "UPDATE users SET".dup+ User+ .where("id >= ?", @first_new_user_id)+ .find_each do |u|+ arr = []+ sql = "UPDATE users SET".dup- if new_approved_by_id = user_id_from_imported_id(u.approved_by_id)- arr << " approved_by_id = #{new_approved_by_id}"- end- if new_primary_group_id = group_id_from_imported_id(u.primary_group_id)- arr << " primary_group_id = #{new_primary_group_id}"- end- if new_notification_id = notification_id_from_imported_id(u.seen_notification_id)- arr << " seen_notification_id = #{new_notification_id}"- end+ if new_approved_by_id = user_id_from_imported_id(u.approved_by_id)+ arr << " approved_by_id = #{new_approved_by_id}"+ end+ if new_primary_group_id = group_id_from_imported_id(u.primary_group_id)+ arr << " primary_group_id = #{new_primary_group_id}"+ end+ if new_notification_id = notification_id_from_imported_id(u.seen_notification_id)+ arr << " seen_notification_id = #{new_notification_id}"+ end- next if arr.empty?+ next if arr.empty?- sql << arr.join(', ')- sql << " WHERE id = #{u.id}"+ sql << arr.join(", ")+ sql << " WHERE id = #{u.id}"- @raw_connection.exec(sql)- end+ @raw_connection.exec(sql)+ endenddef fix_topic_links@@ -777,33 +871,37 @@ class BulkImport::DiscourseMerger < BulkImport::Base@topics.each do |old_topic_id, new_topic_id|current += 1percent = (current * 100) / total- puts "#{current} (#{percent}\%) completed. #{update_count} rows updated." if current % 200 == 0+ if current % 200 == 0+ puts "#{current} (#{percent}\%) completed. #{update_count} rows updated."+ endif topic = Topic.find_by_id(new_topic_id)replace_arg = ["#{@source_base_url}/t/#{topic.slug}/#{old_topic_id}",- "#{@source_base_url}/t/#{topic.slug}/#{new_topic_id}"+ "#{@source_base_url}/t/#{topic.slug}/#{new_topic_id}",]- r = @raw_connection.async_exec(- "UPDATE posts+ r =+ @raw_connection.async_exec(+ "UPDATE postsSET raw = replace(raw, $1, $2)WHERE NOT raw IS NULLAND topic_id >= #{@first_new_topic_id}AND raw <> replace(raw, $1, $2)",- replace_arg- )+ replace_arg,+ )update_count += r.cmd_tuples- r = @raw_connection.async_exec(- "UPDATE posts+ r =+ @raw_connection.async_exec(+ "UPDATE postsSET cooked = replace(cooked, $1, $2)WHERE NOT cooked IS NULLAND topic_id >= #{@first_new_topic_id}AND cooked <> replace(cooked, $1, $2)",- replace_arg- )+ replace_arg,+ )update_count += r.cmd_tuplesend@@ -811,7 +909,6 @@ class BulkImport::DiscourseMerger < BulkImport::Baseputs "updated #{update_count} rows"end-endBulkImport::DiscourseMerger.new.startdiff --git a/script/bulk_import/phpbb_postgresql.rb b/script/bulk_import/phpbb_postgresql.rbindex cd5fa626fd5..70def55fb83 100644--- a/script/bulk_import/phpbb_postgresql.rb+++ b/script/bulk_import/phpbb_postgresql.rb@@ -3,17 +3,16 @@require_relative "base"require "pg"require "htmlentities"-require 'ruby-bbcode-to-md'+require "ruby-bbcode-to-md"class BulkImport::PhpBB < BulkImport::Base-SUSPENDED_TILL ||= Date.new(3000, 1, 1)- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "phpbb_"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "phpbb_"def initializesuper- charset = ENV["DB_CHARSET"] || "utf8"+ charset = ENV["DB_CHARSET"] || "utf8"database = ENV["DB_NAME"] || "flightaware"password = ENV["DB_PASSWORD"] || "discourse"@@ -57,7 +56,7 @@ class BulkImport::PhpBB < BulkImport::Base{imported_id: row["group_id"],name: normalize_text(row["group_name"]),- bio_raw: normalize_text(row["group_desc"])+ bio_raw: normalize_text(row["group_desc"]),}endend@@ -85,15 +84,28 @@ class BulkImport::PhpBB < BulkImport::Baseusername: normalize_text(row["username"]),email: row["user_email"],created_at: Time.zone.at(row["user_regdate"].to_i),- last_seen_at: row["user_lastvisit"] == 0 ? Time.zone.at(row["user_regdate"].to_i) : Time.zone.at(row["user_lastvisit"].to_i),+ last_seen_at:+ (+ if row["user_lastvisit"] == 0+ Time.zone.at(row["user_regdate"].to_i)+ else+ Time.zone.at(row["user_lastvisit"].to_i)+ end+ ),trust_level: row["user_posts"] == 0 ? TrustLevel[0] : TrustLevel[1],date_of_birth: parse_birthday(row["user_birthday"]),- primary_group_id: group_id_from_imported_id(row["group_id"])+ primary_group_id: group_id_from_imported_id(row["group_id"]),}u[:ip_address] = row["user_ip"][/\b(?:\d{1,3}\.){3}\d{1,3}\b/] if row["user_ip"].present?if row["ban_start"]u[:suspended_at] = Time.zone.at(row["ban_start"].to_i)- u[:suspended_till] = row["ban_end"].to_i > 0 ? Time.zone.at(row["ban_end"].to_i) : SUSPENDED_TILL+ u[:suspended_till] = (+ if row["ban_end"].to_i > 0+ Time.zone.at(row["ban_end"].to_i)+ else+ SUSPENDED_TILL+ end+ )enduend@@ -114,7 +126,7 @@ class BulkImport::PhpBB < BulkImport::Baseimported_id: row["user_id"],imported_user_id: row["user_id"],email: row["user_email"],- created_at: Time.zone.at(row["user_regdate"].to_i)+ created_at: Time.zone.at(row["user_regdate"].to_i),}endend@@ -149,7 +161,14 @@ class BulkImport::PhpBB < BulkImport::Basecreate_user_profiles(user_profiles) do |row|{user_id: user_id_from_imported_id(row["user_id"]),- website: (URI.parse(row["user_website"]).to_s rescue nil),+ website:+ (+ begin+ URI.parse(row["user_website"]).to_s+ rescue StandardError+ nil+ end+ ),location: row["user_from"],}end@@ -158,17 +177,16 @@ class BulkImport::PhpBB < BulkImport::Basedef import_categoriesputs "Importing categories..."- categories = psql_query(<<-SQL+ categories = psql_query(<<-SQL).to_aSELECT forum_id, parent_id, forum_name, forum_descFROM #{TABLE_PREFIX}forumsWHERE forum_id > #{@last_imported_category_id}ORDER BY parent_id, left_idSQL- ).to_areturn if categories.empty?- parent_categories = categories.select { |c| c["parent_id"].to_i == 0 }+ parent_categories = categories.select { |c| c["parent_id"].to_i == 0 }children_categories = categories.select { |c| c["parent_id"].to_i != 0 }puts "Importing parent categories..."@@ -176,7 +194,7 @@ class BulkImport::PhpBB < BulkImport::Base{imported_id: row["forum_id"],name: normalize_text(row["forum_name"]),- description: normalize_text(row["forum_desc"])+ description: normalize_text(row["forum_desc"]),}end@@ -186,7 +204,7 @@ class BulkImport::PhpBB < BulkImport::Baseimported_id: row["forum_id"],name: normalize_text(row["forum_name"]),description: normalize_text(row["forum_desc"]),- parent_category_id: category_id_from_imported_id(row["parent_id"])+ parent_category_id: category_id_from_imported_id(row["parent_id"]),}endend@@ -209,7 +227,7 @@ class BulkImport::PhpBB < BulkImport::Basecategory_id: category_id_from_imported_id(row["forum_id"]),user_id: user_id_from_imported_id(row["topic_poster"]),created_at: Time.zone.at(row["topic_time"].to_i),- views: row["topic_views"]+ views: row["topic_views"],}endend@@ -261,7 +279,7 @@ class BulkImport::PhpBB < BulkImport::Baseimported_id: row["msg_id"].to_i + PRIVATE_OFFSET,title: normalize_text(title),user_id: user_id_from_imported_id(row["author_id"].to_i),- created_at: Time.zone.at(row["message_time"].to_i)+ created_at: Time.zone.at(row["message_time"].to_i),}endend@@ -271,13 +289,12 @@ class BulkImport::PhpBB < BulkImport::Baseallowed_users = []- psql_query(<<-SQL+ psql_query(<<-SQL).each do |row|SELECT msg_id, author_id, to_addressFROM #{TABLE_PREFIX}privmsgsWHERE msg_id > (#{@last_imported_private_topic_id - PRIVATE_OFFSET})ORDER BY msg_idSQL- ).each do |row|next unless topic_id = topic_id_from_imported_id(row["msg_id"].to_i + PRIVATE_OFFSET)user_ids = get_message_recipients(row["author_id"], row["to_address"])@@ -287,12 +304,7 @@ class BulkImport::PhpBB < BulkImport::Baseendend- create_topic_allowed_users(allowed_users) do |row|- {- topic_id: row[0],- user_id: row[1]- }- end+ create_topic_allowed_users(allowed_users) { |row| { topic_id: row[0], user_id: row[1] } }enddef import_private_posts@@ -316,13 +328,13 @@ class BulkImport::PhpBB < BulkImport::Basetopic_id: topic_id,user_id: user_id_from_imported_id(row["author_id"].to_i),created_at: Time.zone.at(row["message_time"].to_i),- raw: process_raw_text(row["message_text"])+ raw: process_raw_text(row["message_text"]),}endenddef get_message_recipients(from, to)- user_ids = to.split(':')+ user_ids = to.split(":")user_ids.map! { |u| u[2..-1].to_i }user_ids.push(from.to_i)user_ids.uniq!@@ -332,15 +344,29 @@ class BulkImport::PhpBB < BulkImport::Basedef extract_pm_title(title)pm_title = CGI.unescapeHTML(title)- pm_title = title.gsub(/^Re\s*:\s*/i, "") rescue nil+ pm_title =+ begin+ title.gsub(/^Re\s*:\s*/i, "")+ rescue StandardError+ nil+ endpm_titleenddef parse_birthday(birthday)return if birthday.blank?- date_of_birth = Date.strptime(birthday.gsub(/[^\d-]+/, ""), "%m-%d-%Y") rescue nil+ date_of_birth =+ begin+ Date.strptime(birthday.gsub(/[^\d-]+/, ""), "%m-%d-%Y")+ rescue StandardError+ nil+ endreturn if date_of_birth.nil?- date_of_birth.year < 1904 ? Date.new(1904, date_of_birth.month, date_of_birth.day) : date_of_birth+ if date_of_birth.year < 1904+ Date.new(1904, date_of_birth.month, date_of_birth.day)+ else+ date_of_birth+ endenddef psql_query(sql)@@ -352,34 +378,36 @@ class BulkImport::PhpBB < BulkImport::Basetext = raw.duptext = CGI.unescapeHTML(text)- text.gsub!(/:(?:\w{8})\]/, ']')+ text.gsub!(/:(?:\w{8})\]/, "]")# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- text.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/i, '[\2](\1)')+ text.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}i, '[\2](\1)')# phpBB shortens link text like this, which breaks our markdown processing:# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- text.gsub!(/\[http(s)?:\/\/(www\.)?/i, '[')+ text.gsub!(%r{\[http(s)?://(www\.)?}i, "[")# convert list tags to ul and list=1 tags to ol# list=a is not supported, so handle it like list=1# list=9 and list=x have the same result as list=1 and list=a- text.gsub!(/\[list\](.*?)\[\/list:u\]/mi, '[ul]\1[/ul]')- text.gsub!(/\[list=.*?\](.*?)\[\/list:o\]/mi, '[ol]\1[/ol]')+ text.gsub!(%r{\[list\](.*?)\[/list:u\]}mi, '[ul]\1[/ul]')+ text.gsub!(%r{\[list=.*?\](.*?)\[/list:o\]}mi, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:- text.gsub!(/\[\*\](.*?)\[\/\*:m\]/mi, '[li]\1[/li]')+ text.gsub!(%r{\[\*\](.*?)\[/\*:m\]}mi, '[li]\1[/li]')# [QUOTE="<username>"] -- add newlinetext.gsub!(/(\[quote="[a-zA-Z\d]+"\])/i) { "#{$1}\n" }# [/QUOTE] -- add newline- text.gsub!(/(\[\/quote\])/i) { "\n#{$1}" }+ text.gsub!(%r{(\[/quote\])}i) { "\n#{$1}" }# :) is encoded as <!-- s:) --><img src="{SMILIES_PATH}/icon_e_smile.gif" alt=":)" title="Smile" /><!-- s:) -->- text.gsub!(/<!-- s(\S+) --><img src="\{SMILIES_PATH\}\/(.+?)" alt="(.*?)" title="(.*?)" \/><!-- s(?:\S+) -->/) do+ text.gsub!(+ /<!-- s(\S+) --><img src="\{SMILIES_PATH\}\/(.+?)" alt="(.*?)" title="(.*?)" \/><!-- s(?:\S+) -->/,+ ) dosmiley = $1@smiley_map.fetch(smiley) do# upload_smiley(smiley, $2, $3, $4) || smiley_as_text(smiley)@@ -405,33 +433,30 @@ class BulkImport::PhpBB < BulkImport::Basedef add_default_smilies{- [':D', ':-D', ':grin:'] => ':smiley:',- [':)', ':-)', ':smile:'] => ':slight_smile:',- [';)', ';-)', ':wink:'] => ':wink:',- [':(', ':-(', ':sad:'] => ':frowning:',- [':o', ':-o', ':eek:'] => ':astonished:',- [':shock:'] => ':open_mouth:',- [':?', ':-?', ':???:'] => ':confused:',- ['8-)', ':cool:'] => ':sunglasses:',- [':lol:'] => ':laughing:',- [':x', ':-x', ':mad:'] => ':angry:',- [':P', ':-P', ':razz:'] => ':stuck_out_tongue:',- [':oops:'] => ':blush:',- [':cry:'] => ':cry:',- [':evil:'] => ':imp:',- [':twisted:'] => ':smiling_imp:',- [':roll:'] => ':unamused:',- [':!:'] => ':exclamation:',- [':?:'] => ':question:',- [':idea:'] => ':bulb:',- [':arrow:'] => ':arrow_right:',- [':|', ':-|'] => ':neutral_face:',- [':geek:'] => ':nerd:'- }.each do |smilies, emoji|- smilies.each { |smiley| @smiley_map[smiley] = emoji }- end+ %w[:D :-D :grin:] => ":smiley:",+ %w[:) :-) :smile:] => ":slight_smile:",+ %w[;) ;-) :wink:] => ":wink:",+ %w[:( :-( :sad:] => ":frowning:",+ %w[:o :-o :eek:] => ":astonished:",+ [":shock:"] => ":open_mouth:",+ %w[:? :-? :???:] => ":confused:",+ %w[8-) :cool:] => ":sunglasses:",+ [":lol:"] => ":laughing:",+ %w[:x :-x :mad:] => ":angry:",+ %w[:P :-P :razz:] => ":stuck_out_tongue:",+ [":oops:"] => ":blush:",+ [":cry:"] => ":cry:",+ [":evil:"] => ":imp:",+ [":twisted:"] => ":smiling_imp:",+ [":roll:"] => ":unamused:",+ [":!:"] => ":exclamation:",+ [":?:"] => ":question:",+ [":idea:"] => ":bulb:",+ [":arrow:"] => ":arrow_right:",+ %w[:| :-|] => ":neutral_face:",+ [":geek:"] => ":nerd:",+ }.each { |smilies, emoji| smilies.each { |smiley| @smiley_map[smiley] = emoji } }end-endBulkImport::PhpBB.new.rundiff --git a/script/bulk_import/vanilla.rb b/script/bulk_import/vanilla.rbindex d01eed3af03..827f57c3fd9 100644--- a/script/bulk_import/vanilla.rb+++ b/script/bulk_import/vanilla.rb@@ -8,7 +8,6 @@ require "htmlentities"# NOTE: this importer expects a MySQL DB to directly connect toclass BulkImport::Vanilla < BulkImport::Base-VANILLA_DB = "dbname"TABLE_PREFIX = "GDN_"ATTACHMENTS_BASE_DIR = "/my/absolute/path/to/from_vanilla/uploads"@@ -20,13 +19,14 @@ class BulkImport::Vanilla < BulkImport::Basedef initializesuper@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- database: VANILLA_DB,- password: "",- reconnect: true- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ database: VANILLA_DB,+ password: "",+ reconnect: true,+ )@import_tags = falsebegin@@ -88,10 +88,10 @@ class BulkImport::Vanilla < BulkImport::Baseenddef import_users- puts '', "Importing users..."+ puts "", "Importing users..."username = nil- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}User;").first['count']+ total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}User;").first["count"]users = mysql_stream <<-SQLSELECT UserID, Name, Title, Location, Email,@@ -103,26 +103,32 @@ class BulkImport::Vanilla < BulkImport::BaseSQLcreate_users(users) do |row|- next if row['Email'].blank?- next if row['Name'].blank?+ next if row["Email"].blank?+ next if row["Name"].blank?- if ip_address = row['InsertIPAddress']&.split(',').try(:[], 0)- ip_address = nil unless (IPAddr.new(ip_address) rescue false)+ if ip_address = row["InsertIPAddress"]&.split(",").try(:[], 0)+ ip_address = nil unless (+ begin+ IPAddr.new(ip_address)+ rescue StandardError+ false+ end+ )endu = {- imported_id: row['UserID'],- email: row['Email'],- username: row['Name'],- name: row['Name'],- created_at: row['DateInserted'] == nil ? 0 : Time.zone.at(row['DateInserted']),+ imported_id: row["UserID"],+ email: row["Email"],+ username: row["Name"],+ name: row["Name"],+ created_at: row["DateInserted"] == nil ? 0 : Time.zone.at(row["DateInserted"]),registration_ip_address: ip_address,- last_seen_at: row['DateLastActive'] == nil ? 0 : Time.zone.at(row['DateLastActive']),- location: row['Location'],- admin: row['Admin'] > 0+ last_seen_at: row["DateLastActive"] == nil ? 0 : Time.zone.at(row["DateLastActive"]),+ location: row["Location"],+ admin: row["Admin"] > 0,}if row["Banned"] > 0- u[:suspended_at] = Time.zone.at(row['DateInserted'])+ u[:suspended_at] = Time.zone.at(row["DateInserted"])u[:suspended_till] = SUSPENDED_TILLendu@@ -130,7 +136,7 @@ class BulkImport::Vanilla < BulkImport::Baseenddef import_user_emails- puts '', 'Importing user emails...'+ puts "", "Importing user emails..."users = mysql_stream <<-SQLSELECT UserID, Name, Email, DateInserted@@ -141,20 +147,20 @@ class BulkImport::Vanilla < BulkImport::BaseSQLcreate_user_emails(users) do |row|- next if row['Email'].blank?- next if row['Name'].blank?+ next if row["Email"].blank?+ next if row["Name"].blank?{imported_id: row["UserID"],imported_user_id: row["UserID"],email: row["Email"],- created_at: Time.zone.at(row["DateInserted"])+ created_at: Time.zone.at(row["DateInserted"]),}endenddef import_user_profiles- puts '', 'Importing user profiles...'+ puts "", "Importing user profiles..."user_profiles = mysql_stream <<-SQLSELECT UserID, Name, Email, Location, About@@ -165,19 +171,19 @@ class BulkImport::Vanilla < BulkImport::BaseSQLcreate_user_profiles(user_profiles) do |row|- next if row['Email'].blank?- next if row['Name'].blank?+ next if row["Email"].blank?+ next if row["Name"].blank?{user_id: user_id_from_imported_id(row["UserID"]),location: row["Location"],- bio_raw: row["About"]+ bio_raw: row["About"],}endenddef import_user_stats- puts '', "Importing user stats..."+ puts "", "Importing user stats..."users = mysql_stream <<-SQLSELECT UserID, CountDiscussions, CountComments, DateInserted@@ -190,14 +196,14 @@ class BulkImport::Vanilla < BulkImport::Basenow = Time.zone.nowcreate_user_stats(users) do |row|- next unless @users[row['UserID'].to_i] # shouldn't need this but it can be NULL :<+ next unless @users[row["UserID"].to_i] # shouldn't need this but it can be NULL :<{- imported_id: row['UserID'],- imported_user_id: row['UserID'],- new_since: Time.zone.at(row['DateInserted'] || now),- post_count: row['CountComments'] || 0,- topic_count: row['CountDiscussions'] || 0+ imported_id: row["UserID"],+ imported_user_id: row["UserID"],+ new_since: Time.zone.at(row["DateInserted"] || now),+ post_count: row["CountComments"] || 0,+ topic_count: row["CountDiscussions"] || 0,}endend@@ -215,7 +221,10 @@ class BulkImport::Vanilla < BulkImport::Basenext unless u.custom_fields["import_id"]- r = mysql_query("SELECT photo FROM #{TABLE_PREFIX}User WHERE UserID = #{u.custom_fields['import_id']};").first+ r =+ mysql_query(+ "SELECT photo FROM #{TABLE_PREFIX}User WHERE UserID = #{u.custom_fields["import_id"]};",+ ).firstnext if r.nil?photo = r["photo"]next unless photo.present?@@ -229,9 +238,9 @@ class BulkImport::Vanilla < BulkImport::Basephoto_real_filename = nilparts = photo.squeeze("/").split("/")if parts[0] =~ /^[a-z0-9]{2}:/- photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[2..-2].join('/')}".squeeze("/")+ photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[2..-2].join("/")}".squeeze("/")elsif parts[0] == "~cf"- photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[1..-2].join('/')}".squeeze("/")+ photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[1..-2].join("/")}".squeeze("/")elseputs "UNKNOWN FORMAT: #{photo}"next@@ -272,75 +281,86 @@ class BulkImport::Vanilla < BulkImport::Basecount = 0# https://us.v-cdn.net/1234567/uploads/editor/xyz/image.jpg- cdn_regex = /https:\/\/us.v-cdn.net\/1234567\/uploads\/(\S+\/(\w|-)+.\w+)/i+ cdn_regex = %r{https://us.v-cdn.net/1234567/uploads/(\S+/(\w|-)+.\w+)}i# [attachment=10109:Screen Shot 2012-04-01 at 3.47.35 AM.png]attachment_regex = /\[attachment=(\d+):(.*?)\]/i- Post.where("raw LIKE '%/us.v-cdn.net/%' OR raw LIKE '%[attachment%'").find_each do |post|- count += 1- print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)]- new_raw = post.raw.dup-- new_raw.gsub!(attachment_regex) do |s|- matches = attachment_regex.match(s)- attachment_id = matches[1]- file_name = matches[2]- next unless attachment_id-- r = mysql_query("SELECT Path, Name FROM #{TABLE_PREFIX}Media WHERE MediaID = #{attachment_id};").first- next if r.nil?- path = r["Path"]- name = r["Name"]- next unless path.present?-- path.gsub!("s3://content/", "")- path.gsub!("s3://uploads/", "")- file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}"-- if File.exist?(file_path)- upload = create_upload(post.user.id, file_path, File.basename(file_path))- if upload && upload.errors.empty?- # upload.url- filename = name || file_name || File.basename(file_path)- html_for_upload(upload, normalize_text(filename))+ Post+ .where("raw LIKE '%/us.v-cdn.net/%' OR raw LIKE '%[attachment%'")+ .find_each do |post|+ count += 1+ print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)]+ new_raw = post.raw.dup++ new_raw.gsub!(attachment_regex) do |s|+ matches = attachment_regex.match(s)+ attachment_id = matches[1]+ file_name = matches[2]+ next unless attachment_id++ r =+ mysql_query(+ "SELECT Path, Name FROM #{TABLE_PREFIX}Media WHERE MediaID = #{attachment_id};",+ ).first+ next if r.nil?+ path = r["Path"]+ name = r["Name"]+ next unless path.present?++ path.gsub!("s3://content/", "")+ path.gsub!("s3://uploads/", "")+ file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}"++ if File.exist?(file_path)+ upload = create_upload(post.user.id, file_path, File.basename(file_path))+ if upload && upload.errors.empty?+ # upload.url+ filename = name || file_name || File.basename(file_path)+ html_for_upload(upload, normalize_text(filename))+ else+ puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ endelse- puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ puts "Couldn't find file for #{attachment_id}. Skipping."+ nextend- else- puts "Couldn't find file for #{attachment_id}. Skipping."- nextend- end- new_raw.gsub!(cdn_regex) do |s|- matches = cdn_regex.match(s)- attachment_id = matches[1]+ new_raw.gsub!(cdn_regex) do |s|+ matches = cdn_regex.match(s)+ attachment_id = matches[1]- file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}"+ file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}"- if File.exist?(file_path)- upload = create_upload(post.user.id, file_path, File.basename(file_path))- if upload && upload.errors.empty?- upload.url+ if File.exist?(file_path)+ upload = create_upload(post.user.id, file_path, File.basename(file_path))+ if upload && upload.errors.empty?+ upload.url+ else+ puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ endelse- puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ puts "Couldn't find file for #{attachment_id}. Skipping."+ nextend- else- puts "Couldn't find file for #{attachment_id}. Skipping."- nextend- end- if new_raw != post.raw- begin- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, skip_revision: true, skip_validations: true, bypass_bump: true)- rescue- puts "PostRevisor error for #{post.id}"- post.raw = new_raw- post.save(validate: false)+ if new_raw != post.raw+ begin+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ skip_revision: true,+ skip_validations: true,+ bypass_bump: true,+ )+ rescue StandardError+ puts "PostRevisor error for #{post.id}"+ post.raw = new_raw+ post.save(validate: false)+ endendend- endendend@@ -352,7 +372,7 @@ class BulkImport::Vanilla < BulkImport::Base# Otherwise, the file exists but with a prefix:# The p prefix seems to be the full file, so try to find that one first.- ['p', 't', 'n'].each do |prefix|+ %w[p t n].each do |prefix|full_guess = File.join(path, "#{prefix}#{base_guess}")return full_guess if File.exist?(full_guess)end@@ -364,26 +384,30 @@ class BulkImport::Vanilla < BulkImport::Basedef import_categoriesputs "", "Importing categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT CategoryID, ParentCategoryID, Name, Description, SortFROM #{TABLE_PREFIX}CategoryWHERE CategoryID > 0ORDER BY Sort, CategoryID- ").to_a+ ",+ ).to_a# Throw the -1 level categories away since they contain no topics.# Use the next level as root categories.- top_level_categories = categories.select { |c| c["ParentCategoryID"].blank? || c['ParentCategoryID'] == -1 }+ top_level_categories =+ categories.select { |c| c["ParentCategoryID"].blank? || c["ParentCategoryID"] == -1 }# Depth = 2create_categories(top_level_categories) do |category|- next if category_id_from_imported_id(category['CategoryID'])+ next if category_id_from_imported_id(category["CategoryID"]){- imported_id: category['CategoryID'],- name: CGI.unescapeHTML(category['Name']),- description: category['Description'] ? CGI.unescapeHTML(category['Description']) : nil,- position: category['Sort']+ imported_id: category["CategoryID"],+ name: CGI.unescapeHTML(category["Name"]),+ description: category["Description"] ? CGI.unescapeHTML(category["Description"]) : nil,+ position: category["Sort"],}end@@ -393,39 +417,39 @@ class BulkImport::Vanilla < BulkImport::Base# Depth = 3create_categories(subcategories) do |category|- next if category_id_from_imported_id(category['CategoryID'])+ next if category_id_from_imported_id(category["CategoryID"]){- imported_id: category['CategoryID'],- parent_category_id: category_id_from_imported_id(category['ParentCategoryID']),- name: CGI.unescapeHTML(category['Name']),- description: category['Description'] ? CGI.unescapeHTML(category['Description']) : nil,- position: category['Sort']+ imported_id: category["CategoryID"],+ parent_category_id: category_id_from_imported_id(category["ParentCategoryID"]),+ name: CGI.unescapeHTML(category["Name"]),+ description: category["Description"] ? CGI.unescapeHTML(category["Description"]) : nil,+ position: category["Sort"],}end- subcategory_ids = Set.new(subcategories.map { |c| c['CategoryID'] })+ subcategory_ids = Set.new(subcategories.map { |c| c["CategoryID"] })# Depth 4 and 5 need to be tagscategories.each do |c|- next if c['ParentCategoryID'] == -1- next if top_level_category_ids.include?(c['CategoryID'])- next if subcategory_ids.include?(c['CategoryID'])+ next if c["ParentCategoryID"] == -1+ next if top_level_category_ids.include?(c["CategoryID"])+ next if subcategory_ids.include?(c["CategoryID"])# Find a depth 3 category for topics in this categoryparent = c- while !parent.nil? && !subcategory_ids.include?(parent['CategoryID'])- parent = categories.find { |subcat| subcat['CategoryID'] == parent['ParentCategoryID'] }+ while !parent.nil? && !subcategory_ids.include?(parent["CategoryID"])+ parent = categories.find { |subcat| subcat["CategoryID"] == parent["ParentCategoryID"] }endif parent- tag_name = DiscourseTagging.clean_tag(c['Name'])- @category_mappings[c['CategoryID']] = {- category_id: category_id_from_imported_id(parent['CategoryID']),- tag: Tag.find_by_name(tag_name) || Tag.create(name: tag_name)+ tag_name = DiscourseTagging.clean_tag(c["Name"])+ @category_mappings[c["CategoryID"]] = {+ category_id: category_id_from_imported_id(parent["CategoryID"]),+ tag: Tag.find_by_name(tag_name) || Tag.create(name: tag_name),}else- puts '', "Couldn't find a category for #{c['CategoryID']} '#{c['Name']}'!"+ puts "", "Couldn't find a category for #{c["CategoryID"]} '#{c["Name"]}'!"endendend@@ -433,7 +457,8 @@ class BulkImport::Vanilla < BulkImport::Basedef import_topicsputs "", "Importing topics..."- topics_sql = "SELECT DiscussionID, CategoryID, Name, Body, DateInserted, InsertUserID, Announce, Format+ topics_sql =+ "SELECT DiscussionID, CategoryID, Name, Body, DateInserted, InsertUserID, Announce, FormatFROM #{TABLE_PREFIX}DiscussionWHERE DiscussionID > #{@last_imported_topic_id}ORDER BY DiscussionID ASC"@@ -442,11 +467,12 @@ class BulkImport::Vanilla < BulkImport::Basedata = {imported_id: row["DiscussionID"],title: normalize_text(row["Name"]),- category_id: category_id_from_imported_id(row["CategoryID"]) ||- @category_mappings[row["CategoryID"]].try(:[], :category_id),+ category_id:+ category_id_from_imported_id(row["CategoryID"]) ||+ @category_mappings[row["CategoryID"]].try(:[], :category_id),user_id: user_id_from_imported_id(row["InsertUserID"]),- created_at: Time.zone.at(row['DateInserted']),- pinned_at: row['Announce'] == 0 ? nil : Time.zone.at(row['DateInserted'])+ created_at: Time.zone.at(row["DateInserted"]),+ pinned_at: row["Announce"] == 0 ? nil : Time.zone.at(row["DateInserted"]),}(data[:user_id].present? && data[:title].present?) ? data : falseend@@ -455,46 +481,45 @@ class BulkImport::Vanilla < BulkImport::Basecreate_posts(mysql_stream(topics_sql)) do |row|data = {- imported_id: "d-" + row['DiscussionID'].to_s,- topic_id: topic_id_from_imported_id(row['DiscussionID']),+ imported_id: "d-" + row["DiscussionID"].to_s,+ topic_id: topic_id_from_imported_id(row["DiscussionID"]),user_id: user_id_from_imported_id(row["InsertUserID"]),- created_at: Time.zone.at(row['DateInserted']),- raw: clean_up(row['Body'], row['Format'])+ created_at: Time.zone.at(row["DateInserted"]),+ raw: clean_up(row["Body"], row["Format"]),}data[:topic_id].present? ? data : falseend- puts '', 'converting deep categories to tags...'+ puts "", "converting deep categories to tags..."create_topic_tags(mysql_stream(topics_sql)) do |row|- next unless mapping = @category_mappings[row['CategoryID']]+ next unless mapping = @category_mappings[row["CategoryID"]]- {- tag_id: mapping[:tag].id,- topic_id: topic_id_from_imported_id(row["DiscussionID"])- }+ { tag_id: mapping[:tag].id, topic_id: topic_id_from_imported_id(row["DiscussionID"]) }endenddef import_postsputs "", "Importing posts..."- posts = mysql_stream(- "SELECT CommentID, DiscussionID, Body, DateInserted, InsertUserID, Format+ posts =+ mysql_stream(+ "SELECT CommentID, DiscussionID, Body, DateInserted, InsertUserID, FormatFROM #{TABLE_PREFIX}CommentWHERE CommentID > #{@last_imported_post_id}- ORDER BY CommentID ASC")+ ORDER BY CommentID ASC",+ )create_posts(posts) do |row|- next unless topic_id = topic_id_from_imported_id(row['DiscussionID'])- next if row['Body'].blank?+ next unless topic_id = topic_id_from_imported_id(row["DiscussionID"])+ next if row["Body"].blank?{- imported_id: row['CommentID'],+ imported_id: row["CommentID"],topic_id: topic_id,- user_id: user_id_from_imported_id(row['InsertUserID']),- created_at: Time.zone.at(row['DateInserted']),- raw: clean_up(row['Body'], row['Format'])+ user_id: user_id_from_imported_id(row["InsertUserID"]),+ created_at: Time.zone.at(row["DateInserted"]),+ raw: clean_up(row["Body"], row["Format"]),}endend@@ -505,31 +530,31 @@ class BulkImport::Vanilla < BulkImport::Basetag_mapping = {}mysql_query("SELECT TagID, Name FROM #{TABLE_PREFIX}Tag").each do |row|- tag_name = DiscourseTagging.clean_tag(row['Name'])+ tag_name = DiscourseTagging.clean_tag(row["Name"])tag = Tag.find_by_name(tag_name) || Tag.create(name: tag_name)- tag_mapping[row['TagID']] = tag.id+ tag_mapping[row["TagID"]] = tag.idend- tags = mysql_query(- "SELECT TagID, DiscussionID+ tags =+ mysql_query(+ "SELECT TagID, DiscussionIDFROM #{TABLE_PREFIX}TagDiscussionWHERE DiscussionID > #{@last_imported_topic_id}- ORDER BY DateInserted")+ ORDER BY DateInserted",+ )create_topic_tags(tags) do |row|- next unless topic_id = topic_id_from_imported_id(row['DiscussionID'])+ next unless topic_id = topic_id_from_imported_id(row["DiscussionID"])- {- topic_id: topic_id,- tag_id: tag_mapping[row['TagID']]- }+ { topic_id: topic_id, tag_id: tag_mapping[row["TagID"]] }endenddef import_private_topicsputs "", "Importing private topics..."- topics_sql = "SELECT c.ConversationID, c.Subject, m.MessageID, m.Body, c.DateInserted, c.InsertUserID+ topics_sql =+ "SELECT c.ConversationID, c.Subject, m.MessageID, m.Body, c.DateInserted, c.InsertUserIDFROM #{TABLE_PREFIX}Conversation c, #{TABLE_PREFIX}ConversationMessage mWHERE c.FirstMessageID = m.MessageIDAND c.ConversationID > #{@last_imported_private_topic_id - PRIVATE_OFFSET}@@ -539,9 +564,10 @@ class BulkImport::Vanilla < BulkImport::Base{archetype: Archetype.private_message,imported_id: row["ConversationID"] + PRIVATE_OFFSET,- title: row["Subject"] ? normalize_text(row["Subject"]) : "Conversation #{row["ConversationID"]}",+ title:+ row["Subject"] ? normalize_text(row["Subject"]) : "Conversation #{row["ConversationID"]}",user_id: user_id_from_imported_id(row["InsertUserID"]),- created_at: Time.zone.at(row['DateInserted'])+ created_at: Time.zone.at(row["DateInserted"]),}endend@@ -549,7 +575,8 @@ class BulkImport::Vanilla < BulkImport::Basedef import_topic_allowed_usersputs "", "importing topic_allowed_users..."- topic_allowed_users_sql = "+ topic_allowed_users_sql =+ "SELECT ConversationID, UserIDFROM #{TABLE_PREFIX}UserConversationWHERE Deleted = 0@@ -559,45 +586,43 @@ class BulkImport::Vanilla < BulkImport::Baseadded = 0create_topic_allowed_users(mysql_stream(topic_allowed_users_sql)) do |row|- next unless topic_id = topic_id_from_imported_id(row['ConversationID'] + PRIVATE_OFFSET)+ next unless topic_id = topic_id_from_imported_id(row["ConversationID"] + PRIVATE_OFFSET)next unless user_id = user_id_from_imported_id(row["UserID"])added += 1- {- topic_id: topic_id,- user_id: user_id,- }+ { topic_id: topic_id, user_id: user_id }end- puts '', "Added #{added} topic_allowed_users records."+ puts "", "Added #{added} topic_allowed_users records."enddef import_private_postsputs "", "importing private replies..."- private_posts_sql = "+ private_posts_sql =+ "SELECT ConversationID, MessageID, Body, InsertUserID, DateInserted, FormatFROM GDN_ConversationMessageWHERE ConversationID > #{@last_imported_private_topic_id - PRIVATE_OFFSET}ORDER BY ConversationID ASC, MessageID ASC"create_posts(mysql_stream(private_posts_sql)) do |row|- next unless topic_id = topic_id_from_imported_id(row['ConversationID'] + PRIVATE_OFFSET)+ next unless topic_id = topic_id_from_imported_id(row["ConversationID"] + PRIVATE_OFFSET){- imported_id: row['MessageID'] + PRIVATE_OFFSET,+ imported_id: row["MessageID"] + PRIVATE_OFFSET,topic_id: topic_id,- user_id: user_id_from_imported_id(row['InsertUserID']),- created_at: Time.zone.at(row['DateInserted']),- raw: clean_up(row['Body'], row['Format'])+ user_id: user_id_from_imported_id(row["InsertUserID"]),+ created_at: Time.zone.at(row["DateInserted"]),+ raw: clean_up(row["Body"], row["Format"]),}endend# TODO: too slowdef create_permalinks- puts '', 'Creating permalinks...', ''+ puts "", "Creating permalinks...", ""- puts ' User pages...'+ puts " User pages..."start = Time.nowcount = 0@@ -606,21 +631,23 @@ class BulkImport::Vanilla < BulkImport::Basesql = "COPY permalinks (url, created_at, updated_at, external_url) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- User.includes(:_custom_fields).find_each do |u|- count += 1- ucf = u.custom_fields- if ucf && ucf["import_id"]- vanilla_username = ucf["import_username"] || u.username- @raw_connection.put_copy_data(- ["profile/#{vanilla_username}", now, now, "/users/#{u.username}"]- )- end+ User+ .includes(:_custom_fields)+ .find_each do |u|+ count += 1+ ucf = u.custom_fields+ if ucf && ucf["import_id"]+ vanilla_username = ucf["import_username"] || u.username+ @raw_connection.put_copy_data(+ ["profile/#{vanilla_username}", now, now, "/users/#{u.username}"],+ )+ end- print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)] if count % 5000 == 0- end+ print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)] if count % 5000 == 0+ endend- puts '', '', ' Topics and posts...'+ puts "", "", " Topics and posts..."start = Time.nowcount = 0@@ -628,38 +655,36 @@ class BulkImport::Vanilla < BulkImport::Basesql = "COPY permalinks (url, topic_id, post_id, created_at, updated_at) FROM STDIN"@raw_connection.copy_data(sql, @encoder) do- Post.includes(:_custom_fields).find_each do |post|- count += 1- pcf = post.custom_fields- if pcf && pcf["import_id"]- topic = post.topic- if topic.present?- id = pcf["import_id"].split('-').last- if post.post_number == 1- slug = Slug.for(topic.title) # probably matches what vanilla would do...- @raw_connection.put_copy_data(- ["discussion/#{id}/#{slug}", topic.id, nil, now, now]- )- else- @raw_connection.put_copy_data(- ["discussion/comment/#{id}", nil, post.id, now, now]- )+ Post+ .includes(:_custom_fields)+ .find_each do |post|+ count += 1+ pcf = post.custom_fields+ if pcf && pcf["import_id"]+ topic = post.topic+ if topic.present?+ id = pcf["import_id"].split("-").last+ if post.post_number == 1+ slug = Slug.for(topic.title) # probably matches what vanilla would do...+ @raw_connection.put_copy_data(["discussion/#{id}/#{slug}", topic.id, nil, now, now])+ else+ @raw_connection.put_copy_data(["discussion/comment/#{id}", nil, post.id, now, now])+ endendend- end- print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)] if count % 5000 == 0- end+ print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)] if count % 5000 == 0+ endendenddef clean_up(raw, format)raw.encode!("utf-8", "utf-8", invalid: :replace, undef: :replace, replace: "")- raw.gsub!(/<(.+)> <\/\1>/, "\n\n")+ raw.gsub!(%r{<(.+)> </\1>}, "\n\n")html =- if format == 'Html'+ if format == "Html"rawelsemarkdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, tables: true)@@ -668,29 +693,23 @@ class BulkImport::Vanilla < BulkImport::Basedoc = Nokogiri::HTML5.fragment(html)- doc.css("blockquote").each do |bq|- name = bq["rel"]- user = User.find_by(name: name)- bq.replace %{<br>[QUOTE="#{user&.username || name}"]\n#{bq.inner_html}\n[/QUOTE]<br>}- end+ doc+ .css("blockquote")+ .each do |bq|+ name = bq["rel"]+ user = User.find_by(name: name)+ bq.replace %{<br>[QUOTE="#{user&.username || name}"]\n#{bq.inner_html}\n[/QUOTE]<br>}+ end- doc.css("font").reverse.each do |f|- f.replace f.inner_html- end+ doc.css("font").reverse.each { |f| f.replace f.inner_html }- doc.css("span").reverse.each do |f|- f.replace f.inner_html- end+ doc.css("span").reverse.each { |f| f.replace f.inner_html }- doc.css("sub").reverse.each do |f|- f.replace f.inner_html- end+ doc.css("sub").reverse.each { |f| f.replace f.inner_html }- doc.css("u").reverse.each do |f|- f.replace f.inner_html- end+ doc.css("u").reverse.each { |f| f.replace f.inner_html }- markdown = format == 'Html' ? ReverseMarkdown.convert(doc.to_html) : doc.to_html+ markdown = format == "Html" ? ReverseMarkdown.convert(doc.to_html) : doc.to_htmlmarkdown.gsub!(/\[QUOTE="([^;]+);c-(\d+)"\]/i) { "[QUOTE=#{$1};#{$2}]" }markdown = process_raw_text(markdown)@@ -702,31 +721,31 @@ class BulkImport::Vanilla < BulkImport::Basetext = raw.duptext = CGI.unescapeHTML(text)- text.gsub!(/:(?:\w{8})\]/, ']')+ text.gsub!(/:(?:\w{8})\]/, "]")# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- text.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/i, '[\2](\1)')+ text.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}i, '[\2](\1)')# phpBB shortens link text like this, which breaks our markdown processing:# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- text.gsub!(/\[http(s)?:\/\/(www\.)?/i, '[')+ text.gsub!(%r{\[http(s)?://(www\.)?}i, "[")# convert list tags to ul and list=1 tags to ol# list=a is not supported, so handle it like list=1# list=9 and list=x have the same result as list=1 and list=a- text.gsub!(/\[list\](.*?)\[\/list:u\]/mi, '[ul]\1[/ul]')- text.gsub!(/\[list=.*?\](.*?)\[\/list:o\]/mi, '[ol]\1[/ol]')+ text.gsub!(%r{\[list\](.*?)\[/list:u\]}mi, '[ul]\1[/ul]')+ text.gsub!(%r{\[list=.*?\](.*?)\[/list:o\]}mi, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:- text.gsub!(/\[\*\](.*?)\[\/\*:m\]/mi, '[li]\1[/li]')+ text.gsub!(%r{\[\*\](.*?)\[/\*:m\]}mi, '[li]\1[/li]')# [QUOTE="<username>"] -- add newlinetext.gsub!(/(\[quote="[a-zA-Z\d]+"\])/i) { "#{$1}\n" }# [/QUOTE] -- add newline- text.gsub!(/(\[\/quote\])/i) { "\n#{$1}" }+ text.gsub!(%r{(\[/quote\])}i) { "\n#{$1}" }textend@@ -742,7 +761,6 @@ class BulkImport::Vanilla < BulkImport::Basedef mysql_query(sql)@client.query(sql)end-endBulkImport::Vanilla.new.startdiff --git a/script/bulk_import/vbulletin.rb b/script/bulk_import/vbulletin.rbindex fde0fbe7d72..b836338a516 100644--- a/script/bulk_import/vbulletin.rb+++ b/script/bulk_import/vbulletin.rb@@ -7,43 +7,42 @@ require "htmlentities"require "parallel"class BulkImport::VBulletin < BulkImport::Base-- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "vb_"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "vb_"SUSPENDED_TILL ||= Date.new(3000, 1, 1)- ATTACHMENT_DIR ||= ENV['ATTACHMENT_DIR'] || '/shared/import/data/attachments'- AVATAR_DIR ||= ENV['AVATAR_DIR'] || '/shared/import/data/customavatars'+ ATTACHMENT_DIR ||= ENV["ATTACHMENT_DIR"] || "/shared/import/data/attachments"+ AVATAR_DIR ||= ENV["AVATAR_DIR"] || "/shared/import/data/customavatars"def initializesuper- host = ENV["DB_HOST"] || "localhost"+ host = ENV["DB_HOST"] || "localhost"username = ENV["DB_USERNAME"] || "root"password = ENV["DB_PASSWORD"]database = ENV["DB_NAME"] || "vbulletin"- charset = ENV["DB_CHARSET"] || "utf8"+ charset = ENV["DB_CHARSET"] || "utf8"@html_entities = HTMLEntities.new@encoding = CHARSET_MAP[charset]- @client = Mysql2::Client.new(- host: host,- username: username,- password: password,- database: database,- encoding: charset,- reconnect: true- )+ @client =+ Mysql2::Client.new(+ host: host,+ username: username,+ password: password,+ database: database,+ encoding: charset,+ reconnect: true,+ )@client.query_options.merge!(as: :array, cache_rows: false)- @has_post_thanks = mysql_query(<<-SQL+ @has_post_thanks = mysql_query(<<-SQL).to_a.count > 0SELECT `COLUMN_NAME`FROM `INFORMATION_SCHEMA`.`COLUMNS`WHERE `TABLE_SCHEMA`='#{database}'AND `TABLE_NAME`='user'AND `COLUMN_NAME` LIKE 'post_thanks_%'SQL- ).to_a.count > 0@user_ids_by_email = {}end@@ -95,7 +94,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_groups- puts '', "Importing groups..."+ puts "", "Importing groups..."groups = mysql_stream <<-SQLSELECT usergroupid, title, description, usertitle@@ -115,7 +114,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_users- puts '', "Importing users..."+ puts "", "Importing users..."users = mysql_stream <<-SQLSELECT u.userid, username, email, joindate, birthday, ipaddress, u.usergroupid, bandate, liftdate@@ -145,7 +144,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_user_emails- puts '', "Importing user emails..."+ puts "", "Importing user emails..."users = mysql_stream <<-SQLSELECT u.userid, email, joindate@@ -155,7 +154,7 @@ class BulkImport::VBulletin < BulkImport::BaseSQLcreate_user_emails(users) do |row|- user_id, email = row[0 .. 1]+ user_id, email = row[0..1]@user_ids_by_email[email.downcase] ||= []user_ids = @user_ids_by_email[email.downcase] << user_id@@ -170,7 +169,7 @@ class BulkImport::VBulletin < BulkImport::Baseimported_id: user_id,imported_user_id: user_id,email: email,- created_at: Time.zone.at(row[2])+ created_at: Time.zone.at(row[2]),}end@@ -179,7 +178,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_user_stats- puts '', "Importing user stats..."+ puts "", "Importing user stats..."users = mysql_stream <<-SQLSELECT u.userid, joindate, posts, COUNT(t.threadid) AS threads, p.dateline@@ -199,7 +198,7 @@ class BulkImport::VBulletin < BulkImport::Basenew_since: Time.zone.at(row[1]),post_count: row[2],topic_count: row[3],- first_post_created_at: row[4] && Time.zone.at(row[4])+ first_post_created_at: row[4] && Time.zone.at(row[4]),}if @has_post_thanks@@ -212,7 +211,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_group_users- puts '', "Importing group users..."+ puts "", "Importing group users..."group_users = mysql_stream <<-SQLSELECT usergroupid, userid@@ -221,15 +220,12 @@ class BulkImport::VBulletin < BulkImport::BaseSQLcreate_group_users(group_users) do |row|- {- group_id: group_id_from_imported_id(row[0]),- user_id: user_id_from_imported_id(row[1]),- }+ { group_id: group_id_from_imported_id(row[0]), user_id: user_id_from_imported_id(row[1]) }endenddef import_user_passwords- puts '', "Importing user passwords..."+ puts "", "Importing user passwords..."user_passwords = mysql_stream <<-SQLSELECT userid, password@@ -239,15 +235,12 @@ class BulkImport::VBulletin < BulkImport::BaseSQLcreate_custom_fields("user", "password", user_passwords) do |row|- {- record_id: user_id_from_imported_id(row[0]),- value: row[1],- }+ { record_id: user_id_from_imported_id(row[0]), value: row[1] }endenddef import_user_salts- puts '', "Importing user salts..."+ puts "", "Importing user salts..."user_salts = mysql_stream <<-SQLSELECT userid, salt@@ -258,15 +251,12 @@ class BulkImport::VBulletin < BulkImport::BaseSQLcreate_custom_fields("user", "salt", user_salts) do |row|- {- record_id: user_id_from_imported_id(row[0]),- value: row[1],- }+ { record_id: user_id_from_imported_id(row[0]), value: row[1] }endenddef import_user_profiles- puts '', "Importing user profiles..."+ puts "", "Importing user profiles..."user_profiles = mysql_stream <<-SQLSELECT userid, homepage, profilevisits@@ -278,16 +268,23 @@ class BulkImport::VBulletin < BulkImport::Basecreate_user_profiles(user_profiles) do |row|{user_id: user_id_from_imported_id(row[0]),- website: (URI.parse(row[1]).to_s rescue nil),+ website:+ (+ begin+ URI.parse(row[1]).to_s+ rescue StandardError+ nil+ end+ ),views: row[2],}endenddef import_categories- puts '', "Importing categories..."+ puts "", "Importing categories..."- categories = mysql_query(<<-SQL+ categories = mysql_query(<<-SQL).to_aselectforumid,parentid,@@ -311,23 +308,20 @@ class BulkImport::VBulletin < BulkImport::Basefrom forumorder by forumidSQL- ).to_areturn if categories.empty?- parent_categories = categories.select { |c| c[1] == -1 }+ parent_categories = categories.select { |c| c[1] == -1 }children_categories = categories.select { |c| c[1] != -1 }parent_category_ids = Set.new parent_categories.map { |c| c[0] }# cut down the tree to only 2 levels of categorieschildren_categories.each do |cc|- until parent_category_ids.include?(cc[1])- cc[1] = categories.find { |c| c[0] == cc[1] }[1]- end+ cc[1] = categories.find { |c| c[0] == cc[1] }[1] until parent_category_ids.include?(cc[1])end- puts '', "Importing parent categories..."+ puts "", "Importing parent categories..."create_categories(parent_categories) do |row|{imported_id: row[0],@@ -337,7 +331,7 @@ class BulkImport::VBulletin < BulkImport::Base}end- puts '', "Importing children categories..."+ puts "", "Importing children categories..."create_categories(children_categories) do |row|{imported_id: row[0],@@ -350,7 +344,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_topics- puts '', "Importing topics..."+ puts "", "Importing topics..."topics = mysql_stream <<-SQLSELECT threadid, title, forumid, postuserid, open, dateline, views, visible, sticky@@ -381,7 +375,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_posts- puts '', "Importing posts..."+ puts "", "Importing posts..."posts = mysql_stream <<-SQLSELECT postid, p.threadid, parentid, userid, p.dateline, p.visible, pagetext@@ -396,7 +390,8 @@ class BulkImport::VBulletin < BulkImport::Basecreate_posts(posts) do |row|topic_id = topic_id_from_imported_id(row[1])replied_post_topic_id = topic_id_from_imported_post_id(row[2])- reply_to_post_number = topic_id == replied_post_topic_id ? post_number_from_imported_id(row[2]) : nil+ reply_to_post_number =+ topic_id == replied_post_topic_id ? post_number_from_imported_id(row[2]) : nilpost = {imported_id: row[0],@@ -415,7 +410,7 @@ class BulkImport::VBulletin < BulkImport::Basedef import_likesreturn unless @has_post_thanks- puts '', "Importing likes..."+ puts "", "Importing likes..."@imported_likes = Set.new@last_imported_post_id = 0@@ -438,13 +433,13 @@ class BulkImport::VBulletin < BulkImport::Basepost_id: post_id_from_imported_id(row[0]),user_id: user_id_from_imported_id(row[1]),post_action_type_id: 2,- created_at: Time.zone.at(row[2])+ created_at: Time.zone.at(row[2]),}endenddef import_private_topics- puts '', "Importing private topics..."+ puts "", "Importing private topics..."@imported_topics = {}@@ -473,34 +468,31 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_topic_allowed_users- puts '', "Importing topic allowed users..."+ puts "", "Importing topic allowed users..."allowed_users = Set.new- mysql_stream(<<-SQL+ mysql_stream(<<-SQL).each do |row|SELECT pmtextid, touserarrayFROM #{TABLE_PREFIX}pmtextWHERE pmtextid > (#{@last_imported_private_topic_id - PRIVATE_OFFSET})ORDER BY pmtextidSQL- ).each do |row|next unless topic_id = topic_id_from_imported_id(row[0] + PRIVATE_OFFSET)- row[1].scan(/i:(\d+)/).flatten.each do |id|- next unless user_id = user_id_from_imported_id(id)- allowed_users << [topic_id, user_id]- end+ row[1]+ .scan(/i:(\d+)/)+ .flatten+ .each do |id|+ next unless user_id = user_id_from_imported_id(id)+ allowed_users << [topic_id, user_id]+ endend- create_topic_allowed_users(allowed_users) do |row|- {- topic_id: row[0],- user_id: row[1],- }- end+ create_topic_allowed_users(allowed_users) { |row| { topic_id: row[0], user_id: row[1] } }enddef import_private_posts- puts '', "Importing private posts..."+ puts "", "Importing private posts..."posts = mysql_stream <<-SQLSELECT pmtextid, title, fromuserid, touserarray, dateline, message@@ -527,7 +519,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef create_permalink_file- puts '', 'Creating Permalink File...', ''+ puts "", "Creating Permalink File...", ""total = Topic.listable_topics.countstart = Time.now@@ -538,9 +530,9 @@ class BulkImport::VBulletin < BulkImport::Basei += 1pcf = topic.posts.includes(:_custom_fields).where(post_number: 1).first.custom_fieldsif pcf && pcf["import_id"]- id = pcf["import_id"].split('-').last+ id = pcf["import_id"].split("-").last- f.print [ "XXX#{id} YYY#{topic.id}" ].to_csv+ f.print ["XXX#{id} YYY#{topic.id}"].to_csvprint "\r%7d/%7d - %6d/sec" % [i, total, i.to_f / (Time.now - start)] if i % 5000 == 0endend@@ -549,7 +541,8 @@ class BulkImport::VBulletin < BulkImport::Base# find the uploaded file information from the dbdef find_upload(post, attachment_id)- sql = "SELECT a.attachmentid attachment_id, a.userid user_id, a.filename filename+ sql =+ "SELECT a.attachmentid attachment_id, a.userid user_id, a.filename filenameFROM #{TABLE_PREFIX}attachment aWHERE a.attachmentid = #{attachment_id}"results = mysql_query(sql)@@ -563,9 +556,10 @@ class BulkImport::VBulletin < BulkImport::Baseuser_id = row[1]db_filename = row[2]- filename = File.join(ATTACHMENT_DIR, user_id.to_s.split('').join('/'), "#{attachment_id}.attach")+ filename =+ File.join(ATTACHMENT_DIR, user_id.to_s.split("").join("/"), "#{attachment_id}.attach")real_filename = db_filename- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."unless File.exist?(filename)puts "Attachment file #{row.inspect} doesn't exist"@@ -588,7 +582,7 @@ class BulkImport::VBulletin < BulkImport::Baseenddef import_attachments- puts '', 'importing attachments...'+ puts "", "importing attachments..."RateLimiter.disablecurrent_count = 0@@ -596,7 +590,7 @@ class BulkImport::VBulletin < BulkImport::Basesuccess_count = 0fail_count = 0- attachment_regex = /\[attach[^\]]*\](\d+)\[\/attach\]/i+ attachment_regex = %r{\[attach[^\]]*\](\d+)\[/attach\]}iPost.find_each do |post|current_count += 1@@ -618,7 +612,12 @@ class BulkImport::VBulletin < BulkImport::Baseendif new_raw != post.raw- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, bypass_bump: true, edit_reason: 'Import attachments from vBulletin')+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ bypass_bump: true,+ edit_reason: "Import attachments from vBulletin",+ )endsuccess_count += 1@@ -639,7 +638,7 @@ class BulkImport::VBulletin < BulkImport::BaseDir.foreach(AVATAR_DIR) do |item|print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)]- next if item == ('.') || item == ('..') || item == ('.DS_Store')+ next if item == (".") || item == ("..") || item == (".DS_Store")next unless item =~ /avatar(\d+)_(\d).gif/scan = item.scan(/avatar(\d+)_(\d).gif/)next unless scan[0][0].present?@@ -671,11 +670,10 @@ class BulkImport::VBulletin < BulkImport::Basedef import_signaturesputs "Importing user signatures..."- total_count = mysql_query(<<-SQL+ total_count = mysql_query(<<-SQL).first[0].to_iSELECT COUNT(userid) countFROM #{TABLE_PREFIX}sigparsedSQL- ).first[0].to_icurrent_count = 0user_signatures = mysql_stream <<-SQL@@ -695,13 +693,20 @@ class BulkImport::VBulletin < BulkImport::Basenext unless u.present?# can not hold dupes- UserCustomField.where(user_id: u.id, name: ["see_signatures", "signature_raw", "signature_cooked"]).destroy_all+ UserCustomField.where(+ user_id: u.id,+ name: %w[see_signatures signature_raw signature_cooked],+ ).destroy_all- user_sig.gsub!(/\[\/?sigpic\]/i, "")+ user_sig.gsub!(%r{\[/?sigpic\]}i, "")UserCustomField.create!(user_id: u.id, name: "see_signatures", value: true)UserCustomField.create!(user_id: u.id, name: "signature_raw", value: user_sig)- UserCustomField.create!(user_id: u.id, name: "signature_cooked", value: PrettyText.cook(user_sig, omit_nofollow: false))+ UserCustomField.create!(+ user_id: u.id,+ name: "signature_cooked",+ value: PrettyText.cook(user_sig, omit_nofollow: false),+ )endend@@ -710,15 +715,15 @@ class BulkImport::VBulletin < BulkImport::Basetotal_count = 0duplicated = {}- @user_ids_by_email.- select { |e, ids| ids.count > 1 }.- each_with_index do |(email, ids), i|- duplicated[email] = [ ids, i ]+ @user_ids_by_email+ .select { |e, ids| ids.count > 1 }+ .each_with_index do |(email, ids), i|+ duplicated[email] = [ids, i]count += 1total_count += ids.countend- puts '', "Merging #{total_count} duplicated users across #{count} distinct emails..."+ puts "", "Merging #{total_count} duplicated users across #{count} distinct emails..."start = Time.now@@ -727,14 +732,15 @@ class BulkImport::VBulletin < BulkImport::Basenext unless email.presence# queried one by one to ensure ordering- first, *rest = user_ids.map do |id|- UserCustomField.includes(:user).find_by!(name: 'import_id', value: id).user- end+ first, *rest =+ user_ids.map do |id|+ UserCustomField.includes(:user).find_by!(name: "import_id", value: id).user+ endrest.each do |dup|UserMerger.new(dup, first).merge!first.reload- printf '.'+ printf "."endprint "\n%6d/%6d - %6d/sec" % [i, count, i.to_f / (Time.now - start)] if i % 10 == 0@@ -744,13 +750,11 @@ class BulkImport::VBulletin < BulkImport::Baseenddef save_duplicated_users- File.open('duplicated_users.json', 'w+') do |f|- f.puts @user_ids_by_email.to_json- end+ File.open("duplicated_users.json", "w+") { |f| f.puts @user_ids_by_email.to_json }enddef read_duplicated_users- @user_ids_by_email = JSON.parse File.read('duplicated_users.json')+ @user_ids_by_email = JSON.parse File.read("duplicated_users.json")enddef extract_pm_title(title)@@ -759,17 +763,26 @@ class BulkImport::VBulletin < BulkImport::Basedef parse_birthday(birthday)return if birthday.blank?- date_of_birth = Date.strptime(birthday.gsub(/[^\d-]+/, ""), "%m-%d-%Y") rescue nil+ date_of_birth =+ begin+ Date.strptime(birthday.gsub(/[^\d-]+/, ""), "%m-%d-%Y")+ rescue StandardError+ nil+ endreturn if date_of_birth.nil?- date_of_birth.year < 1904 ? Date.new(1904, date_of_birth.month, date_of_birth.day) : date_of_birth+ if date_of_birth.year < 1904+ Date.new(1904, date_of_birth.month, date_of_birth.day)+ else+ date_of_birth+ endenddef print_status(current, max, start_time = nil)if start_time.present?elapsed_seconds = Time.now - start_time- elements_per_minute = '[%.0f items/min] ' % [current / elapsed_seconds.to_f * 60]+ elements_per_minute = "[%.0f items/min] " % [current / elapsed_seconds.to_f * 60]else- elements_per_minute = ''+ elements_per_minute = ""endprint "\r%9d / %d (%5.1f%%) %s" % [current, max, current / max.to_f * 100, elements_per_minute]@@ -782,7 +795,6 @@ class BulkImport::VBulletin < BulkImport::Basedef mysql_query(sql)@client.query(sql)end-endBulkImport::VBulletin.new.rundiff --git a/script/bulk_import/vbulletin5.rb b/script/bulk_import/vbulletin5.rbindex 9be967c25c4..e952ab5d764 100644--- a/script/bulk_import/vbulletin5.rb+++ b/script/bulk_import/vbulletin5.rb@@ -5,47 +5,56 @@ require "cgi"require "set"require "mysql2"require "htmlentities"-require 'ruby-bbcode-to-md'-require 'find'+require "ruby-bbcode-to-md"+require "find"class BulkImport::VBulletin5 < BulkImport::Base-DB_PREFIX = ""SUSPENDED_TILL ||= Date.new(3000, 1, 1)- ATTACH_DIR ||= ENV['ATTACH_DIR'] || '/shared/import/data/attachments'- AVATAR_DIR ||= ENV['AVATAR_DIR'] || '/shared/import/data/customavatars'+ ATTACH_DIR ||= ENV["ATTACH_DIR"] || "/shared/import/data/attachments"+ AVATAR_DIR ||= ENV["AVATAR_DIR"] || "/shared/import/data/customavatars"ROOT_NODE = 2def initializesuper- host = ENV["DB_HOST"] || "localhost"+ host = ENV["DB_HOST"] || "localhost"username = ENV["DB_USERNAME"] || "root"password = ENV["DB_PASSWORD"]database = ENV["DB_NAME"] || "vbulletin"- charset = ENV["DB_CHARSET"] || "utf8"+ charset = ENV["DB_CHARSET"] || "utf8"@html_entities = HTMLEntities.new@encoding = CHARSET_MAP[charset]@bbcode_to_md = true- @client = Mysql2::Client.new(- host: host,- username: username,- password: password,- database: database,- encoding: charset,- reconnect: true- )+ @client =+ Mysql2::Client.new(+ host: host,+ username: username,+ password: password,+ database: database,+ encoding: charset,+ reconnect: true,+ )@client.query_options.merge!(as: :array, cache_rows: false)# TODO: Add `LIMIT 1` to the below queries# ------# be aware there may be other contenttypeid's in use, such as poll, link, video, etc.- @forum_typeid = mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Forum'").to_a[0][0]- @channel_typeid = mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Channel'").to_a[0][0]- @text_typeid = mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Text'").to_a[0][0]+ @forum_typeid =+ mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Forum'").to_a[0][+ 0+ ]+ @channel_typeid =+ mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Channel'").to_a[+ 0+ ][+ 0+ ]+ @text_typeid =+ mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Text'").to_a[0][0]enddef execute@@ -127,7 +136,7 @@ class BulkImport::VBulletin5 < BulkImport::Basedate_of_birth: parse_birthday(row[3]),primary_group_id: group_id_from_imported_id(row[5]),admin: row[5] == 6,- moderator: row[5] == 7+ moderator: row[5] == 7,}u[:ip_address] = row[4][/\b(?:\d{1,3}\.){3}\d{1,3}\b/] if row[4].present?if row[7]@@ -153,7 +162,7 @@ class BulkImport::VBulletin5 < BulkImport::Baseimported_id: row[0],imported_user_id: row[0],email: random_email,- created_at: Time.zone.at(row[2])+ created_at: Time.zone.at(row[2]),}endend@@ -203,10 +212,7 @@ class BulkImport::VBulletin5 < BulkImport::BaseSQLcreate_group_users(group_users) do |row|- {- group_id: group_id_from_imported_id(row[0]),- user_id: user_id_from_imported_id(row[1]),- }+ { group_id: group_id_from_imported_id(row[0]), user_id: user_id_from_imported_id(row[1]) }end# import secondary group memberships@@ -228,12 +234,7 @@ class BulkImport::VBulletin5 < BulkImport::Baseendend- create_group_users(group_mapping) do |row|- {- group_id: row[0],- user_id: row[1]- }- end+ create_group_users(group_mapping) { |row| { group_id: row[0], user_id: row[1] } }enddef import_user_profiles@@ -249,7 +250,14 @@ class BulkImport::VBulletin5 < BulkImport::Basecreate_user_profiles(user_profiles) do |row|{user_id: user_id_from_imported_id(row[0]),- website: (URI.parse(row[1]).to_s rescue nil),+ website:+ (+ begin+ URI.parse(row[1]).to_s+ rescue StandardError+ nil+ end+ ),views: row[2],}end@@ -258,7 +266,7 @@ class BulkImport::VBulletin5 < BulkImport::Basedef import_categoriesputs "Importing categories..."- categories = mysql_query(<<-SQL+ categories = mysql_query(<<-SQL).to_aSELECT nodeid AS forumid, title, description, displayorder, parentid, urlidentFROM #{DB_PREFIX}nodeWHERE parentid = #{ROOT_NODE}@@ -269,11 +277,10 @@ class BulkImport::VBulletin5 < BulkImport::BaseWHERE contenttypeid = #{@channel_typeid}AND nodeid > #{@last_imported_category_id}SQL- ).to_areturn if categories.empty?- parent_categories = categories.select { |c| c[4] == ROOT_NODE }+ parent_categories = categories.select { |c| c[4] == ROOT_NODE }children_categories = categories.select { |c| c[4] != ROOT_NODE }parent_category_ids = Set.new parent_categories.map { |c| c[0] }@@ -285,7 +292,7 @@ class BulkImport::VBulletin5 < BulkImport::Basename: normalize_text(row[1]),description: normalize_text(row[2]),position: row[3],- slug: row[5]+ slug: row[5],}end@@ -297,7 +304,7 @@ class BulkImport::VBulletin5 < BulkImport::Basedescription: normalize_text(row[2]),position: row[3],parent_category_id: category_id_from_imported_id(row[4]),- slug: row[5]+ slug: row[5],}endend@@ -428,7 +435,7 @@ class BulkImport::VBulletin5 < BulkImport::Basepost_id: post_id,user_id: user_id,post_action_type_id: 2,- created_at: Time.zone.at(row[2])+ created_at: Time.zone.at(row[2]),}endend@@ -455,7 +462,6 @@ class BulkImport::VBulletin5 < BulkImport::Baseuser_id: user_id_from_imported_id(row[2]),created_at: Time.zone.at(row[3]),}-endend@@ -475,17 +481,18 @@ class BulkImport::VBulletin5 < BulkImport::Baseusers_added = Set.newcreate_topic_allowed_users(mysql_stream(allowed_users_sql)) do |row|- next unless topic_id = topic_id_from_imported_id(row[0] + PRIVATE_OFFSET) || topic_id_from_imported_id(row[2] + PRIVATE_OFFSET)+ unless topic_id =+ topic_id_from_imported_id(row[0] + PRIVATE_OFFSET) ||+ topic_id_from_imported_id(row[2] + PRIVATE_OFFSET)+ next+ endnext unless user_id = user_id_from_imported_id(row[1])next if users_added.add?([topic_id, user_id]).nil?added += 1- {- topic_id: topic_id,- user_id: user_id,- }+ { topic_id: topic_id, user_id: user_id }end- puts '', "Added #{added} topic allowed users records."+ puts "", "Added #{added} topic allowed users records."enddef import_private_first_posts@@ -543,7 +550,7 @@ class BulkImport::VBulletin5 < BulkImport::Baseenddef create_permalinks- puts '', 'creating permalinks...', ''+ puts "", "creating permalinks...", ""# add permalink normalizations to site settings# EVERYTHING: /.*\/([\w-]+)$/\1 -- selects the last segment of the URL@@ -580,21 +587,23 @@ class BulkImport::VBulletin5 < BulkImport::Basereturn nilend- tmpfile = 'attach_' + row[6].to_s- filename = File.join('/tmp/', tmpfile)- File.open(filename, 'wb') { |f| f.write(row[5]) }+ tmpfile = "attach_" + row[6].to_s+ filename = File.join("/tmp/", tmpfile)+ File.open(filename, "wb") { |f| f.write(row[5]) }filenameenddef find_upload(post, opts = {})if opts[:node_id].present?- sql = "SELECT a.nodeid, n.parentid, a.filename, fd.userid, LENGTH(fd.filedata), filedata, fd.filedataid+ sql =+ "SELECT a.nodeid, n.parentid, a.filename, fd.userid, LENGTH(fd.filedata), filedata, fd.filedataidFROM #{DB_PREFIX}attach aLEFT JOIN #{DB_PREFIX}filedata fd ON fd.filedataid = a.filedataidLEFT JOIN #{DB_PREFIX}node n ON n.nodeid = a.nodeidWHERE a.nodeid = #{opts[:node_id]}"elsif opts[:attachment_id].present?- sql = "SELECT a.nodeid, n.parentid, a.filename, fd.userid, LENGTH(fd.filedata), filedata, fd.filedataid+ sql =+ "SELECT a.nodeid, n.parentid, a.filename, fd.userid, LENGTH(fd.filedata), filedata, fd.filedataidFROM #{DB_PREFIX}attachment aLEFT JOIN #{DB_PREFIX}filedata fd ON fd.filedataid = a.filedataidLEFT JOIN #{DB_PREFIX}node n ON n.nodeid = a.nodeid@@ -612,9 +621,9 @@ class BulkImport::VBulletin5 < BulkImport::Baseuser_id = row[3]db_filename = row[2]- filename = File.join(ATTACH_DIR, user_id.to_s.split('').join('/'), "#{attachment_id}.attach")+ filename = File.join(ATTACH_DIR, user_id.to_s.split("").join("/"), "#{attachment_id}.attach")real_filename = db_filename- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."unless File.exist?(filename)filename = check_database_for_attachment(row) if filename.blank?@@ -637,7 +646,7 @@ class BulkImport::VBulletin5 < BulkImport::Baseenddef import_attachments- puts '', 'importing attachments...'+ puts "", "importing attachments..."# add extensions to authorized setting#ext = mysql_query("SELECT GROUP_CONCAT(DISTINCT(extension)) exts FROM #{DB_PREFIX}filedata").first[0].split(',')@@ -655,8 +664,8 @@ class BulkImport::VBulletin5 < BulkImport::Base# new style matches the nodeid in the attach table# old style matches the filedataid in attach/filedata tables# if the site is very old, there may be multiple different attachment syntaxes used in posts- attachment_regex = /\[attach[^\]]*\].*\"data-attachmentid\":"?(\d+)"?,?.*\[\/attach\]/i- attachment_regex_oldstyle = /\[attach[^\]]*\](\d+)\[\/attach\]/i+ attachment_regex = %r{\[attach[^\]]*\].*\"data-attachmentid\":"?(\d+)"?,?.*\[/attach\]}i+ attachment_regex_oldstyle = %r{\[attach[^\]]*\](\d+)\[/attach\]}iPost.find_each do |post|current_count += 1@@ -715,9 +724,18 @@ class BulkImport::VBulletin5 < BulkImport::Basedef parse_birthday(birthday)return if birthday.blank?- date_of_birth = Date.strptime(birthday.gsub(/[^\d-]+/, ""), "%m-%d-%Y") rescue nil+ date_of_birth =+ begin+ Date.strptime(birthday.gsub(/[^\d-]+/, ""), "%m-%d-%Y")+ rescue StandardError+ nil+ endreturn if date_of_birth.nil?- date_of_birth.year < 1904 ? Date.new(1904, date_of_birth.month, date_of_birth.day) : date_of_birth+ if date_of_birth.year < 1904+ Date.new(1904, date_of_birth.month, date_of_birth.day)+ else+ date_of_birth+ endenddef preprocess_raw(raw)@@ -726,33 +744,37 @@ class BulkImport::VBulletin5 < BulkImport::Baseraw = raw.dup# [PLAINTEXT]...[/PLAINTEXT]- raw.gsub!(/\[\/?PLAINTEXT\]/i, "\n\n```\n\n")+ raw.gsub!(%r{\[/?PLAINTEXT\]}i, "\n\n```\n\n")# [FONT=font]...[/FONT]raw.gsub!(/\[FONT=\w*\]/im, "")- raw.gsub!(/\[\/FONT\]/im, "")+ raw.gsub!(%r{\[/FONT\]}im, "")# @[URL=<user_profile>]<username>[/URL]# [USER=id]username[/USER]# [MENTION=id]username[/MENTION]- raw.gsub!(/@\[URL=\"\S+\"\]([\w\s]+)\[\/URL\]/i) { "@#{$1.gsub(" ", "_")}" }- raw.gsub!(/\[USER=\"\d+\"\]([\S]+)\[\/USER\]/i) { "@#{$1.gsub(" ", "_")}" }- raw.gsub!(/\[MENTION=\d+\]([\S]+)\[\/MENTION\]/i) { "@#{$1.gsub(" ", "_")}" }+ raw.gsub!(%r{@\[URL=\"\S+\"\]([\w\s]+)\[/URL\]}i) { "@#{$1.gsub(" ", "_")}" }+ raw.gsub!(%r{\[USER=\"\d+\"\]([\S]+)\[/USER\]}i) { "@#{$1.gsub(" ", "_")}" }+ raw.gsub!(%r{\[MENTION=\d+\]([\S]+)\[/MENTION\]}i) { "@#{$1.gsub(" ", "_")}" }# [IMG2=JSON]{..."src":"<url>"}[/IMG2]- raw.gsub!(/\[img2[^\]]*\].*\"src\":\"?([\w\\\/:\.\-;%]*)\"?}.*\[\/img2\]/i) { "\n#{CGI::unescape($1)}\n" }+ raw.gsub!(/\[img2[^\]]*\].*\"src\":\"?([\w\\\/:\.\-;%]*)\"?}.*\[\/img2\]/i) do+ "\n#{CGI.unescape($1)}\n"+ end# [TABLE]...[/TABLE]raw.gsub!(/\[TABLE=\\"[\w:\-\s,]+\\"\]/i, "")- raw.gsub!(/\[\/TABLE\]/i, "")+ raw.gsub!(%r{\[/TABLE\]}i, "")# [HR]...[/HR]- raw.gsub(/\[HR\]\s*\[\/HR\]/im, "---")+ raw.gsub(%r{\[HR\]\s*\[/HR\]}im, "---")# [VIDEO=youtube_share;<id>]...[/VIDEO]# [VIDEO=vimeo;<id>]...[/VIDEO]- raw.gsub!(/\[VIDEO=YOUTUBE_SHARE;([^\]]+)\].*?\[\/VIDEO\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }- raw.gsub!(/\[VIDEO=VIMEO;([^\]]+)\].*?\[\/VIDEO\]/i) { "\nhttps://vimeo.com/#{$1}\n" }+ raw.gsub!(%r{\[VIDEO=YOUTUBE_SHARE;([^\]]+)\].*?\[/VIDEO\]}i) do+ "\nhttps://www.youtube.com/watch?v=#{$1}\n"+ end+ raw.gsub!(%r{\[VIDEO=VIMEO;([^\]]+)\].*?\[/VIDEO\]}i) { "\nhttps://vimeo.com/#{$1}\n" }rawend@@ -760,9 +782,9 @@ class BulkImport::VBulletin5 < BulkImport::Basedef print_status(current, max, start_time = nil)if start_time.present?elapsed_seconds = Time.now - start_time- elements_per_minute = '[%.0f items/min] ' % [current / elapsed_seconds.to_f * 60]+ elements_per_minute = "[%.0f items/min] " % [current / elapsed_seconds.to_f * 60]else- elements_per_minute = ''+ elements_per_minute = ""endprint "\r%9d / %d (%5.1f%%) %s" % [current, max, current / max.to_f * 100, elements_per_minute]@@ -775,7 +797,6 @@ class BulkImport::VBulletin5 < BulkImport::Basedef mysql_query(sql)@client.query(sql)end-endBulkImport::VBulletin5.new.rundiff --git a/script/check_forking.rb b/script/check_forking.rbindex ae8196af943..8679e6ec25e 100644--- a/script/check_forking.rb+++ b/script/check_forking.rb@@ -13,20 +13,22 @@ endDiscourse.after_forkpretty-child = fork do- Discourse.after_fork- pretty- grand_child = fork do+child =+ fork doDiscourse.after_forkpretty- puts "try to exit"+ grand_child =+ fork do+ Discourse.after_fork+ pretty+ puts "try to exit"+ Process.kill "KILL", Process.pid+ end+ puts "before wait 2"+ Process.wait grand_child+ puts "after wait 2"Process.kill "KILL", Process.pidend- puts "before wait 2"- Process.wait grand_child- puts "after wait 2"- Process.kill "KILL", Process.pid-endputs "before wait 1"Process.wait childdiff --git a/script/db_timestamps_mover.rb b/script/db_timestamps_mover.rbindex 30701dd1f6f..248f1893871 100644--- a/script/db_timestamps_mover.rb+++ b/script/db_timestamps_mover.rb@@ -12,20 +12,18 @@ class TimestampsUpdaterdef initialize(schema, ignore_tables)@schema = schema@ignore_tables = ignore_tables- @raw_connection = PG.connect(- host: ENV['DISCOURSE_DB_HOST'] || 'localhost',- port: ENV['DISCOURSE_DB_PORT'] || 5432,- dbname: ENV['DISCOURSE_DB_NAME'] || 'discourse_development',- user: ENV['DISCOURSE_DB_USERNAME'] || 'postgres',- password: ENV['DISCOURSE_DB_PASSWORD'] || '')+ @raw_connection =+ PG.connect(+ host: ENV["DISCOURSE_DB_HOST"] || "localhost",+ port: ENV["DISCOURSE_DB_PORT"] || 5432,+ dbname: ENV["DISCOURSE_DB_NAME"] || "discourse_development",+ user: ENV["DISCOURSE_DB_USERNAME"] || "postgres",+ password: ENV["DISCOURSE_DB_PASSWORD"] || "",+ )enddef move_by(days)- postgresql_date_types = [- "timestamp without time zone",- "timestamp with time zone",- "date"- ]+ postgresql_date_types = ["timestamp without time zone", "timestamp with time zone", "date"]postgresql_date_types.each do |data_type|columns = all_columns_of_type(data_type)@@ -118,11 +116,19 @@ class TimestampsUpdaterenddef is_i?(string)- true if Integer(string) rescue false+ begin+ true if Integer(string)+ rescue StandardError+ false+ endenddef is_date?(string)- true if Date.parse(string) rescue false+ begin+ true if Date.parse(string)+ rescue StandardError+ false+ endenddef create_updaterdiff --git a/script/diff_heaps.rb b/script/diff_heaps.rbindex 5a0e91efd67..8433773d7f5 100644--- a/script/diff_heaps.rb+++ b/script/diff_heaps.rb@@ -6,8 +6,8 @@# rbtrace -p 15193 -e 'Thread.new{require "objspace"; ObjectSpace.trace_object_allocations_start; GC.start(full_mark: true); ObjectSpace.dump_all(output: File.open("heap.json","w"))}.join'##-require 'set'-require 'json'+require "set"+require "json"if ARGV.length != 2puts "Usage: diff_heaps [ORIG.json] [AFTER.json]"@@ -16,26 +16,26 @@ endorigs = Set.new-File.open(ARGV[0], "r").each_line do |line|- parsed = JSON.parse(line)- origs << parsed["address"] if parsed && parsed["address"]-end+File+ .open(ARGV[0], "r")+ .each_line do |line|+ parsed = JSON.parse(line)+ origs << parsed["address"] if parsed && parsed["address"]+ enddiff = []-File.open(ARGV[1], "r").each_line do |line|- parsed = JSON.parse(line)- if parsed && parsed["address"]- diff << parsed unless origs.include? parsed["address"]+File+ .open(ARGV[1], "r")+ .each_line do |line|+ parsed = JSON.parse(line)+ if parsed && parsed["address"]+ diff << parsed unless origs.include? parsed["address"]+ endend-end-diff.group_by do |x|- [x["type"], x["file"], x["line"]]-end.map { |x, y|- [x, y.count]-}.sort { |a, b|- b[1] <=> a[1]-}.each { |x, y|- puts "Leaked #{y} #{x[0]} objects at: #{x[1]}:#{x[2]}"-}+diff+ .group_by { |x| [x["type"], x["file"], x["line"]] }+ .map { |x, y| [x, y.count] }+ .sort { |a, b| b[1] <=> a[1] }+ .each { |x, y| puts "Leaked #{y} #{x[0]} objects at: #{x[1]}:#{x[2]}" }diff --git a/script/docker_test.rb b/script/docker_test.rbindex db73d531be4..d51b63b5c57 100644--- a/script/docker_test.rb+++ b/script/docker_test.rb@@ -19,11 +19,11 @@ def run_or_fail(command)exit 1 unless $?.exitstatus == 0end-unless ENV['NO_UPDATE']+unless ENV["NO_UPDATE"]run_or_fail("git reset --hard")run_or_fail("git fetch")- checkout = ENV['COMMIT_HASH'] || "FETCH_HEAD"+ checkout = ENV["COMMIT_HASH"] || "FETCH_HEAD"run_or_fail("LEFTHOOK=0 git checkout #{checkout}")run_or_fail("bundle")@@ -31,7 +31,7 @@ endlog("Running tests")-if ENV['RUN_SMOKE_TESTS']+if ENV["RUN_SMOKE_TESTS"]run_or_fail("bundle exec rake smoke:test")elserun_or_fail("bundle exec rake docker:test")diff --git a/script/i18n_lint.rb b/script/i18n_lint.rbindex b00de751916..f3f96abf87d 100755--- a/script/i18n_lint.rb+++ b/script/i18n_lint.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require 'colored2'-require 'psych'+require "colored2"+require "psych"class I18nLinterdef initialize(filenames_or_patterns)@@ -27,16 +27,22 @@ endclass LocaleFileValidatorERROR_MESSAGES = {- invalid_relative_links: "The following keys have relative links, but do not start with %{base_url} or %{base_path}:",- invalid_relative_image_sources: "The following keys have relative image sources, but do not start with %{base_url} or %{base_path}:",- invalid_interpolation_key_format: "The following keys use {{key}} instead of %{key} for interpolation keys:",- wrong_pluralization_keys: "Pluralized strings must have only the sub-keys 'one' and 'other'.\nThe following keys have missing or additional keys:",- invalid_one_keys: "The following keys contain the number 1 instead of the interpolation key %{count}:",- invalid_message_format_one_key: "The following keys use 'one {1 foo}' instead of the generic 'one {# foo}':",+ invalid_relative_links:+ "The following keys have relative links, but do not start with %{base_url} or %{base_path}:",+ invalid_relative_image_sources:+ "The following keys have relative image sources, but do not start with %{base_url} or %{base_path}:",+ invalid_interpolation_key_format:+ "The following keys use {{key}} instead of %{key} for interpolation keys:",+ wrong_pluralization_keys:+ "Pluralized strings must have only the sub-keys 'one' and 'other'.\nThe following keys have missing or additional keys:",+ invalid_one_keys:+ "The following keys contain the number 1 instead of the interpolation key %{count}:",+ invalid_message_format_one_key:+ "The following keys use 'one {1 foo}' instead of the generic 'one {# foo}':",}- PLURALIZATION_KEYS = ['zero', 'one', 'two', 'few', 'many', 'other']- ENGLISH_KEYS = ['one', 'other']+ PLURALIZATION_KEYS = %w[zero one two few many other]+ ENGLISH_KEYS = %w[one other]def initialize(filename)@filename = filename@@ -66,7 +72,7 @@ class LocaleFileValidatorprivate- def each_translation(hash, parent_key = '', &block)+ def each_translation(hash, parent_key = "", &block)hash.each do |key, value|current_key = parent_key.empty? ? key : "#{parent_key}.#{key}"@@ -85,13 +91,9 @@ class LocaleFileValidator@errors[:invalid_message_format_one_key] = []each_translation(yaml) do |key, value|- if value.match?(/href\s*=\s*["']\/[^\/]|\]\(\/[^\/]/i)- @errors[:invalid_relative_links] << key- end+ @errors[:invalid_relative_links] << key if value.match?(%r{href\s*=\s*["']/[^/]|\]\(/[^/]}i)- if value.match?(/src\s*=\s*["']\/[^\/]/i)- @errors[:invalid_relative_image_sources] << key- end+ @errors[:invalid_relative_image_sources] << key if value.match?(%r{src\s*=\s*["']/[^/]}i)if value.match?(/{{.+?}}/) && !key.end_with?("_MF")@errors[:invalid_interpolation_key_format] << key@@ -103,7 +105,7 @@ class LocaleFileValidatorendend- def each_pluralization(hash, parent_key = '', &block)+ def each_pluralization(hash, parent_key = "", &block)hash.each do |key, value|if Hash === valuecurrent_key = parent_key.empty? ? key : "#{parent_key}.#{key}"@@ -124,8 +126,8 @@ class LocaleFileValidator@errors[:wrong_pluralization_keys] << key if hash.keys.sort != ENGLISH_KEYS- one_value = hash['one']- if one_value && one_value.include?('1') && !one_value.match?(/%{count}|{{count}}/)+ one_value = hash["one"]+ if one_value && one_value.include?("1") && !one_value.match?(/%{count}|{{count}}/)@errors[:invalid_one_keys] << keyendenddiff --git a/script/import_scripts/answerbase.rb b/script/import_scripts/answerbase.rbindex 1f436ac0ba3..63de1d4a937 100644--- a/script/import_scripts/answerbase.rb+++ b/script/import_scripts/answerbase.rb@@ -1,9 +1,9 @@# frozen_string_literal: true-require 'csv'-require 'reverse_markdown'-require_relative 'base'-require_relative 'base/generic_database'+require "csv"+require "reverse_markdown"+require_relative "base"+require_relative "base/generic_database"# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/answerbase.rb DIRNAME@@ -15,8 +15,10 @@ class ImportScripts::Answerbase < ImportScripts::BaseANSWER_IMAGE_DIRECTORY = "Answer Images"QUESTION_ATTACHMENT_DIRECTORY = "Question Attachments"QUESTION_IMAGE_DIRECTORY = "Question Images"- EMBEDDED_IMAGE_REGEX = /<a[^>]*href="[^"]*relativeUrl=(?<path>[^"\&]*)[^"]*"[^>]*>\s*<img[^>]*>\s*<\/a>/i- QUESTION_LINK_REGEX = /<a[^>]*?href="#{Regexp.escape(OLD_DOMAIN)}\/[^"]*?(?:q|questionid=)(?<id>\d+)[^"]*?"[^>]*>(?<text>.*?)<\/a>/i+ EMBEDDED_IMAGE_REGEX =+ %r{<a[^>]*href="[^"]*relativeUrl=(?<path>[^"\&]*)[^"]*"[^>]*>\s*<img[^>]*>\s*</a>}i+ QUESTION_LINK_REGEX =+ %r{<a[^>]*?href="#{Regexp.escape(OLD_DOMAIN)}/[^"]*?(?:q|questionid=)(?<id>\d+)[^"]*?"[^>]*>(?<text>.*?)</a>}iTOPIC_LINK_NORMALIZATION = '/.*?-(q\d+).*/\1'BATCH_SIZE = 1000@@ -24,12 +26,13 @@ class ImportScripts::Answerbase < ImportScripts::Basesuper()@path = path- @db = ImportScripts::GenericDatabase.new(- @path,- batch_size: BATCH_SIZE,- recreate: true,- numeric_keys: true- )+ @db =+ ImportScripts::GenericDatabase.new(+ @path,+ batch_size: BATCH_SIZE,+ recreate: true,+ numeric_keys: true,+ )enddef execute@@ -47,11 +50,7 @@ class ImportScripts::Answerbase < ImportScripts::Basecategory_position = 0csv_parse("categories") do |row|- @db.insert_category(- id: row[:id],- name: row[:name],- position: category_position += 1- )+ @db.insert_category(id: row[:id], name: row[:name], position: category_position += 1)endcsv_parse("users") do |row|@@ -62,7 +61,7 @@ class ImportScripts::Answerbase < ImportScripts::Basebio: row[:description],avatar_path: row[:profile_image],created_at: parse_date(row[:createtime]),- active: true+ active: true,)end@@ -74,8 +73,9 @@ class ImportScripts::Answerbase < ImportScripts::Basebeginif row[:type] == "Question"- attachments = parse_filenames(row[:attachments], QUESTION_ATTACHMENT_DIRECTORY) +- parse_filenames(row[:images], QUESTION_IMAGE_DIRECTORY)+ attachments =+ parse_filenames(row[:attachments], QUESTION_ATTACHMENT_DIRECTORY) ++ parse_filenames(row[:images], QUESTION_IMAGE_DIRECTORY)@db.insert_topic(id: row[:id],@@ -84,12 +84,13 @@ class ImportScripts::Answerbase < ImportScripts::Basecategory_id: row[:categorylist],user_id: user_id,created_at: created_at,- attachments: attachments+ attachments: attachments,)last_topic_id = row[:id]else- attachments = parse_filenames(row[:attachments], ANSWER_ATTACHMENT_DIRECTORY) +- parse_filenames(row[:images], ANSWER_IMAGE_DIRECTORY)+ attachments =+ parse_filenames(row[:attachments], ANSWER_ATTACHMENT_DIRECTORY) ++ parse_filenames(row[:images], ANSWER_IMAGE_DIRECTORY)@db.insert_post(id: row[:id],@@ -97,10 +98,10 @@ class ImportScripts::Answerbase < ImportScripts::Basetopic_id: last_topic_id,user_id: user_id,created_at: created_at,- attachments: attachments+ attachments: attachments,)end- rescue+ rescue StandardErrorp rowraiseend@@ -110,9 +111,7 @@ class ImportScripts::Answerbase < ImportScripts::Basedef parse_filenames(text, directory)return [] if text.blank?- text- .split(';')- .map { |filename| File.join(@path, directory, filename.strip) }+ text.split(";").map { |filename| File.join(@path, directory, filename.strip) }enddef parse_date(text)@@ -132,10 +131,10 @@ class ImportScripts::Answerbase < ImportScripts::Basecreate_categories(rows) do |row|{- id: row['id'],- name: row['name'],- description: row['description'],- position: row['position']+ id: row["id"],+ name: row["name"],+ description: row["description"],+ position: row["position"],}endend@@ -153,19 +152,17 @@ class ImportScripts::Answerbase < ImportScripts::Baserows, last_id = @db.fetch_users(last_id)break if rows.empty?- next if all_records_exist?(:users, rows.map { |row| row['id'] })+ next if all_records_exist?(:users, rows.map { |row| row["id"] })create_users(rows, total: total_count, offset: offset) do |row|{- id: row['id'],- email: row['email'],- username: row['username'],- bio_raw: row['bio'],- created_at: row['created_at'],- active: row['active'] == 1,- post_create_action: proc do |user|- create_avatar(user, row['avatar_path'])- end+ id: row["id"],+ email: row["email"],+ username: row["username"],+ bio_raw: row["bio"],+ created_at: row["created_at"],+ active: row["active"] == 1,+ post_create_action: proc { |user| create_avatar(user, row["avatar_path"]) },}endend@@ -191,24 +188,25 @@ class ImportScripts::Answerbase < ImportScripts::Baserows, last_id = @db.fetch_topics(last_id)break if rows.empty?- next if all_records_exist?(:posts, rows.map { |row| row['id'] })+ next if all_records_exist?(:posts, rows.map { |row| row["id"] })create_posts(rows, total: total_count, offset: offset) do |row|- attachments = @db.fetch_topic_attachments(row['id']) if row['upload_count'] > 0- user_id = user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id+ attachments = @db.fetch_topic_attachments(row["id"]) if row["upload_count"] > 0+ user_id = user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id{- id: row['id'],- title: row['title'],- raw: raw_with_attachments(row['raw'].presence || row['title'], attachments, user_id),- category: category_id_from_imported_category_id(row['category_id']),+ id: row["id"],+ title: row["title"],+ raw: raw_with_attachments(row["raw"].presence || row["title"], attachments, user_id),+ category: category_id_from_imported_category_id(row["category_id"]),user_id: user_id,- created_at: row['created_at'],- closed: row['closed'] == 1,- post_create_action: proc do |post|- url = "q#{row['id']}"- Permalink.create(url: url, topic_id: post.topic.id) unless permalink_exists?(url)- end+ created_at: row["created_at"],+ closed: row["closed"] == 1,+ post_create_action:+ proc do |post|+ url = "q#{row["id"]}"+ Permalink.create(url: url, topic_id: post.topic.id) unless permalink_exists?(url)+ end,}endend@@ -223,19 +221,19 @@ class ImportScripts::Answerbase < ImportScripts::Baserows, last_row_id = @db.fetch_posts(last_row_id)break if rows.empty?- next if all_records_exist?(:posts, rows.map { |row| row['id'] })+ next if all_records_exist?(:posts, rows.map { |row| row["id"] })create_posts(rows, total: total_count, offset: offset) do |row|- topic = topic_lookup_from_imported_post_id(row['topic_id'])- attachments = @db.fetch_post_attachments(row['id']) if row['upload_count'] > 0- user_id = user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id+ topic = topic_lookup_from_imported_post_id(row["topic_id"])+ attachments = @db.fetch_post_attachments(row["id"]) if row["upload_count"] > 0+ user_id = user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id{- id: row['id'],- raw: raw_with_attachments(row['raw'], attachments, user_id),+ id: row["id"],+ raw: raw_with_attachments(row["raw"], attachments, user_id),user_id: user_id,topic_id: topic[:topic_id],- created_at: row['created_at']+ created_at: row["created_at"],}endend@@ -247,7 +245,7 @@ class ImportScripts::Answerbase < ImportScripts::Baseraw = ReverseMarkdown.convert(raw) || ""attachments&.each do |attachment|- path = attachment['path']+ path = attachment["path"]next if embedded_paths.include?(path)if File.exist?(path)@@ -269,23 +267,24 @@ class ImportScripts::Answerbase < ImportScripts::Basepaths = []upload_ids = []- raw = raw.gsub(EMBEDDED_IMAGE_REGEX) do- path = File.join(@path, Regexp.last_match['path'])- filename = File.basename(path)- path = find_image_path(filename)+ raw =+ raw.gsub(EMBEDDED_IMAGE_REGEX) do+ path = File.join(@path, Regexp.last_match["path"])+ filename = File.basename(path)+ path = find_image_path(filename)- if path- upload = @uploader.create_upload(user_id, path, filename)+ if path+ upload = @uploader.create_upload(user_id, path, filename)- if upload.present? && upload.persisted?- paths << path- upload_ids << upload.id- @uploader.html_for_upload(upload, filename)+ if upload.present? && upload.persisted?+ paths << path+ upload_ids << upload.id+ @uploader.html_for_upload(upload, filename)+ end+ else+ STDERR.puts "Could not find file: #{path}"end- else- STDERR.puts "Could not find file: #{path}"end- end[raw, paths, upload_ids]end@@ -311,11 +310,11 @@ class ImportScripts::Answerbase < ImportScripts::Basedef add_permalink_normalizationsnormalizations = SiteSetting.permalink_normalizations- normalizations = normalizations.blank? ? [] : normalizations.split('|')+ normalizations = normalizations.blank? ? [] : normalizations.split("|")add_normalization(normalizations, TOPIC_LINK_NORMALIZATION)- SiteSetting.permalink_normalizations = normalizations.join('|')+ SiteSetting.permalink_normalizations = normalizations.join("|")enddef add_normalization(normalizations, normalization)@@ -327,11 +326,13 @@ class ImportScripts::Answerbase < ImportScripts::Baseenddef csv_parse(table_name)- CSV.foreach(File.join(@path, "#{table_name}.csv"),- headers: true,- header_converters: :symbol,- skip_blanks: true,- encoding: 'bom|utf-8') { |row| yield row }+ CSV.foreach(+ File.join(@path, "#{table_name}.csv"),+ headers: true,+ header_converters: :symbol,+ skip_blanks: true,+ encoding: "bom|utf-8",+ ) { |row| yield row }endenddiff --git a/script/import_scripts/answerhub.rb b/script/import_scripts/answerhub.rbindex f2e05811bac..b4954dcccba 100644--- a/script/import_scripts/answerhub.rb+++ b/script/import_scripts/answerhub.rb@@ -5,34 +5,29 @@# Based on having access to a mysql dump.# Pass in the ENV variables listed below before running the script.-require_relative 'base'-require 'mysql2'-require 'open-uri'+require_relative "base"+require "mysql2"+require "open-uri"class ImportScripts::AnswerHub < ImportScripts::Base-- DB_NAME ||= ENV['DB_NAME'] || "answerhub"- DB_PASS ||= ENV['DB_PASS'] || "answerhub"- DB_USER ||= ENV['DB_USER'] || "answerhub"- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "network1"- BATCH_SIZE ||= ENV['BATCH_SIZE'].to_i || 1000- ATTACHMENT_DIR = ENV['ATTACHMENT_DIR'] || ''- PROCESS_UPLOADS = ENV['PROCESS_UPLOADS'].to_i || 0- ANSWERHUB_DOMAIN = ENV['ANSWERHUB_DOMAIN']- AVATAR_DIR = ENV['AVATAR_DIR'] || ""- SITE_ID = ENV['SITE_ID'].to_i || 0- CATEGORY_MAP_FROM = ENV['CATEGORY_MAP_FROM'].to_i || 0- CATEGORY_MAP_TO = ENV['CATEGORY_MAP_TO'].to_i || 0- SCRAPE_AVATARS = ENV['SCRAPE_AVATARS'].to_i || 0+ DB_NAME ||= ENV["DB_NAME"] || "answerhub"+ DB_PASS ||= ENV["DB_PASS"] || "answerhub"+ DB_USER ||= ENV["DB_USER"] || "answerhub"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "network1"+ BATCH_SIZE ||= ENV["BATCH_SIZE"].to_i || 1000+ ATTACHMENT_DIR = ENV["ATTACHMENT_DIR"] || ""+ PROCESS_UPLOADS = ENV["PROCESS_UPLOADS"].to_i || 0+ ANSWERHUB_DOMAIN = ENV["ANSWERHUB_DOMAIN"]+ AVATAR_DIR = ENV["AVATAR_DIR"] || ""+ SITE_ID = ENV["SITE_ID"].to_i || 0+ CATEGORY_MAP_FROM = ENV["CATEGORY_MAP_FROM"].to_i || 0+ CATEGORY_MAP_TO = ENV["CATEGORY_MAP_TO"].to_i || 0+ SCRAPE_AVATARS = ENV["SCRAPE_AVATARS"].to_i || 0def initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: DB_USER,- password: DB_PASS,- database: DB_NAME- )+ @client =+ Mysql2::Client.new(host: "localhost", username: DB_USER, password: DB_PASS, database: DB_NAME)@skip_updates = trueSiteSetting.tagging_enabled = trueSiteSetting.max_tags_per_topic = 10@@ -56,7 +51,7 @@ class ImportScripts::AnswerHub < ImportScripts::Baseenddef import_users- puts '', "creating users"+ puts "", "creating users"query ="SELECT count(*) count@@ -64,12 +59,13 @@ class ImportScripts::AnswerHub < ImportScripts::BaseWHERE c_type = 'user'AND c_active = 1AND c_system <> 1;"- total_count = @client.query(query).first['count']+ total_count = @client.query(query).first["count"]puts "Total count: #{total_count}"@last_user_id = -1batches(BATCH_SIZE) do |offset|- query = "SELECT c_id, c_creation_date, c_name, c_primaryEmail, c_last_seen, c_description+ query =+ "SELECT c_id, c_creation_date, c_name, c_primaryEmail, c_last_seen, c_descriptionFROM #{TABLE_PREFIX}_authoritablesWHERE c_type = 'user'AND c_active = 1@@ -79,17 +75,18 @@ class ImportScripts::AnswerHub < ImportScripts::Baseresults = @client.query(query)break if results.size < 1- @last_user_id = results.to_a.last['c_id']+ @last_user_id = results.to_a.last["c_id"]create_users(results, total: total_count, offset: offset) do |user|# puts user['c_id'].to_s + ' ' + user['c_name']- next if @lookup.user_id_from_imported_user_id(user['c_id'])- { id: user['c_id'],+ next if @lookup.user_id_from_imported_user_id(user["c_id"])+ {+ id: user["c_id"],email: "#{SecureRandom.hex}@invalid.invalid",- username: user['c_name'],- created_at: user['c_creation_date'],- bio_raw: user['c_description'],- last_seen_at: user['c_last_seen'],+ username: user["c_name"],+ created_at: user["c_creation_date"],+ bio_raw: user["c_description"],+ last_seen_at: user["c_last_seen"],}endend@@ -99,7 +96,8 @@ class ImportScripts::AnswerHub < ImportScripts::Baseputs "", "importing categories..."# Import parent categories first- query = "SELECT c_id, c_name, c_plug, c_parent+ query =+ "SELECT c_id, c_name, c_plug, c_parentFROM containersWHERE c_type = 'space'AND c_active = 1@@ -107,15 +105,12 @@ class ImportScripts::AnswerHub < ImportScripts::Baseresults = @client.query(query)create_categories(results) do |c|- {- id: c['c_id'],- name: c['c_name'],- parent_category_id: check_parent_id(c['c_parent']),- }+ { id: c["c_id"], name: c["c_name"], parent_category_id: check_parent_id(c["c_parent"]) }end# Import sub-categories- query = "SELECT c_id, c_name, c_plug, c_parent+ query =+ "SELECT c_id, c_name, c_plug, c_parentFROM containersWHERE c_type = 'space'AND c_active = 1@@ -125,9 +120,9 @@ class ImportScripts::AnswerHub < ImportScripts::Basecreate_categories(results) do |c|# puts c.inspect{- id: c['c_id'],- name: c['c_name'],- parent_category_id: category_id_from_imported_category_id(check_parent_id(c['c_parent'])),+ id: c["c_id"],+ name: c["c_name"],+ parent_category_id: category_id_from_imported_category_id(check_parent_id(c["c_parent"])),}endend@@ -141,7 +136,7 @@ class ImportScripts::AnswerHub < ImportScripts::BaseWHERE c_visibility <> 'deleted'AND (c_type = 'question'OR c_type = 'kbentry');"- total_count = @client.query(count_query).first['count']+ total_count = @client.query(count_query).first["count"]@last_topic_id = -1@@ -159,26 +154,25 @@ class ImportScripts::AnswerHub < ImportScripts::Basetopics = @client.query(query)break if topics.size < 1- @last_topic_id = topics.to_a.last['c_id']+ @last_topic_id = topics.to_a.last["c_id"]create_posts(topics, total: total_count, offset: offset) do |t|- user_id = user_id_from_imported_user_id(t['c_author']) || Discourse::SYSTEM_USER_ID- body = process_mentions(t['c_body'])- if PROCESS_UPLOADS == 1- body = process_uploads(body, user_id)- end+ user_id = user_id_from_imported_user_id(t["c_author"]) || Discourse::SYSTEM_USER_ID+ body = process_mentions(t["c_body"])+ body = process_uploads(body, user_id) if PROCESS_UPLOADS == 1markdown_body = HtmlToMarkdown.new(body).to_markdown{- id: t['c_id'],+ id: t["c_id"],user_id: user_id,- title: t['c_title'],- category: category_id_from_imported_category_id(t['c_primaryContainer']),+ title: t["c_title"],+ category: category_id_from_imported_category_id(t["c_primaryContainer"]),raw: markdown_body,- created_at: t['c_creation_date'],- post_create_action: proc do |post|- tag_names = t['c_topic_names'].split(',')- DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)- end+ created_at: t["c_creation_date"],+ post_create_action:+ proc do |post|+ tag_names = t["c_topic_names"].split(",")+ DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)+ end,}endend@@ -194,7 +188,7 @@ class ImportScripts::AnswerHub < ImportScripts::BaseAND (c_type = 'answer'OR c_type = 'comment'OR c_type = 'kbentry');"- total_count = @client.query(count_query).first['count']+ total_count = @client.query(count_query).first["count"]@last_post_id = -1@@ -210,49 +204,49 @@ class ImportScripts::AnswerHub < ImportScripts::BaseORDER BY c_id ASCLIMIT #{BATCH_SIZE};"posts = @client.query(query)- next if all_records_exist? :posts, posts.map { |p| p['c_id'] }+ next if all_records_exist? :posts, posts.map { |p| p["c_id"] }break if posts.size < 1- @last_post_id = posts.to_a.last['c_id']+ @last_post_id = posts.to_a.last["c_id"]create_posts(posts, total: total_count, offset: offset) do |p|- t = topic_lookup_from_imported_post_id(p['c_originalParent'])+ t = topic_lookup_from_imported_post_id(p["c_originalParent"])next unless t- reply_to_post_id = post_id_from_imported_post_id(p['c_parent'])+ reply_to_post_id = post_id_from_imported_post_id(p["c_parent"])reply_to_post = reply_to_post_id.present? ? Post.find(reply_to_post_id) : nilreply_to_post_number = reply_to_post.present? ? reply_to_post.post_number : nil- user_id = user_id_from_imported_user_id(p['c_author']) || Discourse::SYSTEM_USER_ID+ user_id = user_id_from_imported_user_id(p["c_author"]) || Discourse::SYSTEM_USER_ID- body = process_mentions(p['c_body'])- if PROCESS_UPLOADS == 1- body = process_uploads(body, user_id)- end+ body = process_mentions(p["c_body"])+ body = process_uploads(body, user_id) if PROCESS_UPLOADS == 1markdown_body = HtmlToMarkdown.new(body).to_markdown{- id: p['c_id'],+ id: p["c_id"],user_id: user_id,topic_id: t[:topic_id],reply_to_post_number: reply_to_post_number,raw: markdown_body,- created_at: p['c_creation_date'],- post_create_action: proc do |post_info|- begin- if p['c_type'] == 'answer' && p['c_marked'] == 1- post = Post.find(post_info[:id])- if post- user_id = user_id_from_imported_user_id(p['c_author']) || Discourse::SYSTEM_USER_ID- current_user = User.find(user_id)- solved = DiscourseSolved.accept_answer!(post, current_user)- # puts "SOLVED: #{solved}"+ created_at: p["c_creation_date"],+ post_create_action:+ proc do |post_info|+ begin+ if p["c_type"] == "answer" && p["c_marked"] == 1+ post = Post.find(post_info[:id])+ if post+ user_id =+ user_id_from_imported_user_id(p["c_author"]) || Discourse::SYSTEM_USER_ID+ current_user = User.find(user_id)+ solved = DiscourseSolved.accept_answer!(post, current_user)+ # puts "SOLVED: #{solved}"+ endend+ rescue ActiveRecord::RecordInvalid+ puts "SOLVED: Skipped post_id: #{post.id} because invalid"end- rescue ActiveRecord::RecordInvalid- puts "SOLVED: Skipped post_id: #{post.id} because invalid"- end- end+ end,}endend@@ -269,11 +263,7 @@ class ImportScripts::AnswerHub < ImportScripts::Basegroups = @client.query(query)create_groups(groups) do |group|- {- id: group["c_id"],- name: group["c_name"],- visibility_level: 1- }+ { id: group["c_id"], name: group["c_name"], visibility_level: 1 }endend@@ -298,11 +288,16 @@ class ImportScripts::AnswerHub < ImportScripts::Basegroup_members.mapgroups.each do |group|- dgroup = find_group_by_import_id(group['c_id'])+ dgroup = find_group_by_import_id(group["c_id"])- next if dgroup.custom_fields['import_users_added']+ next if dgroup.custom_fields["import_users_added"]- group_member_ids = group_members.map { |m| user_id_from_imported_user_id(m["c_members"]) if m["c_groups"] == group['c_id'] }.compact+ group_member_ids =+ group_members+ .map do |m|+ user_id_from_imported_user_id(m["c_members"]) if m["c_groups"] == group["c_id"]+ end+ .compact# add membersdgroup.bulk_add(group_member_ids)@@ -310,7 +305,7 @@ class ImportScripts::AnswerHub < ImportScripts::Base# reload groupdgroup.reload- dgroup.custom_fields['import_users_added'] = true+ dgroup.custom_fields["import_users_added"] = truedgroup.saveprogress_count += 1@@ -362,7 +357,7 @@ class ImportScripts::AnswerHub < ImportScripts::Baseavatars.each do |a|begin- user_id = user_id_from_imported_user_id(a['c_user'])+ user_id = user_id_from_imported_user_id(a["c_user"])user = User.find(user_id)if userfilename = "avatar-#{user_id}.png"@@ -371,9 +366,11 @@ class ImportScripts::AnswerHub < ImportScripts::Base# Scrape Avatars - Avatars are saved in the db, but it might be easier to just scrape themif SCRAPE_AVATARS == 1- File.open(path, 'wb') { |f|- f << open("https://#{ANSWERHUB_DOMAIN}/forums/users/#{a['c_user']}/photo/view.html?s=240").read- }+ File.open(path, "wb") do |f|+ f << open(+ "https://#{ANSWERHUB_DOMAIN}/forums/users/#{a["c_user"]}/photo/view.html?s=240",+ ).read+ endendupload = @uploader.create_upload(user.id, path, filename)@@ -389,7 +386,7 @@ class ImportScripts::AnswerHub < ImportScripts::Baseendendrescue ActiveRecord::RecordNotFound- puts "Could not find User for user_id: #{a['c_user']}"+ puts "Could not find User for user_id: #{a["c_user"]}"endendend@@ -438,9 +435,10 @@ class ImportScripts::AnswerHub < ImportScripts::Baseraw = body.dup# https://example.forum.com/forums/users/1469/XYZ_Rob.html- raw.gsub!(/(https:\/\/example.forum.com\/forums\/users\/\d+\/[\w_%-.]*.html)/) do+ raw.gsub!(%r{(https://example.forum.com/forums/users/\d+/[\w_%-.]*.html)}) dolegacy_url = $1- import_user_id = legacy_url.match(/https:\/\/example.forum.com\/forums\/users\/(\d+)\/[\w_%-.]*.html/).captures+ import_user_id =+ legacy_url.match(%r{https://example.forum.com/forums/users/(\d+)/[\w_%-.]*.html}).capturesuser = @lookup.find_user_by_import_id(import_user_id[0])if user.present?@@ -453,9 +451,9 @@ class ImportScripts::AnswerHub < ImportScripts::Baseend# /forums/users/395/petrocket.html- raw.gsub!(/(\/forums\/users\/\d+\/[\w_%-.]*.html)/) do+ raw.gsub!(%r{(/forums/users/\d+/[\w_%-.]*.html)}) dolegacy_url = $1- import_user_id = legacy_url.match(/\/forums\/users\/(\d+)\/[\w_%-.]*.html/).captures+ import_user_id = legacy_url.match(%r{/forums/users/(\d+)/[\w_%-.]*.html}).captures# puts rawuser = @lookup.find_user_by_import_id(import_user_id[0])@@ -472,7 +470,7 @@ class ImportScripts::AnswerHub < ImportScripts::Baseenddef create_permalinks- puts '', 'Creating redirects...', ''+ puts "", "Creating redirects...", ""# https://example.forum.com/forums/questions/2005/missing-file.htmlTopic.find_each do |topic|@@ -480,8 +478,12 @@ class ImportScripts::AnswerHub < ImportScripts::Baseif pcf && pcf["import_id"]id = pcf["import_id"]slug = Slug.for(topic.title)- Permalink.create(url: "questions/#{id}/#{slug}.html", topic_id: topic.id) rescue nil- print '.'+ begin+ Permalink.create(url: "questions/#{id}/#{slug}.html", topic_id: topic.id)+ rescue StandardError+ nil+ end+ print "."endendend@@ -496,7 +498,6 @@ class ImportScripts::AnswerHub < ImportScripts::Basereturn CATEGORY_MAP_TO if CATEGORY_MAP_FROM > 0 && id == CATEGORY_MAP_FROMidend-endImportScripts::AnswerHub.new.performdiff --git a/script/import_scripts/askbot.rb b/script/import_scripts/askbot.rbindex 7bc7866a0ef..537c5ba71fe 100644--- a/script/import_scripts/askbot.rb+++ b/script/import_scripts/askbot.rb@@ -1,23 +1,23 @@# frozen_string_literal: truerequire File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'pg'+require "pg"class ImportScripts::MyAskBot < ImportScripts::Base# CHANGE THESE BEFORE RUNNING THE IMPORTERBATCH_SIZE = 1000- OLD_SITE = "ask.cvxr.com"- DB_NAME = "cvxforum"- DB_USER = "cvxforum"- DB_PORT = 5432- DB_HOST = "ask.cvxr.com"- DB_PASS = 'yeah, right'+ OLD_SITE = "ask.cvxr.com"+ DB_NAME = "cvxforum"+ DB_USER = "cvxforum"+ DB_PORT = 5432+ DB_HOST = "ask.cvxr.com"+ DB_PASS = "yeah, right"# A list of categories to create. Any post with one of these tags will be# assigned to that category. Ties are broken by list order.- CATEGORIES = [ 'Nonconvex', 'TFOCS', 'MIDCP', 'FAQ' ]+ CATEGORIES = %w[Nonconvex TFOCS MIDCP FAQ]def initializesuper@@ -25,13 +25,8 @@ class ImportScripts::MyAskBot < ImportScripts::Base@thread_parents = {}@tagmap = []@td = PG::TextDecoder::TimestampWithTimeZone.new- @client = PG.connect(- dbname: DB_NAME,- host: DB_HOST,- port: DB_PORT,- user: DB_USER,- password: DB_PASS- )+ @client =+ PG.connect(dbname: DB_NAME, host: DB_HOST, port: DB_PORT, user: DB_USER, password: DB_PASS)enddef execute@@ -55,18 +50,17 @@ class ImportScripts::MyAskBot < ImportScripts::Basedef read_tagsputs "", "reading thread tags..."- tag_count = @client.exec(<<-SQL+ tag_count = @client.exec(<<-SQL)[0]["count"]SELECT COUNT(A.id)FROM askbot_thread_tags AJOIN tag BON A.tag_id = B.idWHERE A.tag_id > 0SQL- )[0]["count"]tags_done = 0batches(BATCH_SIZE) do |offset|- tags = @client.exec(<<-SQL+ tags = @client.exec(<<-SQL)SELECT A.thread_id, B.nameFROM askbot_thread_tags AJOIN tag B@@ -75,7 +69,6 @@ class ImportScripts::MyAskBot < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )break if tags.ntuples() < 1tags.each do |tag|tid = tag["thread_id"].to_i@@ -83,7 +76,7 @@ class ImportScripts::MyAskBot < ImportScripts::Baseif @tagmap[tid]@tagmap[tid].push(tnm)else- @tagmap[tid] = [ tnm ]+ @tagmap[tid] = [tnm]endtags_done += 1print_status tags_done, tag_count@@ -94,21 +87,19 @@ class ImportScripts::MyAskBot < ImportScripts::Basedef import_usersputs "", "importing users"- total_count = @client.exec(<<-SQL+ total_count = @client.exec(<<-SQL)[0]["count"]SELECT COUNT(id)FROM auth_userSQL- )[0]["count"]batches(BATCH_SIZE) do |offset|- users = @client.query(<<-SQL+ users = @client.query(<<-SQL)SELECT id, username, email, is_staff, date_joined, last_seen, real_name, website, location, aboutFROM auth_userORDER BY date_joinedLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )break if users.ntuples() < 1@@ -133,17 +124,16 @@ class ImportScripts::MyAskBot < ImportScripts::Basedef import_postsputs "", "importing questions..."- post_count = @client.exec(<<-SQL+ post_count = @client.exec(<<-SQL)[0]["count"]SELECT COUNT(A.id)FROM askbot_post AJOIN askbot_thread BON A.thread_id = B.idWHERE NOT B.closed AND A.post_type='question'SQL- )[0]["count"]batches(BATCH_SIZE) do |offset|- posts = @client.exec(<<-SQL+ posts = @client.exec(<<-SQL)SELECT A.id, A.author_id, A.added_at, A.text, A.thread_id, B.titleFROM askbot_post AJOIN askbot_thread B@@ -153,7 +143,6 @@ class ImportScripts::MyAskBot < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )break if posts.ntuples() < 1@@ -176,7 +165,11 @@ class ImportScripts::MyAskBot < ImportScripts::Baseid: pid,title: post["title"],category: cat,- custom_fields: { import_id: pid, import_thread_id: tid, import_tags: tags },+ custom_fields: {+ import_id: pid,+ import_thread_id: tid,+ import_tags: tags,+ },user_id: user_id_from_imported_user_id(post["author_id"]) || Discourse::SYSTEM_USER_ID,created_at: Time.zone.at(@td.decode(post["added_at"])),raw: post["text"],@@ -188,17 +181,16 @@ class ImportScripts::MyAskBot < ImportScripts::Basedef import_repliesputs "", "importing answers and comments..."- post_count = @client.exec(<<-SQL+ post_count = @client.exec(<<-SQL)[0]["count"]SELECT COUNT(A.id)FROM askbot_post AJOIN askbot_thread BON A.thread_id = B.idWHERE NOT B.closed AND A.post_type<>'question'SQL- )[0]["count"]batches(BATCH_SIZE) do |offset|- posts = @client.exec(<<-SQL+ posts = @client.exec(<<-SQL)SELECT A.id, A.author_id, A.added_at, A.text, A.thread_id, B.titleFROM askbot_post AJOIN askbot_thread B@@ -208,7 +200,6 @@ class ImportScripts::MyAskBot < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )break if posts.ntuples() < 1@@ -222,10 +213,12 @@ class ImportScripts::MyAskBot < ImportScripts::Base{id: pid,topic_id: parent[:topic_id],- custom_fields: { import_id: pid },+ custom_fields: {+ import_id: pid,+ },user_id: user_id_from_imported_user_id(post["author_id"]) || Discourse::SYSTEM_USER_ID,created_at: Time.zone.at(@td.decode(post["added_at"])),- raw: post["text"]+ raw: post["text"],}endend@@ -240,32 +233,37 @@ class ImportScripts::MyAskBot < ImportScripts::Base# I am sure this is incomplete, but we didn't make heavy use of internal# links on our site.tmp = Regexp.quote("http://#{OLD_SITE}")- r1 = /"(#{tmp})?\/question\/(\d+)\/[a-zA-Z-]*\/?"/- r2 = /\((#{tmp})?\/question\/(\d+)\/[a-zA-Z-]*\/?\)/- r3 = /<?#tmp\/question\/(\d+)\/[a-zA-Z-]*\/?>?/+ r1 = %r{"(#{tmp})?/question/(\d+)/[a-zA-Z-]*/?"}+ r2 = %r{\((#{tmp})?/question/(\d+)/[a-zA-Z-]*/?\)}+ r3 = %r{<?#tmp/question/(\d+)/[a-zA-Z-]*/?>?}Post.find_each do |post|- raw = post.raw.gsub(r1) do- if topic = topic_lookup_from_imported_post_id($2)- "\"#{topic[:url]}\""- else- $&- end- end- raw = raw.gsub(r2) do- if topic = topic_lookup_from_imported_post_id($2)- "(#{topic[:url]})"- else- $&+ raw =+ post+ .raw+ .gsub(r1) do+ if topic = topic_lookup_from_imported_post_id($2)+ "\"#{topic[:url]}\""+ else+ $&+ end+ end+ raw =+ raw.gsub(r2) do+ if topic = topic_lookup_from_imported_post_id($2)+ "(#{topic[:url]})"+ else+ $&+ endend- end- raw = raw.gsub(r3) do- if topic = topic_lookup_from_imported_post_id($1)- trec = Topic.find_by(id: topic[:topic_id])- "[#{trec.title}](#{topic[:url]})"- else- $&+ raw =+ raw.gsub(r3) do+ if topic = topic_lookup_from_imported_post_id($1)+ trec = Topic.find_by(id: topic[:topic_id])+ "[#{trec.title}](#{topic[:url]})"+ else+ $&+ endend- endif raw != post.rawpost.raw = rawdiff --git a/script/import_scripts/base.rb b/script/import_scripts/base.rbindex 1345f206d78..7dbca7d3532 100644--- a/script/import_scripts/base.rb+++ b/script/import_scripts/base.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-if ARGV.include?('bbcode-to-md')+if ARGV.include?("bbcode-to-md")# Replace (most) bbcode with markdown before creating posts.# This will dramatically clean up the final posts in Discourse.#@@ -10,17 +10,17 @@ if ARGV.include?('bbcode-to-md')# cd ruby-bbcode-to-md# gem build ruby-bbcode-to-md.gemspec# gem install ruby-bbcode-to-md-*.gem- require 'ruby-bbcode-to-md'+ require "ruby-bbcode-to-md"end-require_relative '../../config/environment'-require_relative 'base/lookup_container'-require_relative 'base/uploader'+require_relative "../../config/environment"+require_relative "base/lookup_container"+require_relative "base/uploader"-module ImportScripts; end+module ImportScripts+endclass ImportScripts::Base-def initializepreload_i18n@@ -62,15 +62,14 @@ class ImportScripts::Baseendelapsed = Time.now - @start_times[:import]- puts '', '', 'Done (%02dh %02dmin %02dsec)' % [elapsed / 3600, elapsed / 60 % 60, elapsed % 60]-+ puts "", "", "Done (%02dh %02dmin %02dsec)" % [elapsed / 3600, elapsed / 60 % 60, elapsed % 60]ensurereset_site_settingsenddef get_site_settings_for_import{- blocked_email_domains: '',+ blocked_email_domains: "",min_topic_title_length: 1,min_post_length: 1,min_first_post_length: 1,@@ -78,21 +77,23 @@ class ImportScripts::Basemin_personal_message_title_length: 1,allow_duplicate_topic_titles: true,allow_duplicate_topic_titles_category: false,- disable_emails: 'yes',- max_attachment_size_kb: 102400,- max_image_size_kb: 102400,- authorized_extensions: '*',+ disable_emails: "yes",+ max_attachment_size_kb: 102_400,+ max_image_size_kb: 102_400,+ authorized_extensions: "*",clean_up_inactive_users_after_days: 0,clean_up_unused_staged_users_after_days: 0,clean_up_uploads: false,- clean_orphan_uploads_grace_period_hours: 1800+ clean_orphan_uploads_grace_period_hours: 1800,}enddef change_site_settingsif SiteSetting.bootstrap_mode_enabled- SiteSetting.default_trust_level = TrustLevel[0] if SiteSetting.default_trust_level == TrustLevel[1]- SiteSetting.default_email_digest_frequency = 10080 if SiteSetting.default_email_digest_frequency == 1440+ SiteSetting.default_trust_level = TrustLevel[0] if SiteSetting.default_trust_level ==+ TrustLevel[1]+ SiteSetting.default_email_digest_frequency =+ 10_080 if SiteSetting.default_email_digest_frequency == 1440SiteSetting.bootstrap_mode_enabled = falseend@@ -131,7 +132,7 @@ class ImportScripts::Baseraise NotImplementedErrorend- %i{+ %i[add_categoryadd_groupadd_post@@ -146,9 +147,7 @@ class ImportScripts::Basetopic_lookup_from_imported_post_iduser_already_imported?user_id_from_imported_user_id- }.each do |method_name|- delegate method_name, to: :@lookup- end+ ].each { |method_name| delegate method_name, to: :@lookup }def create_admin(opts = {})admin = User.new@@ -196,7 +195,11 @@ class ImportScripts::Baseendend- print_status(created + skipped + failed + (opts[:offset] || 0), total, get_start_time("groups"))+ print_status(+ created + skipped + failed + (opts[:offset] || 0),+ total,+ get_start_time("groups"),+ )end[created, skipped]@@ -224,23 +227,22 @@ class ImportScripts::BaseActiveRecord::Base.transaction dobeginconnection = ActiveRecord::Base.connection.raw_connection- connection.exec('CREATE TEMP TABLE import_ids(val text PRIMARY KEY)')+ connection.exec("CREATE TEMP TABLE import_ids(val text PRIMARY KEY)")- import_id_clause = import_ids.map { |id| "('#{PG::Connection.escape_string(id.to_s)}')" }.join(",")+ import_id_clause =+ import_ids.map { |id| "('#{PG::Connection.escape_string(id.to_s)}')" }.join(",")connection.exec("INSERT INTO import_ids VALUES #{import_id_clause}")existing = "#{type.to_s.classify}CustomField".constantize- existing = existing.where(name: 'import_id')- .joins('JOIN import_ids ON val = value')- .count+ existing = existing.where(name: "import_id").joins("JOIN import_ids ON val = value").countif existing == import_ids.lengthputs "Skipping #{import_ids.length} already imported #{type}"trueendensure- connection.exec('DROP TABLE import_ids') unless connection.nil?+ connection.exec("DROP TABLE import_ids") unless connection.nil?endendend@@ -292,7 +294,11 @@ class ImportScripts::Baseendend- print_status(created + skipped + failed + (opts[:offset] || 0), total, get_start_time("users"))+ print_status(+ created + skipped + failed + (opts[:offset] || 0),+ total,+ get_start_time("users"),+ )end[created, skipped]@@ -305,7 +311,9 @@ class ImportScripts::Basepost_create_action = opts.delete(:post_create_action)existing = find_existing_user(opts[:email], opts[:username])- return existing if existing && (merge || existing.custom_fields["import_id"].to_s == import_id.to_s)+ if existing && (merge || existing.custom_fields["import_id"].to_s == import_id.to_s)+ return existing+ endbio_raw = opts.delete(:bio_raw)website = opts.delete(:website)@@ -316,8 +324,11 @@ class ImportScripts::Baseoriginal_name = opts[:name]original_email = opts[:email] = opts[:email].downcase- if !UsernameValidator.new(opts[:username]).valid_format? || !User.username_available?(opts[:username])- opts[:username] = UserNameSuggester.suggest(opts[:username].presence || opts[:name].presence || opts[:email])+ if !UsernameValidator.new(opts[:username]).valid_format? ||+ !User.username_available?(opts[:username])+ opts[:username] = UserNameSuggester.suggest(+ opts[:username].presence || opts[:name].presence || opts[:email],+ )endif !EmailAddressValidator.valid_value?(opts[:email])@@ -339,7 +350,8 @@ class ImportScripts::Baseu = User.new(opts)(opts[:custom_fields] || {}).each { |k, v| u.custom_fields[k] = v }u.custom_fields["import_id"] = import_id- u.custom_fields["import_username"] = original_username if original_username.present? && original_username != opts[:username]+ u.custom_fields["import_username"] = original_username if original_username.present? &&+ original_username != opts[:username]u.custom_fields["import_avatar_url"] = avatar_url if avatar_url.present?u.custom_fields["import_pass"] = opts[:password] if opts[:password].present?u.custom_fields["import_email"] = original_email if original_email != opts[:email]@@ -359,9 +371,7 @@ class ImportScripts::Baseendend- if opts[:active] && opts[:password].present?- u.activate- end+ u.activate if opts[:active] && opts[:password].present?rescue => e# try based on emailif e.try(:record).try(:errors).try(:messages).try(:[], :primary_email).present?@@ -377,7 +387,7 @@ class ImportScripts::Baseendend- if u.custom_fields['import_email']+ if u.custom_fields["import_email"]u.suspended_at = Time.zone.at(Time.now)u.suspended_till = 200.years.from_nowu.save!@@ -388,11 +398,15 @@ class ImportScripts::Baseuser_option.email_messages_level = UserOption.email_level_types[:never]user_option.save!if u.save- StaffActionLogger.new(Discourse.system_user).log_user_suspend(u, 'Invalid email address on import')+ StaffActionLogger.new(Discourse.system_user).log_user_suspend(+ u,+ "Invalid email address on import",+ )else- Rails.logger.error("Failed to suspend user #{u.username}. #{u.errors.try(:full_messages).try(:inspect)}")+ Rails.logger.error(+ "Failed to suspend user #{u.username}. #{u.errors.try(:full_messages).try(:inspect)}",+ )end-endpost_create_action.try(:call, u) if u.persisted?@@ -402,7 +416,8 @@ class ImportScripts::Basedef find_existing_user(email, username)# Force the use of the index on the 'user_emails' table- UserEmail.where("lower(email) = ?", email.downcase).first&.user || User.where(username: username).first+ UserEmail.where("lower(email) = ?", email.downcase).first&.user ||+ User.where(username: username).firstenddef created_category(category)@@ -435,7 +450,8 @@ class ImportScripts::Base# make sure categories don't go more than 2 levels deepif params[:parent_category_id]top = Category.find_by_id(params[:parent_category_id])- top = top.parent_category while (top&.height_of_ancestors || -1) + 1 >= SiteSetting.max_category_nesting+ top = top.parent_category while (top&.height_of_ancestors || -1) + 1 >=+ SiteSetting.max_category_nestingparams[:parent_category_id] = top.id if topend@@ -471,15 +487,16 @@ class ImportScripts::Basepost_create_action = opts.delete(:post_create_action)- new_category = Category.new(- name: opts[:name],- user_id: opts[:user_id] || opts[:user].try(:id) || Discourse::SYSTEM_USER_ID,- position: opts[:position],- parent_category_id: opts[:parent_category_id],- color: opts[:color] || category_color(opts[:parent_category_id]),- text_color: opts[:text_color] || "FFF",- read_restricted: opts[:read_restricted] || false,- )+ new_category =+ Category.new(+ name: opts[:name],+ user_id: opts[:user_id] || opts[:user].try(:id) || Discourse::SYSTEM_USER_ID,+ position: opts[:position],+ parent_category_id: opts[:parent_category_id],+ color: opts[:color] || category_color(opts[:parent_category_id]),+ text_color: opts[:text_color] || "FFF",+ read_restricted: opts[:read_restricted] || false,+ )new_category.custom_fields["import_id"] = import_id if import_idnew_category.save!@@ -498,10 +515,16 @@ class ImportScripts::Baseenddef category_color(parent_category_id)- @category_colors ||= SiteSetting.category_colors.split('|')+ @category_colors ||= SiteSetting.category_colors.split("|")index = @next_category_color_index[parent_category_id].presence || 0- @next_category_color_index[parent_category_id] = index + 1 >= @category_colors.count ? 0 : index + 1+ @next_category_color_index[parent_category_id] = (+ if index + 1 >= @category_colors.count+ 0+ else+ index + 1+ end+ )@category_colors[index]end@@ -571,7 +594,7 @@ class ImportScripts::Baseopts = opts.merge(skip_validations: true)opts[:import_mode] = trueopts[:custom_fields] ||= {}- opts[:custom_fields]['import_id'] = import_id+ opts[:custom_fields]["import_id"] = import_idunless opts[:topic_id]opts[:meta_data] = meta_data = {}@@ -582,7 +605,11 @@ class ImportScripts::Baseopts[:guardian] = STAFF_GUARDIANif @bbcode_to_md- opts[:raw] = opts[:raw].bbcode_to_md(false, {}, :disable, :quote) rescue opts[:raw]+ opts[:raw] = begin+ opts[:raw].bbcode_to_md(false, {}, :disable, :quote)+ rescue StandardError+ opts[:raw]+ endendpost_creator = PostCreator.new(user, opts)@@ -628,7 +655,7 @@ class ImportScripts::Basecreated += 1 if manager.errors.none?skipped += 1 if manager.errors.any?- rescue+ rescue StandardErrorskipped += 1endend@@ -671,14 +698,14 @@ class ImportScripts::Basedef close_inactive_topics(opts = {})num_days = opts[:days] || 30- puts '', "Closing topics that have been inactive for more than #{num_days} days."+ puts "", "Closing topics that have been inactive for more than #{num_days} days."- query = Topic.where('last_posted_at < ?', num_days.days.ago).where(closed: false)+ query = Topic.where("last_posted_at < ?", num_days.days.ago).where(closed: false)total_count = query.countclosed_count = 0query.find_each do |topic|- topic.update_status('closed', true, Discourse.system_user)+ topic.update_status("closed", true, Discourse.system_user)closed_count += 1print_status(closed_count, total_count, get_start_time("close_inactive_topics"))end@@ -790,7 +817,9 @@ class ImportScripts::Baseputs "", "Updating user digest_attempted_at..."- DB.exec("UPDATE user_stats SET digest_attempted_at = now() - random() * interval '1 week' WHERE digest_attempted_at IS NULL")+ DB.exec(+ "UPDATE user_stats SET digest_attempted_at = now() - random() * interval '1 week' WHERE digest_attempted_at IS NULL",+ )end# scripts that are able to import last_seen_at from the source data should override this method@@ -854,13 +883,15 @@ class ImportScripts::Basecount = 0total = User.count- User.includes(:user_stat).find_each do |user|- begin- user.update_columns(trust_level: 0) if user.trust_level > 0 && user.post_count == 0- rescue Discourse::InvalidAccess+ User+ .includes(:user_stat)+ .find_each do |user|+ begin+ user.update_columns(trust_level: 0) if user.trust_level > 0 && user.post_count == 0+ rescue Discourse::InvalidAccess+ end+ print_status(count += 1, total, get_start_time("update_tl0"))end- print_status(count += 1, total, get_start_time("update_tl0"))- endenddef update_user_signup_date_based_on_first_post@@ -870,7 +901,7 @@ class ImportScripts::Basetotal = User.countUser.find_each do |user|- if first = user.posts.order('created_at ASC').first+ if first = user.posts.order("created_at ASC").firstuser.created_at = first.created_atuser.save!end@@ -893,16 +924,16 @@ class ImportScripts::Basedef print_status(current, max, start_time = nil)if start_time.present?elapsed_seconds = Time.now - start_time- elements_per_minute = '[%.0f items/min] ' % [current / elapsed_seconds.to_f * 60]+ elements_per_minute = "[%.0f items/min] " % [current / elapsed_seconds.to_f * 60]else- elements_per_minute = ''+ elements_per_minute = ""endprint "\r%9d / %d (%5.1f%%) %s" % [current, max, current / max.to_f * 100, elements_per_minute]enddef print_spinner- @spinner_chars ||= %w{ | / - \\ }+ @spinner_chars ||= %w[| / - \\]@spinner_chars.push @spinner_chars.shiftprint "\b#{@spinner_chars[0]}"enddiff --git a/script/import_scripts/base/csv_helper.rb b/script/import_scripts/base/csv_helper.rbindex 7f7becbd3d6..3f211ea366a 100644--- a/script/import_scripts/base/csv_helper.rb+++ b/script/import_scripts/base/csv_helper.rb@@ -13,65 +13,69 @@ module ImportScriptsdef initialize(cols)cols.each_with_index do |col, idx|- self.class.public_send(:define_method, col.downcase.gsub(/[\W]/, '_').squeeze('_')) do- @row[idx]- end+ self+ .class+ .public_send(:define_method, col.downcase.gsub(/[\W]/, "_").squeeze("_")) { @row[idx] }endendend- def csv_parse(filename, col_sep = ',')+ def csv_parse(filename, col_sep = ",")first = truerow = nilcurrent_row = +""double_quote_count = 0- File.open(filename).each_line do |line|-- line.strip!-- current_row << "\n" unless current_row.empty?- current_row << line-- double_quote_count += line.scan('"').count-- next if double_quote_count % 2 == 1 # this row continues on a new line. don't parse until we have the whole row.-- raw = begin- CSV.parse(current_row, col_sep: col_sep)- rescue CSV::MalformedCSVError => e- puts e.message- puts "*" * 100- puts "Bad row skipped, line is: #{line}"- puts- puts current_row- puts- puts "double quote count is : #{double_quote_count}"- puts "*" * 100-- current_row = ""- double_quote_count = 0+ File+ .open(filename)+ .each_line do |line|+ line.strip!++ current_row << "\n" unless current_row.empty?+ current_row << line++ double_quote_count += line.scan('"').count++ next if double_quote_count % 2 == 1 # this row continues on a new line. don't parse until we have the whole row.++ raw =+ begin+ CSV.parse(current_row, col_sep: col_sep)+ rescue CSV::MalformedCSVError => e+ puts e.message+ puts "*" * 100+ puts "Bad row skipped, line is: #{line}"+ puts+ puts current_row+ puts+ puts "double quote count is : #{double_quote_count}"+ puts "*" * 100++ current_row = ""+ double_quote_count = 0++ next+ end[+ 0+ ]++ if first+ row = RowResolver.create(raw)++ current_row = ""+ double_quote_count = 0+ first = false+ next+ end- next- end[0]+ row.load(raw)- if first- row = RowResolver.create(raw)+ yield rowcurrent_row = ""double_quote_count = 0- first = false- nextend-- row.load(raw)-- yield row-- current_row = ""- double_quote_count = 0- endendendenddiff --git a/script/import_scripts/base/generic_database.rb b/script/import_scripts/base/generic_database.rbindex 28bfd8ee3bf..dafea94199e 100644--- a/script/import_scripts/base/generic_database.rb+++ b/script/import_scripts/base/generic_database.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require 'sqlite3'+require "sqlite3"module ImportScriptsclass GenericDatabase@@ -80,24 +80,20 @@ module ImportScriptsVALUES (:id, :raw, :topic_id, :user_id, :created_at, :reply_to_post_id, :url, :upload_count)SQL- attachments&.each do |attachment|- @db.execute(<<-SQL, post_id: post[:id], path: attachment)+ attachments&.each { |attachment| @db.execute(<<-SQL, post_id: post[:id], path: attachment) }INSERT OR REPLACE INTO post_upload (post_id, path)VALUES (:post_id, :path)SQL- end- like_user_ids&.each do |user_id|- @db.execute(<<-SQL, post_id: post[:id], user_id: user_id)+ like_user_ids&.each { |user_id| @db.execute(<<-SQL, post_id: post[:id], user_id: user_id) }INSERT OR REPLACE INTO like (post_id, user_id)VALUES (:post_id, :user_id)SQL- endendenddef sort_posts_by_created_at- @db.execute 'DELETE FROM post_order'+ @db.execute "DELETE FROM post_order"@db.execute <<-SQLINSERT INTO post_order (post_id)@@ -146,7 +142,7 @@ module ImportScriptsLIMIT #{@batch_size}SQL- add_last_column_value(rows, 'id')+ add_last_column_value(rows, "id")enddef get_user_id(username)@@ -173,7 +169,7 @@ module ImportScriptsLIMIT #{@batch_size}SQL- add_last_column_value(rows, 'id')+ add_last_column_value(rows, "id")enddef fetch_topic_attachments(topic_id)@@ -200,7 +196,7 @@ module ImportScriptsLIMIT #{@batch_size}SQL- add_last_column_value(rows, 'rowid')+ add_last_column_value(rows, "rowid")enddef fetch_sorted_posts(last_row_id)@@ -213,7 +209,7 @@ module ImportScriptsLIMIT #{@batch_size}SQL- add_last_column_value(rows, 'rowid')+ add_last_column_value(rows, "rowid")enddef fetch_post_attachments(post_id)@@ -240,7 +236,7 @@ module ImportScriptsLIMIT #{@batch_size}SQL- add_last_column_value(rows, 'rowid')+ add_last_column_value(rows, "rowid")enddef execute_sql(sql)@@ -254,12 +250,12 @@ module ImportScriptsprivatedef configure_database- @db.execute 'PRAGMA journal_mode = OFF'- @db.execute 'PRAGMA locking_mode = EXCLUSIVE'+ @db.execute "PRAGMA journal_mode = OFF"+ @db.execute "PRAGMA locking_mode = EXCLUSIVE"enddef key_data_type- @numeric_keys ? 'INTEGER' : 'TEXT'+ @numeric_keys ? "INTEGER" : "TEXT"enddef create_category_table@@ -299,7 +295,7 @@ module ImportScripts)SQL- @db.execute 'CREATE INDEX IF NOT EXISTS user_by_username ON user (username)'+ @db.execute "CREATE INDEX IF NOT EXISTS user_by_username ON user (username)"enddef create_topic_table@@ -317,7 +313,7 @@ module ImportScripts)SQL- @db.execute 'CREATE INDEX IF NOT EXISTS topic_by_user_id ON topic (user_id)'+ @db.execute "CREATE INDEX IF NOT EXISTS topic_by_user_id ON topic (user_id)"@db.execute <<-SQLCREATE TABLE IF NOT EXISTS topic_upload (@@ -326,7 +322,7 @@ module ImportScripts)SQL- @db.execute 'CREATE UNIQUE INDEX IF NOT EXISTS topic_upload_unique ON topic_upload(topic_id, path)'+ @db.execute "CREATE UNIQUE INDEX IF NOT EXISTS topic_upload_unique ON topic_upload(topic_id, path)"enddef create_post_table@@ -343,7 +339,7 @@ module ImportScripts)SQL- @db.execute 'CREATE INDEX IF NOT EXISTS post_by_user_id ON post (user_id)'+ @db.execute "CREATE INDEX IF NOT EXISTS post_by_user_id ON post (user_id)"@db.execute <<-SQLCREATE TABLE IF NOT EXISTS post_order (@@ -358,7 +354,7 @@ module ImportScripts)SQL- @db.execute 'CREATE UNIQUE INDEX IF NOT EXISTS post_upload_unique ON post_upload(post_id, path)'+ @db.execute "CREATE UNIQUE INDEX IF NOT EXISTS post_upload_unique ON post_upload(post_id, path)"enddef prepare(hash)diff --git a/script/import_scripts/base/lookup_container.rb b/script/import_scripts/base/lookup_container.rbindex 30ac96203d4..4147daf43f4 100644--- a/script/import_scripts/base/lookup_container.rb+++ b/script/import_scripts/base/lookup_container.rb@@ -3,27 +3,26 @@module ImportScriptsclass LookupContainerdef initialize- puts 'Loading existing groups...'- @groups = GroupCustomField.where(name: 'import_id').pluck(:value, :group_id).to_h+ puts "Loading existing groups..."+ @groups = GroupCustomField.where(name: "import_id").pluck(:value, :group_id).to_h- puts 'Loading existing users...'- @users = UserCustomField.where(name: 'import_id').pluck(:value, :user_id).to_h+ puts "Loading existing users..."+ @users = UserCustomField.where(name: "import_id").pluck(:value, :user_id).to_h- puts 'Loading existing categories...'- @categories = CategoryCustomField.where(name: 'import_id').pluck(:value, :category_id).to_h+ puts "Loading existing categories..."+ @categories = CategoryCustomField.where(name: "import_id").pluck(:value, :category_id).to_h- puts 'Loading existing posts...'- @posts = PostCustomField.where(name: 'import_id').pluck(:value, :post_id).to_h+ puts "Loading existing posts..."+ @posts = PostCustomField.where(name: "import_id").pluck(:value, :post_id).to_h- puts 'Loading existing topics...'+ puts "Loading existing topics..."@topics = {}- Post.joins(:topic).pluck('posts.id, posts.topic_id, posts.post_number, topics.slug').each do |p|- @topics[p[0]] = {- topic_id: p[1],- post_number: p[2],- url: Post.url(p[3], p[1], p[2])- }- end+ Post+ .joins(:topic)+ .pluck("posts.id, posts.topic_id, posts.post_number, topics.slug")+ .each do |p|+ @topics[p[0]] = { topic_id: p[1], post_number: p[2], url: Post.url(p[3], p[1], p[2]) }+ endend# Get the Discourse Post id based on the id of the source record@@ -44,7 +43,7 @@ module ImportScripts# Get the Discourse Group based on the id of the source groupdef find_group_by_import_id(import_id)- GroupCustomField.where(name: 'import_id', value: import_id.to_s).first.try(:group)+ GroupCustomField.where(name: "import_id", value: import_id.to_s).first.try(:group)end# Get the Discourse User id based on the id of the source user@@ -54,7 +53,7 @@ module ImportScripts# Get the Discourse User based on the id of the source userdef find_user_by_import_id(import_id)- UserCustomField.where(name: 'import_id', value: import_id.to_s).first.try(:user)+ UserCustomField.where(name: "import_id", value: import_id.to_s).first.try(:user)enddef find_username_by_import_id(import_id)@@ -84,11 +83,7 @@ module ImportScriptsenddef add_topic(post)- @topics[post.id] = {- post_number: post.post_number,- topic_id: post.topic_id,- url: post.url,- }+ @topics[post.id] = { post_number: post.post_number, topic_id: post.topic_id, url: post.url }enddef user_already_imported?(import_id)@@ -98,6 +93,5 @@ module ImportScriptsdef post_already_imported?(import_id)@posts.has_key?(import_id) || @posts.has_key?(import_id.to_s)end-endenddiff --git a/script/import_scripts/base/uploader.rb b/script/import_scripts/base/uploader.rbindex 45404bba21a..4342d328878 100644--- a/script/import_scripts/base/uploader.rb+++ b/script/import_scripts/base/uploader.rb@@ -13,8 +13,16 @@ module ImportScriptsSTDERR.puts "Failed to create upload: #{e}"nilensure- tmp.close rescue nil- tmp.unlink rescue nil+ begin+ tmp.close+ rescue StandardError+ nil+ end+ begin+ tmp.unlink+ rescue StandardError+ nil+ endenddef create_avatar(user, avatar_path)@@ -30,7 +38,7 @@ module ImportScriptsSTDERR.puts "Failed to upload avatar for user #{user.username}: #{avatar_path}"STDERR.puts upload.errors.inspect if uploadend- rescue+ rescue StandardErrorSTDERR.puts "Failed to create avatar for user #{user.username}: #{avatar_path}"ensuretempfile.close! if tempfile@@ -52,11 +60,9 @@ module ImportScriptsdef copy_to_tempfile(source_path)extension = File.extname(source_path)- tmp = Tempfile.new(['discourse-upload', extension])+ tmp = Tempfile.new(["discourse-upload", extension])- File.open(source_path) do |source_stream|- IO.copy_stream(source_stream, tmp)- end+ File.open(source_path) { |source_stream| IO.copy_stream(source_stream, tmp) }tmp.rewindtmpdiff --git a/script/import_scripts/bbpress.rb b/script/import_scripts/bbpress.rbindex 2cd0698d123..4864ba6b94f 100644--- a/script/import_scripts/bbpress.rb+++ b/script/import_scripts/bbpress.rb@@ -1,29 +1,29 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Bbpress < ImportScripts::Base-- BB_PRESS_HOST ||= ENV['BBPRESS_HOST'] || "localhost"- BB_PRESS_DB ||= ENV['BBPRESS_DB'] || "bbpress"- BATCH_SIZE ||= 1000- BB_PRESS_PW ||= ENV['BBPRESS_PW'] || ""- BB_PRESS_USER ||= ENV['BBPRESS_USER'] || "root"- BB_PRESS_PREFIX ||= ENV['BBPRESS_PREFIX'] || "wp_"- BB_PRESS_ATTACHMENTS_DIR ||= ENV['BBPRESS_ATTACHMENTS_DIR'] || "/path/to/attachments"+ BB_PRESS_HOST ||= ENV["BBPRESS_HOST"] || "localhost"+ BB_PRESS_DB ||= ENV["BBPRESS_DB"] || "bbpress"+ BATCH_SIZE ||= 1000+ BB_PRESS_PW ||= ENV["BBPRESS_PW"] || ""+ BB_PRESS_USER ||= ENV["BBPRESS_USER"] || "root"+ BB_PRESS_PREFIX ||= ENV["BBPRESS_PREFIX"] || "wp_"+ BB_PRESS_ATTACHMENTS_DIR ||= ENV["BBPRESS_ATTACHMENTS_DIR"] || "/path/to/attachments"def initializesuper@he = HTMLEntities.new- @client = Mysql2::Client.new(- host: BB_PRESS_HOST,- username: BB_PRESS_USER,- database: BB_PRESS_DB,- password: BB_PRESS_PW,- )+ @client =+ Mysql2::Client.new(+ host: BB_PRESS_HOST,+ username: BB_PRESS_USER,+ database: BB_PRESS_DB,+ password: BB_PRESS_PW,+ )enddef execute@@ -40,17 +40,16 @@ class ImportScripts::Bbpress < ImportScripts::Baseputs "", "importing users..."last_user_id = -1- total_users = bbpress_query(<<-SQL+ total_users = bbpress_query(<<-SQL).first["cnt"]SELECT COUNT(DISTINCT(u.id)) AS cntFROM #{BB_PRESS_PREFIX}users uLEFT JOIN #{BB_PRESS_PREFIX}posts p ON p.post_author = u.idWHERE p.post_type IN ('forum', 'reply', 'topic')AND user_email LIKE '%@%'SQL- ).first["cnt"]batches(BATCH_SIZE) do |offset|- users = bbpress_query(<<-SQL+ users = bbpress_query(<<-SQL).to_aSELECT u.id, user_nicename, display_name, user_email, user_registered, user_url, user_passFROM #{BB_PRESS_PREFIX}users uLEFT JOIN #{BB_PRESS_PREFIX}posts p ON p.post_author = u.id@@ -61,7 +60,6 @@ class ImportScripts::Bbpress < ImportScripts::BaseORDER BY u.idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?@@ -73,22 +71,20 @@ class ImportScripts::Bbpress < ImportScripts::Baseuser_ids_sql = user_ids.join(",")users_description = {}- bbpress_query(<<-SQL+ bbpress_query(<<-SQL).each { |um| users_description[um["user_id"]] = um["description"] }SELECT user_id, meta_value descriptionFROM #{BB_PRESS_PREFIX}usermetaWHERE user_id IN (#{user_ids_sql})AND meta_key = 'description'SQL- ).each { |um| users_description[um["user_id"]] = um["description"] }users_last_activity = {}- bbpress_query(<<-SQL+ bbpress_query(<<-SQL).each { |um| users_last_activity[um["user_id"]] = um["last_activity"] }SELECT user_id, meta_value last_activityFROM #{BB_PRESS_PREFIX}usermetaWHERE user_id IN (#{user_ids_sql})AND meta_key = 'last_activity'SQL- ).each { |um| users_last_activity[um["user_id"]] = um["last_activity"] }create_users(users, total: total_users, offset: offset) do |u|{@@ -96,7 +92,7 @@ class ImportScripts::Bbpress < ImportScripts::Baseusername: u["user_nicename"],password: u["user_pass"],email: u["user_email"].downcase,- name: u["display_name"].presence || u['user_nicename'],+ name: u["display_name"].presence || u["user_nicename"],created_at: u["user_registered"],website: u["user_url"],bio_raw: users_description[u["id"]],@@ -114,67 +110,60 @@ class ImportScripts::Bbpress < ImportScripts::Baseemails = Array.new# gather anonymous users via postmeta table- bbpress_query(<<-SQL+ bbpress_query(<<-SQL).each do |pm|SELECT post_id, meta_key, meta_valueFROM #{BB_PRESS_PREFIX}postmetaWHERE meta_key LIKE '_bbp_anonymous%'SQL- ).each do |pm|- anon_posts[pm['post_id']] = Hash.new if not anon_posts[pm['post_id']]+ anon_posts[pm["post_id"]] = Hash.new if not anon_posts[pm["post_id"]]- if pm['meta_key'] == '_bbp_anonymous_email'- anon_posts[pm['post_id']]['email'] = pm['meta_value']+ if pm["meta_key"] == "_bbp_anonymous_email"+ anon_posts[pm["post_id"]]["email"] = pm["meta_value"]end- if pm['meta_key'] == '_bbp_anonymous_name'- anon_posts[pm['post_id']]['name'] = pm['meta_value']+ if pm["meta_key"] == "_bbp_anonymous_name"+ anon_posts[pm["post_id"]]["name"] = pm["meta_value"]end- if pm['meta_key'] == '_bbp_anonymous_website'- anon_posts[pm['post_id']]['website'] = pm['meta_value']+ if pm["meta_key"] == "_bbp_anonymous_website"+ anon_posts[pm["post_id"]]["website"] = pm["meta_value"]endend# gather every existent usernameanon_posts.each do |id, post|- anon_names[post['name']] = Hash.new if not anon_names[post['name']]+ anon_names[post["name"]] = Hash.new if not anon_names[post["name"]]# overwriting email address, one user can only use one email address- anon_names[post['name']]['email'] = post['email']- anon_names[post['name']]['website'] = post['website'] if post['website'] != ''+ anon_names[post["name"]]["email"] = post["email"]+ anon_names[post["name"]]["website"] = post["website"] if post["website"] != ""end# make sure every user name has a unique email addressanon_names.each do |k, name|- if not emails.include? name['email']- emails.push ( name['email'])+ if not emails.include? name["email"]+ emails.push (name["email"])else- name['email'] = "anonymous_#{SecureRandom.hex}@no-email.invalid"+ name["email"] = "anonymous_#{SecureRandom.hex}@no-email.invalid"endendcreate_users(anon_names) do |k, n|- {- id: k,- email: n["email"].downcase,- name: k,- website: n["website"]- }+ { id: k, email: n["email"].downcase, name: k, website: n["website"] }endenddef import_categoriesputs "", "importing categories..."- categories = bbpress_query(<<-SQL+ categories = bbpress_query(<<-SQL)SELECT id, post_name, post_parentFROM #{BB_PRESS_PREFIX}postsWHERE post_type = 'forum'AND LENGTH(COALESCE(post_name, '')) > 0ORDER BY post_parent, idSQL- )create_categories(categories) do |c|- category = { id: c['id'], name: c['post_name'] }- if (parent_id = c['post_parent'].to_i) > 0+ category = { id: c["id"], name: c["post_name"] }+ if (parent_id = c["post_parent"].to_i) > 0category[:parent_category_id] = category_id_from_imported_category_id(parent_id)endcategory@@ -185,16 +174,15 @@ class ImportScripts::Bbpress < ImportScripts::Baseputs "", "importing topics and posts..."last_post_id = -1- total_posts = bbpress_query(<<-SQL+ total_posts = bbpress_query(<<-SQL).first["count"]SELECT COUNT(*) countFROM #{BB_PRESS_PREFIX}postsWHERE post_status <> 'spam'AND post_type IN ('topic', 'reply')SQL- ).first["count"]batches(BATCH_SIZE) do |offset|- posts = bbpress_query(<<-SQL+ posts = bbpress_query(<<-SQL).to_aSELECT id,post_author,post_date,@@ -209,7 +197,6 @@ class ImportScripts::Bbpress < ImportScripts::BaseORDER BY idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if posts.empty?@@ -221,31 +208,29 @@ class ImportScripts::Bbpress < ImportScripts::Basepost_ids_sql = post_ids.join(",")posts_likes = {}- bbpress_query(<<-SQL+ bbpress_query(<<-SQL).each { |pm| posts_likes[pm["post_id"]] = pm["likes"].to_i }SELECT post_id, meta_value likesFROM #{BB_PRESS_PREFIX}postmetaWHERE post_id IN (#{post_ids_sql})AND meta_key = 'Likes'SQL- ).each { |pm| posts_likes[pm["post_id"]] = pm["likes"].to_i }anon_names = {}- bbpress_query(<<-SQL+ bbpress_query(<<-SQL).each { |pm| anon_names[pm["post_id"]] = pm["meta_value"] }SELECT post_id, meta_valueFROM #{BB_PRESS_PREFIX}postmetaWHERE post_id IN (#{post_ids_sql})AND meta_key = '_bbp_anonymous_name'SQL- ).each { |pm| anon_names[pm["post_id"]] = pm["meta_value"] }create_posts(posts, total: total_posts, offset: offset) do |p|skip = false- user_id = user_id_from_imported_user_id(p["post_author"]) ||- find_user_by_import_id(p["post_author"]).try(:id) ||- user_id_from_imported_user_id(anon_names[p['id']]) ||- find_user_by_import_id(anon_names[p['id']]).try(:id) ||- -1+ user_id =+ user_id_from_imported_user_id(p["post_author"]) ||+ find_user_by_import_id(p["post_author"]).try(:id) ||+ user_id_from_imported_user_id(anon_names[p["id"]]) ||+ find_user_by_import_id(anon_names[p["id"]]).try(:id) || -1post = {id: p["id"],@@ -256,7 +241,9 @@ class ImportScripts::Bbpress < ImportScripts::Base}if post[:raw].present?- post[:raw].gsub!(/\<pre\>\<code(=[a-z]*)?\>(.*?)\<\/code\>\<\/pre\>/im) { "```\n#{@he.decode($2)}\n```" }+ post[:raw].gsub!(%r{\<pre\>\<code(=[a-z]*)?\>(.*?)\</code\>\</pre\>}im) do+ "```\n#{@he.decode($2)}\n```"+ endendif p["post_type"] == "topic"@@ -288,17 +275,16 @@ class ImportScripts::Bbpress < ImportScripts::Basecount = 0last_attachment_id = -1- total_attachments = bbpress_query(<<-SQL+ total_attachments = bbpress_query(<<-SQL).first["count"]SELECT COUNT(*) countFROM #{BB_PRESS_PREFIX}postmeta pmJOIN #{BB_PRESS_PREFIX}posts p ON p.id = pm.post_idWHERE pm.meta_key = '_wp_attached_file'AND p.post_parent > 0SQL- ).first["count"]batches(BATCH_SIZE) do |offset|- attachments = bbpress_query(<<-SQL+ attachments = bbpress_query(<<-SQL).to_aSELECT pm.meta_id id, pm.meta_value, p.post_parent post_idFROM #{BB_PRESS_PREFIX}postmeta pmJOIN #{BB_PRESS_PREFIX}posts p ON p.id = pm.post_id@@ -308,7 +294,6 @@ class ImportScripts::Bbpress < ImportScripts::BaseORDER BY pm.meta_idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if attachments.empty?last_attachment_id = attachments[-1]["id"].to_i@@ -325,7 +310,9 @@ class ImportScripts::Bbpress < ImportScripts::Baseif !post.raw[html]post.raw << "\n\n" << htmlpost.save!- PostUpload.create!(post: post, upload: upload) unless PostUpload.where(post: post, upload: upload).exists?+ unless PostUpload.where(post: post, upload: upload).exists?+ PostUpload.create!(post: post, upload: upload)+ endendendend@@ -340,15 +327,14 @@ class ImportScripts::Bbpress < ImportScripts::Basecount = 0last_attachment_id = -1- total_attachments = bbpress_query(<<-SQL+ total_attachments = bbpress_query(<<-SQL).first["count"]SELECT COUNT(*) countFROM #{BB_PRESS_PREFIX}bb_attachmentsWHERE post_id IN (SELECT id FROM #{BB_PRESS_PREFIX}posts WHERE post_status <> 'spam' AND post_type IN ('topic', 'reply'))SQL- ).first["count"]batches(BATCH_SIZE) do |offset|- attachments = bbpress_query(<<-SQL+ attachments = bbpress_query(<<-SQL).to_aSELECT id, filename, post_idFROM #{BB_PRESS_PREFIX}bb_attachmentsWHERE post_id IN (SELECT id FROM #{BB_PRESS_PREFIX}posts WHERE post_status <> 'spam' AND post_type IN ('topic', 'reply'))@@ -356,13 +342,16 @@ class ImportScripts::Bbpress < ImportScripts::BaseORDER BY idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if attachments.empty?last_attachment_id = attachments[-1]["id"].to_iattachments.each do |a|- print_status(count += 1, total_attachments, get_start_time("attachments_from_bb_attachments"))+ print_status(+ count += 1,+ total_attachments,+ get_start_time("attachments_from_bb_attachments"),+ )if path = find_attachment(a["filename"], a["id"])if post = Post.find_by(id: post_id_from_imported_post_id(a["post_id"]))upload = create_upload(post.user.id, path, a["filename"])@@ -371,7 +360,9 @@ class ImportScripts::Bbpress < ImportScripts::Baseif !post.raw[html]post.raw << "\n\n" << htmlpost.save!- PostUpload.create!(post: post, upload: upload) unless PostUpload.where(post: post, upload: upload).exists?+ unless PostUpload.where(post: post, upload: upload).exists?+ PostUpload.create!(post: post, upload: upload)+ endendendend@@ -391,7 +382,7 @@ class ImportScripts::Bbpress < ImportScripts::Baselast_topic_id = -1batches(BATCH_SIZE) do |offset|- topics = bbpress_query(<<-SQL+ topics = bbpress_query(<<-SQL).to_aSELECT id,guidFROM #{BB_PRESS_PREFIX}posts@@ -401,14 +392,17 @@ class ImportScripts::Bbpress < ImportScripts::BaseORDER BY idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if topics.empty?last_topic_id = topics[-1]["id"].to_itopics.each do |t|- topic = topic_lookup_from_imported_post_id(t['id'])- Permalink.create(url: URI.parse(t['guid']).path.chomp('/'), topic_id: topic[:topic_id]) rescue nil+ topic = topic_lookup_from_imported_post_id(t["id"])+ begin+ Permalink.create(url: URI.parse(t["guid"]).path.chomp("/"), topic_id: topic[:topic_id])+ rescue StandardError+ nil+ endendendend@@ -417,42 +411,44 @@ class ImportScripts::Bbpress < ImportScripts::Baseputs "", "importing private messages..."last_post_id = -1- total_posts = bbpress_query("SELECT COUNT(*) count FROM #{BB_PRESS_PREFIX}bp_messages_messages").first["count"]+ total_posts =+ bbpress_query("SELECT COUNT(*) count FROM #{BB_PRESS_PREFIX}bp_messages_messages").first[+ "count"+ ]threads = {}- total_count = bbpress_query("SELECT COUNT(*) count FROM #{BB_PRESS_PREFIX}bp_messages_recipients").first["count"]+ total_count =+ bbpress_query("SELECT COUNT(*) count FROM #{BB_PRESS_PREFIX}bp_messages_recipients").first[+ "count"+ ]current_count = 0batches(BATCH_SIZE) do |offset|- rows = bbpress_query(<<-SQL+ rows = bbpress_query(<<-SQL).to_aSELECT thread_id, user_idFROM #{BB_PRESS_PREFIX}bp_messages_recipientsORDER BY idLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- ).to_abreak if rows.empty?rows.each do |row|current_count += 1- print_status(current_count, total_count, get_start_time('private_messages'))+ print_status(current_count, total_count, get_start_time("private_messages"))- threads[row['thread_id']] ||= {- target_user_ids: [],- imported_topic_id: nil- }- user_id = user_id_from_imported_user_id(row['user_id'])- if user_id && !threads[row['thread_id']][:target_user_ids].include?(user_id)- threads[row['thread_id']][:target_user_ids] << user_id+ threads[row["thread_id"]] ||= { target_user_ids: [], imported_topic_id: nil }+ user_id = user_id_from_imported_user_id(row["user_id"])+ if user_id && !threads[row["thread_id"]][:target_user_ids].include?(user_id)+ threads[row["thread_id"]][:target_user_ids] << user_idendendendbatches(BATCH_SIZE) do |offset|- posts = bbpress_query(<<-SQL+ posts = bbpress_query(<<-SQL).to_aSELECT id,thread_id,date_sent,@@ -464,39 +460,48 @@ class ImportScripts::Bbpress < ImportScripts::BaseORDER BY thread_id, date_sentLIMIT #{BATCH_SIZE}SQL- ).to_abreak if posts.empty?last_post_id = posts[-1]["id"].to_icreate_posts(posts, total: total_posts, offset: offset) do |post|- if tcf = TopicCustomField.where(name: 'bb_thread_id', value: post['thread_id']).first+ if tcf = TopicCustomField.where(name: "bb_thread_id", value: post["thread_id"]).first{- id: "pm#{post['id']}",- topic_id: threads[post['thread_id']][:imported_topic_id],- user_id: user_id_from_imported_user_id(post['sender_id']) || find_user_by_import_id(post['sender_id'])&.id || -1,- raw: post['message'],- created_at: post['date_sent'],+ id: "pm#{post["id"]}",+ topic_id: threads[post["thread_id"]][:imported_topic_id],+ user_id:+ user_id_from_imported_user_id(post["sender_id"]) ||+ find_user_by_import_id(post["sender_id"])&.id || -1,+ raw: post["message"],+ created_at: post["date_sent"],}else# First post of the thread{- id: "pm#{post['id']}",+ id: "pm#{post["id"]}",archetype: Archetype.private_message,- user_id: user_id_from_imported_user_id(post['sender_id']) || find_user_by_import_id(post['sender_id'])&.id || -1,- title: post['subject'],- raw: post['message'],- created_at: post['date_sent'],- target_usernames: User.where(id: threads[post['thread_id']][:target_user_ids]).pluck(:username),- post_create_action: proc do |new_post|- if topic = new_post.topic- threads[post['thread_id']][:imported_topic_id] = topic.id- TopicCustomField.create(topic_id: topic.id, name: 'bb_thread_id', value: post['thread_id'])- else- puts "Error in post_create_action! Can't find topic!"- end- end+ user_id:+ user_id_from_imported_user_id(post["sender_id"]) ||+ find_user_by_import_id(post["sender_id"])&.id || -1,+ title: post["subject"],+ raw: post["message"],+ created_at: post["date_sent"],+ target_usernames:+ User.where(id: threads[post["thread_id"]][:target_user_ids]).pluck(:username),+ post_create_action:+ proc do |new_post|+ if topic = new_post.topic+ threads[post["thread_id"]][:imported_topic_id] = topic.id+ TopicCustomField.create(+ topic_id: topic.id,+ name: "bb_thread_id",+ value: post["thread_id"],+ )+ else+ puts "Error in post_create_action! Can't find topic!"+ end+ end,}endend@@ -506,7 +511,6 @@ class ImportScripts::Bbpress < ImportScripts::Basedef bbpress_query(sql)@client.query(sql, cache_rows: false)end-endImportScripts::Bbpress.new.performdiff --git a/script/import_scripts/bespoke_1.rb b/script/import_scripts/bespoke_1.rbindex 9ca420f319a..833f7723500 100644--- a/script/import_scripts/bespoke_1.rb+++ b/script/import_scripts/bespoke_1.rb@@ -2,13 +2,12 @@# bespoke importer for a customer, feel free to borrow ideas-require 'csv'+require "csv"require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/bespoke_1.rbclass ImportScripts::Bespoke < ImportScripts::Base-BATCH_SIZE = 1000def initialize(path)@@ -18,9 +17,9 @@ class ImportScripts::Bespoke < ImportScripts::Baseputs "loading post mappings..."@post_number_map = {}- Post.pluck(:id, :post_number).each do |post_id, post_number|- @post_number_map[post_id] = post_number- end+ Post+ .pluck(:id, :post_number)+ .each { |post_id, post_number| @post_number_map[post_id] = post_number }enddef created_post(post)@@ -32,7 +31,6 @@ class ImportScripts::Bespoke < ImportScripts::Baseimport_usersimport_categoriesimport_posts-endclass RowResolver@@ -45,19 +43,13 @@ class ImportScripts::Bespoke < ImportScripts::Baseenddef initialize(cols)- cols.each_with_index do |col, idx|- self.class.public_send(:define_method, col) do- @row[idx]- end- end+ cols.each_with_index { |col, idx| self.class.public_send(:define_method, col) { @row[idx] } }endenddef load_user_batch!(users, offset, total)if users.length > 0- create_users(users, offset: offset, total: total) do |user|- user- end+ create_users(users, offset: offset, total: total) { |user| user }users.clearendend@@ -70,54 +62,56 @@ class ImportScripts::Bespoke < ImportScripts::Basecurrent_row = +""double_quote_count = 0- File.open(filename).each_line do |line|-- # escaping is mental here- line.gsub!(/\\(.{1})/) { |m| m[-1] == '"' ? '""' : m[-1] }- line.strip!-- current_row << "\n" unless current_row.empty?- current_row << line-- double_quote_count += line.scan('"').count+ File+ .open(filename)+ .each_line do |line|+ # escaping is mental here+ line.gsub!(/\\(.{1})/) { |m| m[-1] == '"' ? '""' : m[-1] }+ line.strip!++ current_row << "\n" unless current_row.empty?+ current_row << line++ double_quote_count += line.scan('"').count++ next if double_quote_count % 2 == 1++ raw =+ begin+ CSV.parse(current_row)+ rescue CSV::MalformedCSVError => e+ puts e.message+ puts "*" * 100+ puts "Bad row skipped, line is: #{line}"+ puts+ puts current_row+ puts+ puts "double quote count is : #{double_quote_count}"+ puts "*" * 100++ current_row = ""+ double_quote_count = 0+ next+ end[+ 0+ ]++ if first+ row = RowResolver.create(raw)++ current_row = ""+ double_quote_count = 0+ first = false+ next+ end- if double_quote_count % 2 == 1- next- end+ row.load(raw)- raw = begin- CSV.parse(current_row)- rescue CSV::MalformedCSVError => e- puts e.message- puts "*" * 100- puts "Bad row skipped, line is: #{line}"- puts- puts current_row- puts- puts "double quote count is : #{double_quote_count}"- puts "*" * 100-- current_row = ""- double_quote_count = 0- next- end[0]-- if first- row = RowResolver.create(raw)+ yield rowcurrent_row = ""double_quote_count = 0- first = false- nextend-- row.load(raw)-- yield row-- current_row = ""- double_quote_count = 0- endenddef total_rows(table)@@ -133,14 +127,11 @@ class ImportScripts::Bespoke < ImportScripts::Basetotal = total_rows("users")csv_parse("users") do |row|-id = row.idemail = row.email# fake it- if row.email.blank? || row.email !~ /@/- email = fake_email- end+ email = fake_email if row.email.blank? || row.email !~ /@/name = row.display_nameusername = row.key_custom@@ -150,19 +141,10 @@ class ImportScripts::Bespoke < ImportScripts::Baseusername = email.split("@")[0] if username.blank?name = email.split("@")[0] if name.blank?- users << {- id: id,- email: email,- name: name,- username: username,- created_at: created_at- }+ users << { id: id, email: email, name: name, username: username, created_at: created_at }count += 1- if count % BATCH_SIZE == 0- load_user_batch! users, count - users.length, total- end-+ load_user_batch! users, count - users.length, total if count % BATCH_SIZE == 0endload_user_batch! users, count, total@@ -174,22 +156,19 @@ class ImportScripts::Bespoke < ImportScripts::Baserows << { id: row.id, name: row.name, description: row.description }end- create_categories(rows) do |row|- row- end+ create_categories(rows) { |row| row }enddef normalize_raw!(raw)# purple and #1223f3raw.gsub!(/\[color=[#a-z0-9]+\]/i, "")- raw.gsub!(/\[\/color\]/i, "")- raw.gsub!(/\[signature\].+\[\/signature\]/im, "")+ raw.gsub!(%r{\[/color\]}i, "")+ raw.gsub!(%r{\[signature\].+\[/signature\]}im, "")rawenddef import_post_batch!(posts, topics, offset, total)create_posts(posts, total: total, offset: offset) do |post|-mapped = {}mapped[:id] = post[:id]@@ -223,7 +202,7 @@ class ImportScripts::Bespoke < ImportScripts::Basemappedend- posts.clear+ posts.clearenddef import_posts@@ -237,7 +216,7 @@ class ImportScripts::Bespoke < ImportScripts::Basecategory_id: topic.forum_category_id,deleted: topic.is_deleted.to_i == 1,locked: topic.is_locked.to_i == 1,- pinned: topic.is_pinned.to_i == 1+ pinned: topic.is_pinned.to_i == 1,}end@@ -246,7 +225,6 @@ class ImportScripts::Bespoke < ImportScripts::Baseposts = []count = 0csv_parse("posts") do |row|-unless row.dcreateputs "NO CREATION DATE FOR POST"p row@@ -261,7 +239,7 @@ class ImportScripts::Bespoke < ImportScripts::Basetitle: row.title,body: normalize_raw!(row.body),deleted: row.is_deleted.to_i == 1,- created_at: DateTime.parse(row.dcreate)+ created_at: DateTime.parse(row.dcreate),}posts << rowcount += 1@@ -275,7 +253,6 @@ class ImportScripts::Bespoke < ImportScripts::Baseexitend-endunless ARGV[0] && Dir.exist?(ARGV[0])diff --git a/script/import_scripts/csv_importer.rb b/script/import_scripts/csv_importer.rbindex a414373dbba..626645f5303 100644--- a/script/import_scripts/csv_importer.rb+++ b/script/import_scripts/csv_importer.rb@@ -7,18 +7,18 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Make sure to follow the right format in your CSV files.class ImportScripts::CsvImporter < ImportScripts::Base-- CSV_FILE_PATH = ENV['CSV_USER_FILE'] || '/var/www/discourse/tmp/users.csv'- CSV_CUSTOM_FIELDS = ENV['CSV_CUSTOM_FIELDS'] || '/var/www/discourse/tmp/custom_fields.csv'- CSV_EMAILS = ENV['CSV_EMAILS'] || '/var/www/discourse/tmp/emails.csv'- CSV_CATEGORIES = ENV['CSV_CATEGORIES'] || '/var/www/discourse/tmp/categories.csv'- CSV_TOPICS = ENV['CSV_TOPICS'] || '/var/www/discourse/tmp/topics_new_users.csv'- CSV_TOPICS_EXISTING_USERS = ENV['CSV_TOPICS'] || '/var/www/discourse/tmp/topics_existing_users.csv'- IMPORT_PREFIX = ENV['IMPORT_PREFIX'] || '2022-08-11'- IMPORT_USER_ID_PREFIX = 'csv-user-import-' + IMPORT_PREFIX + '-'- IMPORT_CATEGORY_ID_PREFIX = 'csv-category-import-' + IMPORT_PREFIX + '-'- IMPORT_TOPIC_ID_PREFIX = 'csv-topic-import-' + IMPORT_PREFIX + '-'- IMPORT_TOPIC_ID_EXISITNG_PREFIX = 'csv-topic_existing-import-' + IMPORT_PREFIX + '-'+ CSV_FILE_PATH = ENV["CSV_USER_FILE"] || "/var/www/discourse/tmp/users.csv"+ CSV_CUSTOM_FIELDS = ENV["CSV_CUSTOM_FIELDS"] || "/var/www/discourse/tmp/custom_fields.csv"+ CSV_EMAILS = ENV["CSV_EMAILS"] || "/var/www/discourse/tmp/emails.csv"+ CSV_CATEGORIES = ENV["CSV_CATEGORIES"] || "/var/www/discourse/tmp/categories.csv"+ CSV_TOPICS = ENV["CSV_TOPICS"] || "/var/www/discourse/tmp/topics_new_users.csv"+ CSV_TOPICS_EXISTING_USERS =+ ENV["CSV_TOPICS"] || "/var/www/discourse/tmp/topics_existing_users.csv"+ IMPORT_PREFIX = ENV["IMPORT_PREFIX"] || "2022-08-11"+ IMPORT_USER_ID_PREFIX = "csv-user-import-" + IMPORT_PREFIX + "-"+ IMPORT_CATEGORY_ID_PREFIX = "csv-category-import-" + IMPORT_PREFIX + "-"+ IMPORT_TOPIC_ID_PREFIX = "csv-topic-import-" + IMPORT_PREFIX + "-"+ IMPORT_TOPIC_ID_EXISITNG_PREFIX = "csv-topic_existing-import-" + IMPORT_PREFIX + "-"def initializesuper@@ -49,25 +49,19 @@ class ImportScripts::CsvImporter < ImportScripts::Basereturn nilend- CSV.parse(File.read(path, encoding: 'bom|utf-8'), headers: true)+ CSV.parse(File.read(path, encoding: "bom|utf-8"), headers: true)enddef username_for(name)- result = name.downcase.gsub(/[^a-z0-9\-\_]/, '')- if result.blank?- result = Digest::SHA1.hexdigest(name)[0...10]- end+ result = name.downcase.gsub(/[^a-z0-9\-\_]/, "")+ result = Digest::SHA1.hexdigest(name)[0...10] if result.blank?resultenddef get_email(id)email = nil- @imported_emails.each do |e|- if e["user_id"] == id- email = e["email"]- end- end+ @imported_emails.each { |e| email = e["email"] if e["user_id"] == id }end@@ -76,9 +70,7 @@ class ImportScripts::CsvImporter < ImportScripts::Basecustom_fields = {}@imported_custom_fields.each do |cf|if cf["user_id"] == id- @imported_custom_fields_names.each do |name|- custom_fields[name] = cf[name]- end+ @imported_custom_fields_names.each { |name| custom_fields[name] = cf[name] }endend@@ -86,98 +78,95 @@ class ImportScripts::CsvImporter < ImportScripts::Baseenddef import_users- puts '', "Importing users"+ puts "", "Importing users"users = []@imported_users.each do |u|- email = get_email(u['id'])- custom_fields = get_custom_fields(u['id'])- u['email'] = email- u['custom_fields'] = custom_fields- u['id'] = IMPORT_USER_ID_PREFIX + u['id']+ email = get_email(u["id"])+ custom_fields = get_custom_fields(u["id"])+ u["email"] = email+ u["custom_fields"] = custom_fields+ u["id"] = IMPORT_USER_ID_PREFIX + u["id"]users << uendusers.uniq!create_users(users) do |u|{- id: u['id'],- username: u['username'],- email: u['email'],- created_at: u['created_at'],- custom_fields: u['custom_fields'],+ id: u["id"],+ username: u["username"],+ email: u["email"],+ created_at: u["created_at"],+ custom_fields: u["custom_fields"],}endenddef import_categories- puts '', "Importing categories"+ puts "", "Importing categories"categories = []@imported_categories.each do |c|- c['user_id'] = user_id_from_imported_user_id(IMPORT_USER_ID_PREFIX + c['user_id']) || Discourse::SYSTEM_USER_ID- c['id'] = IMPORT_CATEGORY_ID_PREFIX + c['id']+ c["user_id"] = user_id_from_imported_user_id(IMPORT_USER_ID_PREFIX + c["user_id"]) ||+ Discourse::SYSTEM_USER_ID+ c["id"] = IMPORT_CATEGORY_ID_PREFIX + c["id"]categories << cendcategories.uniq!create_categories(categories) do |c|- {- id: c['id'],- user_id: c['user_id'],- name: c['name'],- description: c['description']- }+ { id: c["id"], user_id: c["user_id"], name: c["name"], description: c["description"] }endenddef import_topics- puts '', "Importing topics"+ puts "", "Importing topics"topics = []@imported_topics.each do |t|- t['user_id'] = user_id_from_imported_user_id(IMPORT_USER_ID_PREFIX + t['user_id']) || Discourse::SYSTEM_USER_ID- t['category_id'] = category_id_from_imported_category_id(IMPORT_CATEGORY_ID_PREFIX + t['category_id'])- t['id'] = IMPORT_TOPIC_ID_PREFIX + t['id']+ t["user_id"] = user_id_from_imported_user_id(IMPORT_USER_ID_PREFIX + t["user_id"]) ||+ Discourse::SYSTEM_USER_ID+ t["category_id"] = category_id_from_imported_category_id(+ IMPORT_CATEGORY_ID_PREFIX + t["category_id"],+ )+ t["id"] = IMPORT_TOPIC_ID_PREFIX + t["id"]topics << tendcreate_posts(topics) do |t|{- id: t['id'],- user_id: t['user_id'],- title: t['title'],- category: t['category_id'],- raw: t['raw']+ id: t["id"],+ user_id: t["user_id"],+ title: t["title"],+ category: t["category_id"],+ raw: t["raw"],}endenddef import_topics_existing_users# Import topics for users that already existed in the DB, not imported during this migration- puts '', "Importing topics for existing users"+ puts "", "Importing topics for existing users"topics = []@imported_topics_existing_users.each do |t|- t['id'] = IMPORT_TOPIC_ID_EXISITNG_PREFIX + t['id']+ t["id"] = IMPORT_TOPIC_ID_EXISITNG_PREFIX + t["id"]topics << tendcreate_posts(topics) do |t|{- id: t['id'],- user_id: t['user_id'], # This is a Discourse user ID- title: t['title'],- category: t['category_id'], # This is a Discourse category ID- raw: t['raw']+ id: t["id"],+ user_id: t["user_id"], # This is a Discourse user ID+ title: t["title"],+ category: t["category_id"], # This is a Discourse category ID+ raw: t["raw"],}endendend-if __FILE__ == $0- ImportScripts::CsvImporter.new.perform-end+ImportScripts::CsvImporter.new.perform if __FILE__ == $0# == CSV files format#diff --git a/script/import_scripts/csv_restore_staged_users.rb b/script/import_scripts/csv_restore_staged_users.rbindex 2145bcc3518..314004b8807 100755--- a/script/import_scripts/csv_restore_staged_users.rb+++ b/script/import_scripts/csv_restore_staged_users.rb@@ -6,10 +6,9 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Edit the constants and initialize method for your import data.class ImportScripts::CsvRestoreStagedUsers < ImportScripts::Base-- CSV_FILE_PATH = ENV['CSV_USER_FILE']- CSV_CUSTOM_FIELDS = ENV['CSV_CUSTOM_FIELDS']- CSV_EMAILS = ENV['CSV_EMAILS']+ CSV_FILE_PATH = ENV["CSV_USER_FILE"]+ CSV_CUSTOM_FIELDS = ENV["CSV_CUSTOM_FIELDS"]+ CSV_EMAILS = ENV["CSV_EMAILS"]BATCH_SIZE ||= 1000@@ -35,62 +34,51 @@ class ImportScripts::CsvRestoreStagedUsers < ImportScripts::Baseenddef username_for(name)- result = name.downcase.gsub(/[^a-z0-9\-\_]/, '')+ result = name.downcase.gsub(/[^a-z0-9\-\_]/, "")- if result.blank?- result = Digest::SHA1.hexdigest(name)[0...10]- end+ result = Digest::SHA1.hexdigest(name)[0...10] if result.blank?resultenddef get_email(id)email = nil- @imported_emails.each do |e|- if e["user_id"] == id- email = e["email"]- end- end+ @imported_emails.each { |e| email = e["email"] if e["user_id"] == id }enddef get_custom_fields(id)custom_fields = {}@imported_custom_fields.each do |cf|- if cf["user_id"] == id- custom_fields[cf["name"]] = cf["value"]- end+ custom_fields[cf["name"]] = cf["value"] if cf["user_id"] == idendcustom_fieldsenddef import_users- puts '', "Importing users"+ puts "", "Importing users"users = []@imported_users.each do |u|- email = get_email(u['id'])- custom_fields = get_custom_fields(u['id'])- u['email'] = email- u['custom_fields'] = custom_fields+ email = get_email(u["id"])+ custom_fields = get_custom_fields(u["id"])+ u["email"] = email+ u["custom_fields"] = custom_fieldsusers << uendusers.uniq!create_users(users) do |u|{- id: u['id'],- username: u['username'],- email: u['email'],- created_at: u['created_at'],- staged: u['staged'],- custom_fields: u['custom_fields'],+ id: u["id"],+ username: u["username"],+ email: u["email"],+ created_at: u["created_at"],+ staged: u["staged"],+ custom_fields: u["custom_fields"],}endend-end-if __FILE__ == $0- ImportScripts::CsvRestoreStagedUsers.new.perform-end+ImportScripts::CsvRestoreStagedUsers.new.perform if __FILE__ == $0diff --git a/script/import_scripts/discuz_x.rb b/script/import_scripts/discuz_x.rbindex 1b3cb5b8cbc..df6a28c2af1 100644--- a/script/import_scripts/discuz_x.rb+++ b/script/import_scripts/discuz_x.rb@@ -9,48 +9,47 @@# This script is tested only on Simplified Chinese Discuz! X instances# If you want to import data other than Simplified Chinese, email me.-require 'php_serialize'-require 'miro'-require 'mysql2'+require "php_serialize"+require "miro"+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::DiscuzX < ImportScripts::Base-DISCUZX_DB = "ultrax"- DB_TABLE_PREFIX = 'pre_'+ DB_TABLE_PREFIX = "pre_"BATCH_SIZE = 1000ORIGINAL_SITE_PREFIX = "oldsite.example.com/forums" # without http(s)://- NEW_SITE_PREFIX = "http://discourse.example.com" # with http:// or https://+ NEW_SITE_PREFIX = "http://discourse.example.com" # with http:// or https://# Set DISCUZX_BASE_DIR to the base directory of your discuz installation.- DISCUZX_BASE_DIR = '/var/www/discuz/upload'- AVATAR_DIR = '/uc_server/data/avatar'- ATTACHMENT_DIR = '/data/attachment/forum'- AUTHORIZED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'zip', 'rar', 'pdf']+ DISCUZX_BASE_DIR = "/var/www/discuz/upload"+ AVATAR_DIR = "/uc_server/data/avatar"+ ATTACHMENT_DIR = "/data/attachment/forum"+ AUTHORIZED_EXTENSIONS = %w[jpg jpeg png gif zip rar pdf]def initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- #password: "password",- database: DISCUZX_DB- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ #password: "password",+ database: DISCUZX_DB,+ )@first_post_id_by_topic_id = {}@internal_url_regexps = [- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/forum\.php\?mod=viewthread(?:&|&)tid=(?<tid>\d+)(?:[^\[\]\s]*)(?:pid=?(?<pid>\d+))?(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/viewthread\.php\?tid=(?<tid>\d+)(?:[^\[\]\s]*)(?:pid=?(?<pid>\d+))?(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/forum\.php\?mod=redirect(?:&|&)goto=findpost(?:&|&)pid=(?<pid>\d+)(?:&|&)ptid=(?<tid>\d+)(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/redirect\.php\?goto=findpost(?:&|&)pid=(?<pid>\d+)(?:&|&)ptid=(?<tid>\d+)(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/forumdisplay\.php\?fid=(?<fid>\d+)(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/forum\.php\?mod=forumdisplay(?:&|&)fid=(?<fid>\d+)(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/(?<action>index)\.php(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/(?<action>stats)\.php(?:[^\[\]\s]*)/,- /http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/misc.php\?mod=(?<mod>stat|ranklist)(?:[^\[\]\s]*)/+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/forum\.php\?mod=viewthread(?:&|&)tid=(?<tid>\d+)(?:[^\[\]\s]*)(?:pid=?(?<pid>\d+))?(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/viewthread\.php\?tid=(?<tid>\d+)(?:[^\[\]\s]*)(?:pid=?(?<pid>\d+))?(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/forum\.php\?mod=redirect(?:&|&)goto=findpost(?:&|&)pid=(?<pid>\d+)(?:&|&)ptid=(?<tid>\d+)(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/redirect\.php\?goto=findpost(?:&|&)pid=(?<pid>\d+)(?:&|&)ptid=(?<tid>\d+)(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/forumdisplay\.php\?fid=(?<fid>\d+)(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/forum\.php\?mod=forumdisplay(?:&|&)fid=(?<fid>\d+)(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/(?<action>index)\.php(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/(?<action>stats)\.php(?:[^\[\]\s]*)},+ %r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/misc.php\?mod=(?<mod>stat|ranklist)(?:[^\[\]\s]*)},]-enddef execute@@ -69,75 +68,84 @@ class ImportScripts::DiscuzX < ImportScripts::Base# find which group members can be granted as admindef get_knowledge_about_group- group_table = table_name 'common_usergroup'- result = mysql_query(- "SELECT groupid group_id, radminid role_id- FROM #{group_table};")+ group_table = table_name "common_usergroup"+ result =+ mysql_query(+ "SELECT groupid group_id, radminid role_id+ FROM #{group_table};",+ )@moderator_group_id = []@admin_group_id = []#@banned_group_id = [4,5] # 禁止的用户及其帖子均不导入,如果你想导入这些用户和帖子,请把这个数组清空。result.each do |group|- case group['role_id']+ case group["role_id"]when 1 # 管理员- @admin_group_id << group['group_id']- when 2, 3 # 超级版主、版主。如果你不希望原普通版主成为Discourse版主,把3去掉。- @moderator_group_id << group['group_id']+ @admin_group_id << group["group_id"]+ when 2,+ 3 # 超级版主、版主。如果你不希望原普通版主成为Discourse版主,把3去掉。+ @moderator_group_id << group["group_id"]endendenddef get_knowledge_about_category_slug@category_slug = {}- results = mysql_query("SELECT svalue value- FROM #{table_name 'common_setting'}- WHERE skey = 'forumkeys'")+ results =+ mysql_query(+ "SELECT svalue value+ FROM #{table_name "common_setting"}+ WHERE skey = 'forumkeys'",+ )return if results.size < 1- value = results.first['value']+ value = results.first["value"]return if value.blank?- PHP.unserialize(value).each do |category_import_id, slug|- next if slug.blank?- @category_slug[category_import_id] = slug- end+ PHP+ .unserialize(value)+ .each do |category_import_id, slug|+ next if slug.blank?+ @category_slug[category_import_id] = slug+ endenddef get_knowledge_about_duplicated_email@duplicated_email = {}- results = mysql_query(- "select a.uid uid, b.uid import_id from pre_common_member a+ results =+ mysql_query(+ "select a.uid uid, b.uid import_id from pre_common_member ajoin (select uid, email from pre_common_member group by email having count(email) > 1 order by uid asc) b USING(email)- where a.uid != b.uid")+ where a.uid != b.uid",+ )users = @lookup.instance_variable_get :@usersresults.each do |row|- @duplicated_email[row['uid']] = row['import_id']- user_id = users[row['import_id']]- if user_id- users[row['uid']] = user_id- end+ @duplicated_email[row["uid"]] = row["import_id"]+ user_id = users[row["import_id"]]+ users[row["uid"]] = user_id if user_idendenddef import_users- puts '', "creating users"+ puts "", "creating users"get_knowledge_about_group- sensitive_user_table = table_name 'ucenter_members'- user_table = table_name 'common_member'- profile_table = table_name 'common_member_profile'- status_table = table_name 'common_member_status'- forum_table = table_name 'common_member_field_forum'- home_table = table_name 'common_member_field_home'- total_count = mysql_query("SELECT count(*) count FROM #{user_table};").first['count']+ sensitive_user_table = table_name "ucenter_members"+ user_table = table_name "common_member"+ profile_table = table_name "common_member_profile"+ status_table = table_name "common_member_status"+ forum_table = table_name "common_member_field_forum"+ home_table = table_name "common_member_field_home"+ total_count = mysql_query("SELECT count(*) count FROM #{user_table};").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT u.uid id, u.username username, u.email email, u.groupid group_id,+ results =+ mysql_query(+ "SELECT u.uid id, u.username username, u.email email, u.groupid group_id,su.regdate regdate, su.password password_hash, su.salt salt,s.regip regip, s.lastip last_visit_ip, s.lastvisit last_visit_time, s.lastpost last_posted_at, s.lastsendmail last_emailed_at,u.emailstatus email_confirmed, u.avatarstatus avatar_exists,@@ -154,7 +162,8 @@ class ImportScripts::DiscuzX < ImportScripts::BaseLEFT JOIN #{home_table} h USING(uid)ORDER BY u.uid ASCLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1@@ -162,147 +171,233 @@ class ImportScripts::DiscuzX < ImportScripts::Base# next if all_records_exist? :users, users.map {|u| u["id"].to_i}create_users(results, total: total_count, offset: offset) do |user|- { id: user['id'],- email: user['email'],- username: user['username'],- name: first_exists(user['realname'], user['customstatus'], user['username']),- import_pass: user['password_hash'],+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ name: first_exists(user["realname"], user["customstatus"], user["username"]),+ import_pass: user["password_hash"],active: true,- salt: user['salt'],+ salt: user["salt"],# TODO: title: user['customstatus'], # move custom title to name since discourse can't let user custom title https://meta.discourse.org/t/let-users-custom-their-title/37626- created_at: user['regdate'] ? Time.zone.at(user['regdate']) : nil,- registration_ip_address: user['regip'],- ip_address: user['last_visit_ip'],- last_seen_at: user['last_visit_time'],- last_emailed_at: user['last_emailed_at'],- last_posted_at: user['last_posted_at'],- moderator: @moderator_group_id.include?(user['group_id']),- admin: @admin_group_id.include?(user['group_id']),- website: (user['website'] && user['website'].include?('.')) ? user['website'].strip : (user['qq'] && user['qq'].strip == (user['qq'].strip.to_i) && user['qq'].strip.to_i > (10000)) ? 'http://user.qzone.qq.com/' + user['qq'].strip : nil,- bio_raw: first_exists((user['bio'] && CGI.unescapeHTML(user['bio'])), user['sightml'], user['spacenote']).strip[0, 3000],- location: first_exists(user['address'], (!user['resideprovince'].blank? ? [user['resideprovince'], user['residecity'], user['residedist'], user['residecommunity']] : [user['birthprovince'], user['birthcity'], user['birthdist'], user['birthcommunity']]).reject { |location|location.blank? }.join(' ')),- post_create_action: lambda do |newmember|- if user['avatar_exists'] == (1) && newmember.uploaded_avatar_id.blank?- path, filename = discuzx_avatar_fullpath(user['id'])- if path- begin- upload = create_upload(newmember.id, path, filename)- if !upload.nil? && upload.persisted?- newmember.import_mode = false- newmember.create_user_avatar- newmember.import_mode = true- newmember.user_avatar.update(custom_upload_id: upload.id)- newmember.update(uploaded_avatar_id: upload.id)- else- puts "Error: Upload did not persist!"+ created_at: user["regdate"] ? Time.zone.at(user["regdate"]) : nil,+ registration_ip_address: user["regip"],+ ip_address: user["last_visit_ip"],+ last_seen_at: user["last_visit_time"],+ last_emailed_at: user["last_emailed_at"],+ last_posted_at: user["last_posted_at"],+ moderator: @moderator_group_id.include?(user["group_id"]),+ admin: @admin_group_id.include?(user["group_id"]),+ website:+ (user["website"] && user["website"].include?(".")) ?+ user["website"].strip :+ if (+ user["qq"] && user["qq"].strip == (user["qq"].strip.to_i) &&+ user["qq"].strip.to_i > (10_000)+ )+ "http://user.qzone.qq.com/" + user["qq"].strip+ else+ nil+ end,+ bio_raw:+ first_exists(+ (user["bio"] && CGI.unescapeHTML(user["bio"])),+ user["sightml"],+ user["spacenote"],+ ).strip[+ 0,+ 3000+ ],+ location:+ first_exists(+ user["address"],+ (+ if !user["resideprovince"].blank?+ [+ user["resideprovince"],+ user["residecity"],+ user["residedist"],+ user["residecommunity"],+ ]+ else+ [+ user["birthprovince"],+ user["birthcity"],+ user["birthdist"],+ user["birthcommunity"],+ ]+ end+ ).reject { |location| location.blank? }.join(" "),+ ),+ post_create_action:+ lambda do |newmember|+ if user["avatar_exists"] == (1) && newmember.uploaded_avatar_id.blank?+ path, filename = discuzx_avatar_fullpath(user["id"])+ if path+ begin+ upload = create_upload(newmember.id, path, filename)+ if !upload.nil? && upload.persisted?+ newmember.import_mode = false+ newmember.create_user_avatar+ newmember.import_mode = true+ newmember.user_avatar.update(custom_upload_id: upload.id)+ newmember.update(uploaded_avatar_id: upload.id)+ else+ puts "Error: Upload did not persist!"+ end+ rescue SystemCallError => err+ puts "Could not import avatar: #{err.message}"end- rescue SystemCallError => err- puts "Could not import avatar: #{err.message}"endend- end- if !user['spacecss'].blank? && newmember.user_profile.profile_background_upload.blank?- # profile background- if matched = user['spacecss'].match(/body\s*{[^}]*url\('?(.+?)'?\)/i)- body_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).last- end- if matched = user['spacecss'].match(/#hd\s*{[^}]*url\('?(.+?)'?\)/i)- header_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).last- end- if matched = user['spacecss'].match(/.blocktitle\s*{[^}]*url\('?(.+?)'?\)/i)- blocktitle_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).last- end- if matched = user['spacecss'].match(/#ct\s*{[^}]*url\('?(.+?)'?\)/i)- content_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).last- end-- if body_background || header_background || blocktitle_background || content_background- profile_background = first_exists(header_background, body_background, content_background, blocktitle_background)- card_background = first_exists(content_background, body_background, header_background, blocktitle_background)- upload = create_upload(newmember.id, File.join(DISCUZX_BASE_DIR, profile_background), File.basename(profile_background))- if upload- newmember.user_profile.upload_profile_background upload- else- puts "WARNING: #{user['username']} (UID: #{user['id']}) profile_background file did not persist!"+ if !user["spacecss"].blank? && newmember.user_profile.profile_background_upload.blank?+ # profile background+ if matched = user["spacecss"].match(/body\s*{[^}]*url\('?(.+?)'?\)/i)+ body_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).lastend- upload = create_upload(newmember.id, File.join(DISCUZX_BASE_DIR, card_background), File.basename(card_background))- if upload- newmember.user_profile.upload_card_background upload- else- puts "WARNING: #{user['username']} (UID: #{user['id']}) card_background file did not persist!"+ if matched = user["spacecss"].match(/#hd\s*{[^}]*url\('?(.+?)'?\)/i)+ header_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).last+ end+ if matched = user["spacecss"].match(/.blocktitle\s*{[^}]*url\('?(.+?)'?\)/i)+ blocktitle_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).last+ end+ if matched = user["spacecss"].match(/#ct\s*{[^}]*url\('?(.+?)'?\)/i)+ content_background = matched[1].split(ORIGINAL_SITE_PREFIX, 2).last+ end++ if body_background || header_background || blocktitle_background ||+ content_background+ profile_background =+ first_exists(+ header_background,+ body_background,+ content_background,+ blocktitle_background,+ )+ card_background =+ first_exists(+ content_background,+ body_background,+ header_background,+ blocktitle_background,+ )+ upload =+ create_upload(+ newmember.id,+ File.join(DISCUZX_BASE_DIR, profile_background),+ File.basename(profile_background),+ )+ if upload+ newmember.user_profile.upload_profile_background upload+ else+ puts "WARNING: #{user["username"]} (UID: #{user["id"]}) profile_background file did not persist!"+ end+ upload =+ create_upload(+ newmember.id,+ File.join(DISCUZX_BASE_DIR, card_background),+ File.basename(card_background),+ )+ if upload+ newmember.user_profile.upload_card_background upload+ else+ puts "WARNING: #{user["username"]} (UID: #{user["id"]}) card_background file did not persist!"+ endendend- end- # we don't send email to the unconfirmed user- newmember.update(email_digests: user['email_confirmed'] == 1) if newmember.email_digests- newmember.update(name: '') if !newmember.name.blank? && newmember.name == (newmember.username)- end+ # we don't send email to the unconfirmed user+ if newmember.email_digests+ newmember.update(email_digests: user["email_confirmed"] == 1)+ end+ if !newmember.name.blank? && newmember.name == (newmember.username)+ newmember.update(name: "")+ end+ end,}endendenddef import_categories- puts '', "creating categories"+ puts "", "creating categories"get_knowledge_about_category_slug- forums_table = table_name 'forum_forum'- forums_data_table = table_name 'forum_forumfield'+ forums_table = table_name "forum_forum"+ forums_data_table = table_name "forum_forumfield"- results = mysql_query("+ results =+ mysql_query(+ "SELECT f.fid id, f.fup parent_id, f.name, f.type type, f.status status, f.displayorder position,d.description description, d.rules rules, d.icon, d.extra extraFROM #{forums_table} fLEFT JOIN #{forums_data_table} d USING(fid)ORDER BY parent_id ASC, id ASC- ")+ ",+ )max_position = Category.all.max_by(&:position).positioncreate_categories(results) do |row|- next if row['type'] == ('group') || row['status'] == (2) # or row['status'].to_i == 3 # 如果不想导入群组,取消注释- extra = PHP.unserialize(row['extra']) if !row['extra'].blank?- if extra && !extra["namecolor"].blank?- color = extra["namecolor"][1, 6]- end+ next if row["type"] == ("group") || row["status"] == (2) # or row['status'].to_i == 3 # 如果不想导入群组,取消注释+ extra = PHP.unserialize(row["extra"]) if !row["extra"].blank?+ color = extra["namecolor"][1, 6] if extra && !extra["namecolor"].blank?Category.all.max_by(&:position).positionh = {- id: row['id'],- name: row['name'],- description: row['description'],- position: row['position'].to_i + max_position,+ id: row["id"],+ name: row["name"],+ description: row["description"],+ position: row["position"].to_i + max_position,color: color,- post_create_action: lambda do |category|- if slug = @category_slug[row['id']]- category.update(slug: slug)- end+ post_create_action:+ lambda do |category|+ if slug = @category_slug[row["id"]]+ category.update(slug: slug)+ end- raw = process_discuzx_post(row['rules'], nil)- if @bbcode_to_md- raw = raw.bbcode_to_md(false) rescue raw- end- category.topic.posts.first.update_attribute(:raw, raw)- if !row['icon'].empty?- upload = create_upload(Discourse::SYSTEM_USER_ID, File.join(DISCUZX_BASE_DIR, ATTACHMENT_DIR, '../common', row['icon']), File.basename(row['icon']))- if upload- category.uploaded_logo_id = upload.id- # FIXME: I don't know how to get '/shared' by script. May change to Rails.root- category.color = Miro::DominantColors.new(File.join('/shared', upload.url)).to_hex.first[1, 6] if !color- category.save!+ raw = process_discuzx_post(row["rules"], nil)+ if @bbcode_to_md+ raw =+ begin+ raw.bbcode_to_md(false)+ rescue StandardError+ raw+ end+ end+ category.topic.posts.first.update_attribute(:raw, raw)+ if !row["icon"].empty?+ upload =+ create_upload(+ Discourse::SYSTEM_USER_ID,+ File.join(DISCUZX_BASE_DIR, ATTACHMENT_DIR, "../common", row["icon"]),+ File.basename(row["icon"]),+ )+ if upload+ category.uploaded_logo_id = upload.id+ # FIXME: I don't know how to get '/shared' by script. May change to Rails.root+ category.color =+ Miro::DominantColors.new(File.join("/shared", upload.url)).to_hex.first[+ 1,+ 6+ ] if !color+ category.save!+ endend- end- if row['status'] == (0) || row['status'] == (3)- SiteSetting.default_categories_muted = [SiteSetting.default_categories_muted, category.id].reject(&:blank?).join("|")- end- category- end+ if row["status"] == (0) || row["status"] == (3)+ SiteSetting.default_categories_muted = [+ SiteSetting.default_categories_muted,+ category.id,+ ].reject(&:blank?).join("|")+ end+ category+ end,}- if row['parent_id'].to_i > 0- h[:parent_category_id] = category_id_from_imported_category_id(row['parent_id'])+ if row["parent_id"].to_i > 0+ h[:parent_category_id] = category_id_from_imported_category_id(row["parent_id"])endhend@@ -311,14 +406,16 @@ class ImportScripts::DiscuzX < ImportScripts::Basedef import_postsputs "", "creating topics and posts"- users_table = table_name 'common_member'- posts_table = table_name 'forum_post'- topics_table = table_name 'forum_thread'+ users_table = table_name "common_member"+ posts_table = table_name "forum_post"+ topics_table = table_name "forum_thread"- total_count = mysql_query("SELECT count(*) count FROM #{posts_table}").first['count']+ total_count = mysql_query("SELECT count(*) count FROM #{posts_table}").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.pid id,p.tid topic_id,t.fid category_id,@@ -336,7 +433,8 @@ class ImportScripts::DiscuzX < ImportScripts::BaseORDER BY id ASC, topic_id ASCLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )# u.status != -1 AND u.groupid != 4 AND u.groupid != 5 用户未被锁定、禁访或禁言。在现实中的 Discuz 论坛,禁止的用户通常是广告机或驱逐的用户,这些不需要导入。break if results.size < 1@@ -346,63 +444,70 @@ class ImportScripts::DiscuzX < ImportScripts::Baseskip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_discuzx_post(m['raw'], m['id'])- mapped[:created_at] = Time.zone.at(m['post_time'])- mapped[:tags] = m['tags']+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_discuzx_post(m["raw"], m["id"])+ mapped[:created_at] = Time.zone.at(m["post_time"])+ mapped[:tags] = m["tags"]- if m['id'] == m['first_id']- mapped[:category] = category_id_from_imported_category_id(m['category_id'])- mapped[:title] = CGI.unescapeHTML(m['title'])+ if m["id"] == m["first_id"]+ mapped[:category] = category_id_from_imported_category_id(m["category_id"])+ mapped[:title] = CGI.unescapeHTML(m["title"])- if m['special'] == 1- results = mysql_query("+ if m["special"] == 1+ results =+ mysql_query(+ "SELECT multiple, maxchoices- FROM #{table_name 'forum_poll'}- WHERE tid = #{m['topic_id']}")+ FROM #{table_name "forum_poll"}+ WHERE tid = #{m["topic_id"]}",+ )poll = results.first || {}- results = mysql_query("+ results =+ mysql_query(+ "SELECT polloption- FROM #{table_name 'forum_polloption'}- WHERE tid = #{m['topic_id']}- ORDER BY displayorder")+ FROM #{table_name "forum_polloption"}+ WHERE tid = #{m["topic_id"]}+ ORDER BY displayorder",+ )if results.empty?- puts "WARNING: can't find poll options for topic #{m['topic_id']}, skip poll"+ puts "WARNING: can't find poll options for topic #{m["topic_id"]}, skip poll"else- mapped[:raw].prepend "[poll#{poll['multiple'] ? ' type=multiple' : ''}#{poll['maxchoices'] > 0 ? " max=#{poll['maxchoices']}" : ''}]\n#{results.map { |option|'- ' + option['polloption'] }.join("\n")}\n[/poll]\n"+ mapped[+ :raw+ ].prepend "[poll#{poll["multiple"] ? " type=multiple" : ""}#{poll["maxchoices"] > 0 ? " max=#{poll["maxchoices"]}" : ""}]\n#{results.map { |option| "- " + option["polloption"] }.join("\n")}\n[/poll]\n"endendelse- parent = topic_lookup_from_imported_post_id(m['first_id'])+ parent = topic_lookup_from_imported_post_id(m["first_id"])if parentmapped[:topic_id] = parent[:topic_id]- reply_post_import_id = find_post_id_by_quote_number(m['raw'])+ reply_post_import_id = find_post_id_by_quote_number(m["raw"])if reply_post_import_idpost_id = post_id_from_imported_post_id(reply_post_import_id.to_i)if (post = Post.find_by(id: post_id))if post.topic_id == mapped[:topic_id]mapped[:reply_to_post_number] = post.post_numberelse- puts "post #{m['id']} reply to another topic, skip reply"+ puts "post #{m["id"]} reply to another topic, skip reply"endelse- puts "post #{m['id']} reply to not exists post #{reply_post_import_id}, skip reply"+ puts "post #{m["id"]} reply to not exists post #{reply_post_import_id}, skip reply"endendelse- puts "Parent topic #{m['topic_id']} doesn't exist. Skipping #{m['id']}: #{m['title'][0..40]}"+ puts "Parent topic #{m["topic_id"]} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"skip = trueend-end- if m['status'] & 1 == 1 || mapped[:raw].blank?+ if m["status"] & 1 == 1 || mapped[:raw].blank?mapped[:post_create_action] = lambda do |action_post|PostDestroyer.new(Discourse.system_user, action_post).perform_deleteend- elsif (m['status'] & 2) >> 1 == 1 # waiting for approve+ elsif (m["status"] & 2) >> 1 == 1 # waiting for approvemapped[:post_create_action] = lambda do |action_post|PostActionCreator.notify_user(Discourse.system_user, action_post)end@@ -413,42 +518,47 @@ class ImportScripts::DiscuzX < ImportScripts::Baseenddef import_bookmarks- puts '', 'creating bookmarks'- favorites_table = table_name 'home_favorite'- posts_table = table_name 'forum_post'-- total_count = mysql_query("SELECT count(*) count FROM #{favorites_table} WHERE idtype = 'tid'").first['count']+ puts "", "creating bookmarks"+ favorites_table = table_name "home_favorite"+ posts_table = table_name "forum_post"++ total_count =+ mysql_query("SELECT count(*) count FROM #{favorites_table} WHERE idtype = 'tid'").first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.pid post_id, f.uid user_idFROM #{favorites_table} fJOIN #{posts_table} p ON f.id = p.tidWHERE f.idtype = 'tid' AND p.firstLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1# next if all_records_exist?create_bookmarks(results, total: total_count, offset: offset) do |row|- {- user_id: row['user_id'],- post_id: row['post_id']- }+ { user_id: row["user_id"], post_id: row["post_id"] }endendenddef import_private_messages- puts '', 'creating private messages'+ puts "", "creating private messages"- pm_indexes = table_name 'ucenter_pm_indexes'- pm_messages = table_name 'ucenter_pm_messages'- total_count = mysql_query("SELECT count(*) count FROM #{pm_indexes}").first['count']+ pm_indexes = table_name "ucenter_pm_indexes"+ pm_messages = table_name "ucenter_pm_messages"+ total_count = mysql_query("SELECT count(*) count FROM #{pm_indexes}").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT pmid id, plid thread_id, authorid user_id, message, dateline created_atFROM #{pm_messages}_1UNION SELECT pmid id, plid thread_id, authorid user_id, message, dateline created_at@@ -469,7 +579,8 @@ class ImportScripts::DiscuzX < ImportScripts::BaseFROM #{pm_messages}_9ORDER BY thread_id ASC, id ASCLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1@@ -479,35 +590,47 @@ class ImportScripts::DiscuzX < ImportScripts::Baseskip = falsemapped = {}- mapped[:id] = "pm:#{m['id']}"- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_discuzx_post(m['message'], m['id'])- mapped[:created_at] = Time.zone.at(m['created_at'])- thread_id = "pm_#{m['thread_id']}"+ mapped[:id] = "pm:#{m["id"]}"+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_discuzx_post(m["message"], m["id"])+ mapped[:created_at] = Time.zone.at(m["created_at"])+ thread_id = "pm_#{m["thread_id"]}"- if is_first_pm(m['id'], m['thread_id'])+ if is_first_pm(m["id"], m["thread_id"])# find the title from list table- pm_thread = mysql_query("+ pm_thread =+ mysql_query(+ "SELECT plid thread_id, subject- FROM #{table_name 'ucenter_pm_lists'}- WHERE plid = #{m['thread_id']};").first- mapped[:title] = pm_thread['subject']+ FROM #{table_name "ucenter_pm_lists"}+ WHERE plid = #{m["thread_id"]};",+ ).first+ mapped[:title] = pm_thread["subject"]mapped[:archetype] = Archetype.private_message# Find the users who are part of this private message.- import_user_ids = mysql_query("+ import_user_ids =+ mysql_query(+ "SELECT plid thread_id, uid user_id- FROM #{table_name 'ucenter_pm_members'}- WHERE plid = #{m['thread_id']};- ").map { |r| r['user_id'] }.uniq-- mapped[:target_usernames] = import_user_ids.map! do |import_user_id|- import_user_id.to_s == m['user_id'].to_s ? nil : User.find_by(id: user_id_from_imported_user_id(import_user_id)).try(:username)- end.compact+ FROM #{table_name "ucenter_pm_members"}+ WHERE plid = #{m["thread_id"]};+ ",+ ).map { |r| r["user_id"] }.uniq++ mapped[:target_usernames] = import_user_ids+ .map! do |import_user_id|+ if import_user_id.to_s == m["user_id"].to_s+ nil+ else+ User.find_by(id: user_id_from_imported_user_id(import_user_id)).try(:username)+ end+ end+ .compactif mapped[:target_usernames].empty? # pm with yourself?skip = true- puts "Skipping pm:#{m['id']} due to no target"+ puts "Skipping pm:#{m["id"]} due to no target"else@first_post_id_by_topic_id[thread_id] = mapped[:id]end@@ -523,22 +646,24 @@ class ImportScripts::DiscuzX < ImportScripts::Baseskip ? nil : mappedend-endend# search for first pm id for the series of pmdef is_first_pm(pm_id, thread_id)- result = mysql_query("+ result =+ mysql_query(+ "SELECT pmid id- FROM #{table_name 'ucenter_pm_indexes'}+ FROM #{table_name "ucenter_pm_indexes"}WHERE plid = #{thread_id}- ORDER BY id")- result.first['id'].to_s == pm_id.to_s+ ORDER BY id",+ )+ result.first["id"].to_s == pm_id.to_senddef process_and_upload_inline_images(raw)- inline_image_regex = /\[img\]([\s\S]*?)\[\/img\]/+ inline_image_regex = %r{\[img\]([\s\S]*?)\[/img\]}s = raw.dup@@ -549,7 +674,6 @@ class ImportScripts::DiscuzX < ImportScripts::Baseupload, filename = upload_inline_image dataupload ? html_for_upload(upload, filename) : nilend-enddef process_discuzx_post(raw, import_id)@@ -559,10 +683,18 @@ class ImportScripts::DiscuzX < ImportScripts::Base# Strip the quote# [quote] quotation includes the topic which is the same as reply to in Discourse# We get the pid to find the post number the post reply to. So it can be stripped- s = s.gsub(/\[b\]回复 \[url=forum.php\?mod=redirect&goto=findpost&pid=\d+&ptid=\d+\].* 的帖子\[\/url\]\[\/b\]/i, '').strip- s = s.gsub(/\[b\]回复 \[url=https?:\/\/#{ORIGINAL_SITE_PREFIX}\/redirect.php\?goto=findpost&pid=\d+&ptid=\d+\].*?\[\/url\].*?\[\/b\]/i, '').strip-- s.gsub!(/\[quote\](.*)?\[\/quote\]/im) do |matched|+ s =+ s.gsub(+ %r{\[b\]回复 \[url=forum.php\?mod=redirect&goto=findpost&pid=\d+&ptid=\d+\].* 的帖子\[/url\]\[/b\]}i,+ "",+ ).strip+ s =+ s.gsub(+ %r{\[b\]回复 \[url=https?://#{ORIGINAL_SITE_PREFIX}/redirect.php\?goto=findpost&pid=\d+&ptid=\d+\].*?\[/url\].*?\[/b\]}i,+ "",+ ).strip++ s.gsub!(%r{\[quote\](.*)?\[/quote\]}im) do |matched|content = $1post_import_id = find_post_id_by_quote_number(content)if post_import_id@@ -578,73 +710,93 @@ class ImportScripts::DiscuzX < ImportScripts::Baseendend- s.gsub!(/\[size=2\]\[color=#999999\].*? 发表于 [\d\-\: ]*\[\/color\] \[url=forum.php\?mod=redirect&goto=findpost&pid=\d+&ptid=\d+\].*?\[\/url\]\[\/size\]/i, '')- s.gsub!(/\[size=2\]\[color=#999999\].*? 发表于 [\d\-\: ]*\[\/color\] \[url=https?:\/\/#{ORIGINAL_SITE_PREFIX}\/redirect.php\?goto=findpost&pid=\d+&ptid=\d+\].*?\[\/url\]\[\/size\]/i, '')+ s.gsub!(+ %r{\[size=2\]\[color=#999999\].*? 发表于 [\d\-\: ]*\[/color\] \[url=forum.php\?mod=redirect&goto=findpost&pid=\d+&ptid=\d+\].*?\[/url\]\[/size\]}i,+ "",+ )+ s.gsub!(+ %r{\[size=2\]\[color=#999999\].*? 发表于 [\d\-\: ]*\[/color\] \[url=https?://#{ORIGINAL_SITE_PREFIX}/redirect.php\?goto=findpost&pid=\d+&ptid=\d+\].*?\[/url\]\[/size\]}i,+ "",+ )# convert quote- s.gsub!(/\[quote\](.*?)\[\/quote\]/m) { "\n" + ($1.strip).gsub(/^/, '> ') + "\n" }+ s.gsub!(%r{\[quote\](.*?)\[/quote\]}m) { "\n" + ($1.strip).gsub(/^/, "> ") + "\n" }# truncate line space, preventing line starting with many blanks to be parsed as code blocks- s.gsub!(/^ {4,}/, ' ')+ s.gsub!(/^ {4,}/, " ")# TODO: Much better to use bbcode-to-md gem# Convert image bbcode with width and height- s.gsub!(/\[img[^\]]*\]https?:\/\/#{ORIGINAL_SITE_PREFIX}\/(.*)\[\/img\]/i, '[x-attach]\1[/x-attach]') # dont convert attachment- s.gsub!(/<img[^>]*src="https?:\/\/#{ORIGINAL_SITE_PREFIX}\/(.*)".*?>/i, '[x-attach]\1[/x-attach]') # dont convert attachment- s.gsub!(/\[img[^\]]*\]https?:\/\/www\.touhou\.cc\/blog\/(.*)\[\/img\]/i, '[x-attach]../blog/\1[/x-attach]') # 私货- s.gsub!(/\[img[^\]]*\]https?:\/\/www\.touhou\.cc\/ucenter\/avatar.php\?uid=(\d+)[^\]]*\[\/img\]/i) { "[x-attach]#{discuzx_avatar_fullpath($1, false)[0]}[/x-attach]" } # 私货- s.gsub!(/\[img=(\d+),(\d+)\]([^\]]*)\[\/img\]/i, '<img width="\1" height="\2" src="\3">')- s.gsub!(/\[img\]([^\]]*)\[\/img\]/i, '<img src="\1">')-- s.gsub!(/\[qq\]([^\]]*)\[\/qq\]/i, '<a href="http://wpa.qq.com/msgrd?V=3&Uin=\1&Site=[Discuz!]&from=discuz&Menu=yes" target="_blank"><!--<img src="static/image/common/qq_big.gif" border="0">-->QQ 交谈</a>')-- s.gsub!(/\[email\]([^\]]*)\[\/email\]/i, '[url=mailto:\1]\1[/url]') # bbcode-to-md can convert it- s.gsub!(/\[s\]([^\]]*)\[\/s\]/i, '<s>\1</s>')- s.gsub!(/\[sup\]([^\]]*)\[\/sup\]/i, '<sup>\1</sup>')- s.gsub!(/\[sub\]([^\]]*)\[\/sub\]/i, '<sub>\1</sub>')+ s.gsub!(+ %r{\[img[^\]]*\]https?://#{ORIGINAL_SITE_PREFIX}/(.*)\[/img\]}i,+ '[x-attach]\1[/x-attach]',+ ) # dont convert attachment+ s.gsub!(+ %r{<img[^>]*src="https?://#{ORIGINAL_SITE_PREFIX}/(.*)".*?>}i,+ '[x-attach]\1[/x-attach]',+ ) # dont convert attachment+ s.gsub!(+ %r{\[img[^\]]*\]https?://www\.touhou\.cc/blog/(.*)\[/img\]}i,+ '[x-attach]../blog/\1[/x-attach]',+ ) # 私货+ s.gsub!(+ %r{\[img[^\]]*\]https?://www\.touhou\.cc/ucenter/avatar.php\?uid=(\d+)[^\]]*\[/img\]}i,+ ) { "[x-attach]#{discuzx_avatar_fullpath($1, false)[0]}[/x-attach]" } # 私货+ s.gsub!(%r{\[img=(\d+),(\d+)\]([^\]]*)\[/img\]}i, '<img width="\1" height="\2" src="\3">')+ s.gsub!(%r{\[img\]([^\]]*)\[/img\]}i, '<img src="\1">')++ s.gsub!(+ %r{\[qq\]([^\]]*)\[/qq\]}i,+ '<a href="http://wpa.qq.com/msgrd?V=3&Uin=\1&Site=[Discuz!]&from=discuz&Menu=yes" target="_blank"><!--<img src="static/image/common/qq_big.gif" border="0">-->QQ 交谈</a>',+ )++ s.gsub!(%r{\[email\]([^\]]*)\[/email\]}i, '[url=mailto:\1]\1[/url]') # bbcode-to-md can convert it+ s.gsub!(%r{\[s\]([^\]]*)\[/s\]}i, '<s>\1</s>')+ s.gsub!(%r{\[sup\]([^\]]*)\[/sup\]}i, '<sup>\1</sup>')+ s.gsub!(%r{\[sub\]([^\]]*)\[/sub\]}i, '<sub>\1</sub>')s.gsub!(/\[hr\]/i, "\n---\n")# remove the media tag- s.gsub!(/\[\/?media[^\]]*\]/i, "\n")- s.gsub!(/\[\/?flash[^\]]*\]/i, "\n")- s.gsub!(/\[\/?audio[^\]]*\]/i, "\n")- s.gsub!(/\[\/?video[^\]]*\]/i, "\n")+ s.gsub!(%r{\[/?media[^\]]*\]}i, "\n")+ s.gsub!(%r{\[/?flash[^\]]*\]}i, "\n")+ s.gsub!(%r{\[/?audio[^\]]*\]}i, "\n")+ s.gsub!(%r{\[/?video[^\]]*\]}i, "\n")# Remove the font, p and backcolor tag# Discourse doesn't support the font tag- s.gsub!(/\[font=[^\]]*?\]/i, '')- s.gsub!(/\[\/font\]/i, '')- s.gsub!(/\[p=[^\]]*?\]/i, '')- s.gsub!(/\[\/p\]/i, '')- s.gsub!(/\[backcolor=[^\]]*?\]/i, '')- s.gsub!(/\[\/backcolor\]/i, '')+ s.gsub!(/\[font=[^\]]*?\]/i, "")+ s.gsub!(%r{\[/font\]}i, "")+ s.gsub!(/\[p=[^\]]*?\]/i, "")+ s.gsub!(%r{\[/p\]}i, "")+ s.gsub!(/\[backcolor=[^\]]*?\]/i, "")+ s.gsub!(%r{\[/backcolor\]}i, "")# Remove the size tag# I really have no idea what is this- s.gsub!(/\[size=[^\]]*?\]/i, '')- s.gsub!(/\[\/size\]/i, '')+ s.gsub!(/\[size=[^\]]*?\]/i, "")+ s.gsub!(%r{\[/size\]}i, "")# Remove the color tag- s.gsub!(/\[color=[^\]]*?\]/i, '')- s.gsub!(/\[\/color\]/i, '')+ s.gsub!(/\[color=[^\]]*?\]/i, "")+ s.gsub!(%r{\[/color\]}i, "")# Remove the hide tag- s.gsub!(/\[\/?hide\]/i, '')- s.gsub!(/\[\/?free[^\]]*\]/i, "\n")+ s.gsub!(%r{\[/?hide\]}i, "")+ s.gsub!(%r{\[/?free[^\]]*\]}i, "\n")# Remove the align tag# still don't know what it iss.gsub!(/\[align=[^\]]*?\]/i, "\n")- s.gsub!(/\[\/align\]/i, "\n")+ s.gsub!(%r{\[/align\]}i, "\n")s.gsub!(/\[float=[^\]]*?\]/i, "\n")- s.gsub!(/\[\/float\]/i, "\n")+ s.gsub!(%r{\[/float\]}i, "\n")# Convert code- s.gsub!(/\[\/?code\]/i, "\n```\n")+ s.gsub!(%r{\[/?code\]}i, "\n```\n")# The edit notice should be removed# example: 本帖最后由 Helloworld 于 2015-1-28 22:05 编辑- s.gsub!(/\[i=s\] 本帖最后由[\s\S]*?编辑 \[\/i\]/, '')+ s.gsub!(%r{\[i=s\] 本帖最后由[\s\S]*?编辑 \[/i\]}, "")# Convert the custom smileys to emojis# `{:cry:}` to `:cry`@@ -653,35 +805,71 @@ class ImportScripts::DiscuzX < ImportScripts::Base# Replace internal forum links that aren't in the <!-- l --> format# convert list tags to ul and list=1 tags to ol# (basically, we're only missing list=a here...)- s.gsub!(/\[list\](.*?)\[\/list:u\]/m, '[ul]\1[/ul]')- s.gsub!(/\[list=1\](.*?)\[\/list:o\]/m, '[ol]\1[/ol]')+ s.gsub!(%r{\[list\](.*?)\[/list:u\]}m, '[ul]\1[/ul]')+ s.gsub!(%r{\[list=1\](.*?)\[/list:o\]}m, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:- s.gsub!(/\[\*\](.*?)\[\/\*:m\]/, '[li]\1[/li]')+ s.gsub!(%r{\[\*\](.*?)\[/\*:m\]}, '[li]\1[/li]')# Discuz can create PM out of a post, which will generates like# [url=http://example.com/forum.php?mod=redirect&goto=findpost&pid=111&ptid=11][b]关于您在“主题名称”的帖子[/b][/url]- s.gsub!(pm_url_regexp) do |discuzx_link|- replace_internal_link(discuzx_link, $1)- end+ s.gsub!(pm_url_regexp) { |discuzx_link| replace_internal_link(discuzx_link, $1) }# [url][b]text[/b][/url] to **[url]text[/url]**- s.gsub!(/(\[url=[^\[\]]*?\])\[b\](\S*)\[\/b\](\[\/url\])/, '**\1\2\3**')+ s.gsub!(%r{(\[url=[^\[\]]*?\])\[b\](\S*)\[/b\](\[/url\])}, '**\1\2\3**')@internal_url_regexps.each do |internal_url_regexp|s.gsub!(internal_url_regexp) do |discuzx_link|- replace_internal_link(discuzx_link, ($~[:tid].to_i rescue nil), ($~[:pid].to_i rescue nil), ($~[:fid].to_i rescue nil), ($~[:action] rescue nil))+ replace_internal_link(+ discuzx_link,+ (+ begin+ $~[:tid].to_i+ rescue StandardError+ nil+ end+ ),+ (+ begin+ $~[:pid].to_i+ rescue StandardError+ nil+ end+ ),+ (+ begin+ $~[:fid].to_i+ rescue StandardError+ nil+ end+ ),+ (+ begin+ $~[:action]+ rescue StandardError+ nil+ end+ ),+ )endend# @someone without the url- s.gsub!(/@\[url=[^\[\]]*?\](\S*)\[\/url\]/i, '@\1')+ s.gsub!(%r{@\[url=[^\[\]]*?\](\S*)\[/url\]}i, '@\1')- s.scan(/http(?:s)?:\/\/#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}\/[^\[\]\s]*/) { |link|puts "WARNING: post #{import_id} can't replace internal url #{link}" }+ s.scan(%r{http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/[^\[\]\s]*}) do |link|+ puts "WARNING: post #{import_id} can't replace internal url #{link}"+ ends.stripend- def replace_internal_link(discuzx_link, import_topic_id, import_post_id, import_category_id, action)+ def replace_internal_link(+ discuzx_link,+ import_topic_id,+ import_post_id,+ import_category_id,+ action+ )if import_post_idpost_id = post_id_from_imported_post_id import_post_idif post_id@@ -691,15 +879,17 @@ class ImportScripts::DiscuzX < ImportScripts::Baseendif import_topic_id-- results = mysql_query("SELECT pid- FROM #{table_name 'forum_post'}+ results =+ mysql_query(+ "SELECT pid+ FROM #{table_name "forum_post"}WHERE tid = #{import_topic_id} AND first- LIMIT 1")+ LIMIT 1",+ )return discuzx_link unless results.size > 0- linked_post_id = results.first['pid']+ linked_post_id = results.first["pid"]lookup = topic_lookup_from_imported_post_id(linked_post_id)if lookup@@ -707,7 +897,6 @@ class ImportScripts::DiscuzX < ImportScripts::Baseelsereturn discuzx_linkend-endif import_category_id@@ -719,9 +908,9 @@ class ImportScripts::DiscuzX < ImportScripts::Baseendcase action- when 'index'+ when "index"return "#{NEW_SITE_PREFIX}/"- when 'stat', 'stats', 'ranklist'+ when "stat", "stats", "ranklist"return "#{NEW_SITE_PREFIX}/users"end@@ -729,28 +918,32 @@ class ImportScripts::DiscuzX < ImportScripts::Baseenddef pm_url_regexp- @pm_url_regexp ||= Regexp.new("http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub('.', '\.')}/forum\\.php\\?mod=redirect&goto=findpost&pid=\\d+&ptid=(\\d+)")+ @pm_url_regexp ||=+ Regexp.new(+ "http(?:s)?://#{ORIGINAL_SITE_PREFIX.gsub(".", '\.')}/forum\\.php\\?mod=redirect&goto=findpost&pid=\\d+&ptid=(\\d+)",+ )end# This step is done separately because it can take multiple attempts to get right (because of# missing files, wrong paths, authorized extensions, etc.).def import_attachments- setting = AUTHORIZED_EXTENSIONS.join('|')+ setting = AUTHORIZED_EXTENSIONS.join("|")SiteSetting.authorized_extensions = setting if setting != SiteSetting.authorized_extensions- attachment_regex = /\[attach\](\d+)\[\/attach\]/- attachment_link_regex = /\[x-attach\](.+)\[\/x-attach\]/+ attachment_regex = %r{\[attach\](\d+)\[/attach\]}+ attachment_link_regex = %r{\[x-attach\](.+)\[/x-attach\]}current_count = 0- total_count = mysql_query("SELECT count(*) count FROM #{table_name 'forum_post'};").first['count']+ total_count =+ mysql_query("SELECT count(*) count FROM #{table_name "forum_post"};").first["count"]success_count = 0fail_count = 0- puts '', "Importing attachments...", ''+ puts "", "Importing attachments...", ""Post.find_each do |post|- next unless post.custom_fields['import_id'] == post.custom_fields['import_id'].to_i.to_s+ next unless post.custom_fields["import_id"] == post.custom_fields["import_id"].to_i.to_suser = post.user@@ -786,17 +979,16 @@ class ImportScripts::DiscuzX < ImportScripts::Basehtml_for_upload(upload, filename)end- sql = "SELECT aid- FROM #{table_name 'forum_attachment'}- WHERE pid = #{post.custom_fields['import_id']}"- if !inline_attachments.empty?- sql = "#{sql} AND aid NOT IN (#{inline_attachments.join(',')})"- end+ sql =+ "SELECT aid+ FROM #{table_name "forum_attachment"}+ WHERE pid = #{post.custom_fields["import_id"]}"+ sql = "#{sql} AND aid NOT IN (#{inline_attachments.join(",")})" if !inline_attachments.empty?results = mysql_query(sql)results.each do |attachment|- attachment_id = attachment['aid']+ attachment_id = attachment["aid"]upload, filename = find_upload(user, post, attachment_id)unless uploadfail_count += 1@@ -810,21 +1002,26 @@ class ImportScripts::DiscuzX < ImportScripts::Baseendif new_raw != post.raw- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, bypass_bump: true, edit_reason: '从 Discuz 中导入附件')+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ bypass_bump: true,+ edit_reason: "从 Discuz 中导入附件",+ )endsuccess_count += 1end- puts '', ''+ puts "", ""puts "succeeded: #{success_count}"puts " failed: #{fail_count}" if fail_count > 0- puts ''+ puts ""end# Create the full path to the discuz avatar specified from user iddef discuzx_avatar_fullpath(user_id, absolute = true)- padded_id = user_id.to_s.rjust(9, '0')+ padded_id = user_id.to_s.rjust(9, "0")part_1 = padded_id[0..2]part_2 = padded_id[3..4]@@ -844,9 +1041,9 @@ class ImportScripts::DiscuzX < ImportScripts::Basecase rawwhen /\[url=forum.php\?mod=redirect&goto=findpost&pid=(\d+)&ptid=\d+\]/ #standard$1- when /\[url=https?:\/\/#{ORIGINAL_SITE_PREFIX}\/redirect.php\?goto=findpost&pid=(\d+)&ptid=\d+\]/ # old discuz 7 format+ when %r{\[url=https?://#{ORIGINAL_SITE_PREFIX}/redirect.php\?goto=findpost&pid=(\d+)&ptid=\d+\]} # old discuz 7 format$1- when /\[quote\][\S\s]*pid=(\d+)[\S\s]*\[\/quote\]/ # quote+ when %r{\[quote\][\S\s]*pid=(\d+)[\S\s]*\[/quote\]} # quote$1endend@@ -856,18 +1053,18 @@ class ImportScripts::DiscuzX < ImportScripts::Basedef upload_inline_image(data)return unless data- puts 'Creating inline image'+ puts "Creating inline image"- encoded_photo = data['data:image/png;base64,'.length .. -1]+ encoded_photo = data["data:image/png;base64,".length..-1]if encoded_photoraw_file = Base64.decode64(encoded_photo)else- puts 'Error parsed inline photo', data[0..20]+ puts "Error parsed inline photo", data[0..20]returnendreal_filename = "#{SecureRandom.hex}.png"- filename = Tempfile.new(['inline', '.png'])+ filename = Tempfile.new(%w[inline .png])beginfilename.binmodefilename.write(raw_file)@@ -875,8 +1072,16 @@ class ImportScripts::DiscuzX < ImportScripts::Baseupload = create_upload(Discourse::SYSTEM_USER_ID, filename, real_filename)ensure- filename.close rescue nil- filename.unlink rescue nil+ begin+ filename.close+ rescue StandardError+ nil+ end+ begin+ filename.unlink+ rescue StandardError+ nil+ endendif upload.nil? || !upload.valid?@@ -890,23 +1095,25 @@ class ImportScripts::DiscuzX < ImportScripts::Base# find the uploaded file and real name from the dbdef find_upload(user, post, upload_id)- attachment_table = table_name 'forum_attachment'+ attachment_table = table_name "forum_attachment"# search for table id- sql = "SELECT a.pid post_id,+ sql =+ "SELECT a.pid post_id,a.aid upload_id,a.tableid table_idFROM #{attachment_table} a- WHERE a.pid = #{post.custom_fields['import_id']}+ WHERE a.pid = #{post.custom_fields["import_id"]}AND a.aid = #{upload_id};"results = mysql_query(sql)unless (meta_data = results.first)- puts "Couldn't find forum_attachment record meta data for post.id = #{post.id}, import_id = #{post.custom_fields['import_id']}"+ puts "Couldn't find forum_attachment record meta data for post.id = #{post.id}, import_id = #{post.custom_fields["import_id"]}"return nilend# search for uploaded file meta data- sql = "SELECT a.pid post_id,+ sql =+ "SELECT a.pid post_id,a.aid upload_id,a.tid topic_id,a.uid user_id,@@ -917,22 +1124,22 @@ class ImportScripts::DiscuzX < ImportScripts::Basea.description description,a.isimage is_image,a.thumb is_thumb- FROM #{attachment_table}_#{meta_data['table_id']} a+ FROM #{attachment_table}_#{meta_data["table_id"]} aWHERE a.aid = #{upload_id};"results = mysql_query(sql)unless (row = results.first)- puts "Couldn't find attachment record for post.id = #{post.id}, import_id = #{post.custom_fields['import_id']}"+ puts "Couldn't find attachment record for post.id = #{post.id}, import_id = #{post.custom_fields["import_id"]}"return nilend- filename = File.join(DISCUZX_BASE_DIR, ATTACHMENT_DIR, row['attachment_path'])+ filename = File.join(DISCUZX_BASE_DIR, ATTACHMENT_DIR, row["attachment_path"])unless File.exist?(filename)puts "Attachment file doesn't exist: #{filename}"return nilend- real_filename = row['real_filename']- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ real_filename = row["real_filename"]+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."upload = create_upload(user.id, filename, real_filename)if upload.nil? || !upload.valid?@@ -950,7 +1157,7 @@ class ImportScripts::DiscuzX < ImportScripts::Baseenddef first_exists(*items)- items.find { |item|!item.blank? } || ''+ items.find { |item| !item.blank? } || ""enddef mysql_query(sql)diff --git a/script/import_scripts/disqus.rb b/script/import_scripts/disqus.rbindex 5dbeb08775a..1b6f4185a5f 100644--- a/script/import_scripts/disqus.rb+++ b/script/import_scripts/disqus.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require 'nokogiri'-require 'optparse'+require "nokogiri"+require "optparse"require File.expand_path(File.dirname(__FILE__) + "/base")class ImportScripts::Disqus < ImportScripts::Base@@ -35,7 +35,7 @@ class ImportScripts::Disqus < ImportScripts::Baseby_email = {}@parser.posts.each do |id, p|- next if p[:is_spam] == 'true' || p[:is_deleted] == 'true'+ next if p[:is_spam] == "true" || p[:is_deleted] == "true"by_email[p[:author_email]] = { name: p[:author_name], username: p[:author_username] }end@@ -45,13 +45,7 @@ class ImportScripts::Disqus < ImportScripts::Basecreate_users(by_email.keys) do |email|user = by_email[email]- {- id: email,- email: email,- username: user[:username],- name: user[:name],- merge: true- }+ { id: email, email: email, username: user[:username], name: user[:name], merge: true }endend@@ -59,7 +53,6 @@ class ImportScripts::Disqus < ImportScripts::Baseputs "", "importing topics..."@parser.threads.each do |id, t|-title = t[:title]title.gsub!(/“/, '"')title.gsub!(/”/, '"')@@ -79,7 +72,7 @@ class ImportScripts::Disqus < ImportScripts::Baseif post.present? && post.topic.posts_count <= 1(t[:posts] || []).each do |p|- post_user = find_existing_user(p[:author_email] || '', p[:author_username])+ post_user = find_existing_user(p[:author_email] || "", p[:author_username])next unless post_user.present?attrs = {@@ -87,7 +80,7 @@ class ImportScripts::Disqus < ImportScripts::Basetopic_id: post.topic_id,raw: p[:cooked],cooked: p[:cooked],- created_at: Date.parse(p[:created_at])+ created_at: Date.parse(p[:created_at]),}if p[:parent_id]@@ -125,23 +118,22 @@ class DisqusSAX < Nokogiri::XML::SAX::Documentenddef start_element(name, attrs = [])-hashed = Hash[attrs]case name- when 'post'+ when "post"@post = {}- @post[:id] = hashed['dsq:id'] if @post- when 'thread'- id = hashed['dsq:id']+ @post[:id] = hashed["dsq:id"] if @post+ when "thread"+ id = hashed["dsq:id"]if @postthread = @threads[id]thread[:posts] << @postelse@thread = { id: id, posts: [] }end- when 'parent'+ when "parent"if @post- id = hashed['dsq:id']+ id = hashed["dsq:id"]@post[:parent_id] = idendend@@ -151,10 +143,10 @@ class DisqusSAX < Nokogiri::XML::SAX::Documentdef end_element(name)case name- when 'post'+ when "post"@posts[@post[:id]] = @post@post = nil- when 'thread'+ when "thread"if @post.nil?@threads[@thread[:id]] = @thread@thread = nil@@ -165,25 +157,25 @@ class DisqusSAX < Nokogiri::XML::SAX::Documentenddef characters(str)- record(@post, :author_email, str, 'author', 'email')- record(@post, :author_name, str, 'author', 'name')- record(@post, :author_username, str, 'author', 'username')- record(@post, :author_anonymous, str, 'author', 'isAnonymous')- record(@post, :created_at, str, 'createdAt')- record(@post, :is_deleted, str, 'isDeleted')- record(@post, :is_spam, str, 'isSpam')-- record(@thread, :link, str, 'link')- record(@thread, :title, str, 'title')- record(@thread, :created_at, str, 'createdAt')- record(@thread, :author_email, str, 'author', 'email')- record(@thread, :author_name, str, 'author', 'name')- record(@thread, :author_username, str, 'author', 'username')- record(@thread, :author_anonymous, str, 'author', 'isAnonymous')+ record(@post, :author_email, str, "author", "email")+ record(@post, :author_name, str, "author", "name")+ record(@post, :author_username, str, "author", "username")+ record(@post, :author_anonymous, str, "author", "isAnonymous")+ record(@post, :created_at, str, "createdAt")+ record(@post, :is_deleted, str, "isDeleted")+ record(@post, :is_spam, str, "isSpam")++ record(@thread, :link, str, "link")+ record(@thread, :title, str, "title")+ record(@thread, :created_at, str, "createdAt")+ record(@thread, :author_email, str, "author", "email")+ record(@thread, :author_name, str, "author", "name")+ record(@thread, :author_username, str, "author", "username")+ record(@thread, :author_anonymous, str, "author", "isAnonymous")enddef cdata_block(str)- record(@post, :cooked, str, 'message')+ record(@post, :cooked, str, "message")enddef record(target, sym, str, *params)@@ -205,7 +197,7 @@ class DisqusSAX < Nokogiri::XML::SAX::Document# Remove any threads that have no posts@threads.delete(id)else- t[:posts].delete_if { |p| p[:is_spam] == 'true' || p[:is_deleted] == 'true' }+ t[:posts].delete_if { |p| p[:is_spam] == "true" || p[:is_deleted] == "true" }endenddiff --git a/script/import_scripts/drupal-6.rb b/script/import_scripts/drupal-6.rbindex 182596c63c3..3e27c0becd3 100644--- a/script/import_scripts/drupal-6.rb+++ b/script/import_scripts/drupal-6.rb@@ -4,19 +4,19 @@ require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Drupal < ImportScripts::Base-- DRUPAL_DB = ENV['DRUPAL_DB'] || "newsite3"- VID = ENV['DRUPAL_VID'] || 1+ DRUPAL_DB = ENV["DRUPAL_DB"] || "newsite3"+ VID = ENV["DRUPAL_VID"] || 1def initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- #password: "password",- database: DRUPAL_DB- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ #password: "password",+ database: DRUPAL_DB,+ )enddef categories_query@@ -25,7 +25,12 @@ class ImportScripts::Drupal < ImportScripts::Basedef executecreate_users(@client.query("SELECT uid id, name, mail email, created FROM users;")) do |row|- { id: row['id'], username: row['name'], email: row['email'], created_at: Time.zone.at(row['created']) }+ {+ id: row["id"],+ username: row["name"],+ email: row["email"],+ created_at: Time.zone.at(row["created"]),+ }end# You'll need to edit the following query for your Drupal install:@@ -34,38 +39,36 @@ class ImportScripts::Drupal < ImportScripts::Base# * Table name may be term_data.# * May need to select a vid other than 1.create_categories(categories_query) do |c|- { id: c['tid'], name: c['name'], description: c['description'] }+ { id: c["tid"], name: c["name"], description: c["description"] }end# "Nodes" in Drupal are divided into types. Here we import two types,# and will later import all the comments/replies for each node.# You will need to figure out what the type names are on your install and edit the queries to match.- if ENV['DRUPAL_IMPORT_BLOG']- create_blog_topics- end+ create_blog_topics if ENV["DRUPAL_IMPORT_BLOG"]create_forum_topicscreate_repliesbegin- create_admin(email: '[email protected]', username: UserNameSuggester.suggest('neil'))+ create_admin(email: "[email protected]", username: UserNameSuggester.suggest("neil"))rescue => e- puts '', "Failed to create admin user"+ puts "", "Failed to create admin user"puts e.messageendenddef create_blog_topics- puts '', "creating blog topics"+ puts "", "creating blog topics"- create_category({- name: 'Blog',- user_id: -1,- description: "Articles from the blog"- }, nil) unless Category.find_by_name('Blog')+ unless Category.find_by_name("Blog")+ create_category({ name: "Blog", user_id: -1, description: "Articles from the blog" }, nil)+ end- results = @client.query("+ results =+ @client.query(+ "SELECT n.nid nid,n.title title,n.uid uid,@@ -76,37 +79,48 @@ class ImportScripts::Drupal < ImportScripts::BaseLEFT JOIN node_revisions nr ON nr.vid=n.vidWHERE n.type = 'blog'AND n.status = 1- ", cache_rows: false)+ ",+ cache_rows: false,+ )create_posts(results) do |row|{- id: "nid:#{row['nid']}",- user_id: user_id_from_imported_user_id(row['uid']) || -1,- category: 'Blog',- raw: row['body'],- created_at: Time.zone.at(row['created']),- pinned_at: row['sticky'].to_i == 1 ? Time.zone.at(row['created']) : nil,- title: row['title'].try(:strip),- custom_fields: { import_id: "nid:#{row['nid']}" }+ id: "nid:#{row["nid"]}",+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ category: "Blog",+ raw: row["body"],+ created_at: Time.zone.at(row["created"]),+ pinned_at: row["sticky"].to_i == 1 ? Time.zone.at(row["created"]) : nil,+ title: row["title"].try(:strip),+ custom_fields: {+ import_id: "nid:#{row["nid"]}",+ },}endenddef create_forum_topics- puts '', "creating forum topics"+ puts "", "creating forum topics"- total_count = @client.query("+ total_count =+ @client.query(+ "SELECT COUNT(*) countFROM node nLEFT JOIN forum f ON f.vid=n.vidWHERE n.type = 'forum'AND n.status = 1- ").first['count']+ ",+ ).first[+ "count"+ ]batch_size = 1000batches(batch_size) do |offset|- results = @client.query("+ results =+ @client.query(+ "SELECT n.nid nid,n.title title,f.tid tid,@@ -121,48 +135,57 @@ class ImportScripts::Drupal < ImportScripts::BaseAND n.status = 1LIMIT #{batch_size}OFFSET #{offset};- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| "nid:#{p['nid']}" }+ next if all_records_exist? :posts, results.map { |p| "nid:#{p["nid"]}" }create_posts(results, total: total_count, offset: offset) do |row|{- id: "nid:#{row['nid']}",- user_id: user_id_from_imported_user_id(row['uid']) || -1,- category: category_id_from_imported_category_id(row['tid']),- raw: row['body'],- created_at: Time.zone.at(row['created']),- pinned_at: row['sticky'].to_i == 1 ? Time.zone.at(row['created']) : nil,- title: row['title'].try(:strip)+ id: "nid:#{row["nid"]}",+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ category: category_id_from_imported_category_id(row["tid"]),+ raw: row["body"],+ created_at: Time.zone.at(row["created"]),+ pinned_at: row["sticky"].to_i == 1 ? Time.zone.at(row["created"]) : nil,+ title: row["title"].try(:strip),}endendenddef create_replies- puts '', "creating replies in topics"+ puts "", "creating replies in topics"- if ENV['DRUPAL_IMPORT_BLOG']+ if ENV["DRUPAL_IMPORT_BLOG"]node_types = "('forum','blog')"elsenode_types = "('forum')"end- total_count = @client.query("+ total_count =+ @client.query(+ "SELECT COUNT(*) countFROM comments cLEFT JOIN node n ON n.nid=c.nidWHERE n.type IN #{node_types}AND n.status = 1AND c.status=0;- ").first['count']+ ",+ ).first[+ "count"+ ]batch_size = 1000batches(batch_size) do |offset|- results = @client.query("+ results =+ @client.query(+ "SELECT c.cid,c.pid,c.nid,@@ -176,37 +199,36 @@ class ImportScripts::Drupal < ImportScripts::BaseAND c.status=0LIMIT #{batch_size}OFFSET #{offset};- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| "cid:#{p['cid']}" }+ next if all_records_exist? :posts, results.map { |p| "cid:#{p["cid"]}" }create_posts(results, total: total_count, offset: offset) do |row|- topic_mapping = topic_lookup_from_imported_post_id("nid:#{row['nid']}")+ topic_mapping = topic_lookup_from_imported_post_id("nid:#{row["nid"]}")if topic_mapping && topic_id = topic_mapping[:topic_id]h = {- id: "cid:#{row['cid']}",+ id: "cid:#{row["cid"]}",topic_id: topic_id,- user_id: user_id_from_imported_user_id(row['uid']) || -1,- raw: row['body'],- created_at: Time.zone.at(row['timestamp']),+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ raw: row["body"],+ created_at: Time.zone.at(row["timestamp"]),}- if row['pid']- parent = topic_lookup_from_imported_post_id("cid:#{row['pid']}")+ if row["pid"]+ parent = topic_lookup_from_imported_post_id("cid:#{row["pid"]}")h[:reply_to_post_number] = parent[:post_number] if parent && parent[:post_number] > (1)endhelse- puts "No topic found for comment #{row['cid']}"+ puts "No topic found for comment #{row["cid"]}"nilendendendend-end-if __FILE__ == $0- ImportScripts::Drupal.new.perform-end+ImportScripts::Drupal.new.perform if __FILE__ == $0diff --git a/script/import_scripts/drupal.rb b/script/import_scripts/drupal.rbindex 2350a4efbf8..ac01a2daa40 100644--- a/script/import_scripts/drupal.rb+++ b/script/import_scripts/drupal.rb@@ -5,9 +5,8 @@ require "htmlentities"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Drupal < ImportScripts::Base-- DRUPAL_DB = ENV['DRUPAL_DB'] || "drupal"- VID = ENV['DRUPAL_VID'] || 1+ DRUPAL_DB = ENV["DRUPAL_DB"] || "drupal"+ VID = ENV["DRUPAL_VID"] || 1BATCH_SIZE = 1000ATTACHMENT_DIR = "/root/files/upload"@@ -16,25 +15,23 @@ class ImportScripts::Drupal < ImportScripts::Base@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- #password: "password",- database: DRUPAL_DB- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ #password: "password",+ database: DRUPAL_DB,+ )enddef execute-import_usersimport_categories# "Nodes" in Drupal are divided into types. Here we import two types,# and will later import all the comments/replies for each node.# You will need to figure out what the type names are on your install and edit the queries to match.- if ENV['DRUPAL_IMPORT_BLOG']- import_blog_topics- end+ import_blog_topics if ENV["DRUPAL_IMPORT_BLOG"]import_forum_topics@@ -56,7 +53,7 @@ class ImportScripts::Drupal < ImportScripts::Baselast_user_id = -1batches(BATCH_SIZE) do |offset|- users = mysql_query(<<-SQL+ users = mysql_query(<<-SQL).to_aSELECT uid,name username,mail email,@@ -66,7 +63,6 @@ class ImportScripts::Drupal < ImportScripts::BaseORDER BY uidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?@@ -80,12 +76,7 @@ class ImportScripts::Drupal < ImportScripts::Baseusername = @htmlentities.decode(user["username"]).strip- {- id: user["uid"],- name: username,- email: email,- created_at: Time.zone.at(user["created"])- }+ { id: user["uid"], name: username, email: email, created_at: Time.zone.at(user["created"]) }endendend@@ -99,35 +90,31 @@ class ImportScripts::Drupal < ImportScripts::Baseputs "", "importing categories"- categories = mysql_query(<<-SQL+ categories = mysql_query(<<-SQL).to_aSELECT tid,name,descriptionFROM taxonomy_term_dataWHERE vid = #{VID}SQL- ).to_acreate_categories(categories) do |category|{- id: category['tid'],- name: @htmlentities.decode(category['name']).strip,- description: @htmlentities.decode(category['description']).strip+ id: category["tid"],+ name: @htmlentities.decode(category["name"]).strip,+ description: @htmlentities.decode(category["description"]).strip,}endenddef import_blog_topics- puts '', "importing blog topics"+ puts "", "importing blog topics"- create_category(- {- name: 'Blog',- description: "Articles from the blog"- },- nil) unless Category.find_by_name('Blog')+ unless Category.find_by_name("Blog")+ create_category({ name: "Blog", description: "Articles from the blog" }, nil)+ end- blogs = mysql_query(<<-SQL+ blogs = mysql_query(<<-SQL).to_aSELECT n.nid nid, n.title title, n.uid uid, n.created created, n.sticky sticky,f.body_value bodyFROM node n,@@ -136,38 +123,38 @@ class ImportScripts::Drupal < ImportScripts::BaseAND n.nid = f.entity_idAND n.status = 1SQL- ).to_a- category_id = Category.find_by_name('Blog').id+ category_id = Category.find_by_name("Blog").idcreate_posts(blogs) do |topic|{- id: "nid:#{topic['nid']}",- user_id: user_id_from_imported_user_id(topic['uid']) || -1,+ id: "nid:#{topic["nid"]}",+ user_id: user_id_from_imported_user_id(topic["uid"]) || -1,category: category_id,- raw: topic['body'],- created_at: Time.zone.at(topic['created']),- pinned_at: topic['sticky'].to_i == 1 ? Time.zone.at(topic['created']) : nil,- title: topic['title'].try(:strip),- custom_fields: { import_id: "nid:#{topic['nid']}" }+ raw: topic["body"],+ created_at: Time.zone.at(topic["created"]),+ pinned_at: topic["sticky"].to_i == 1 ? Time.zone.at(topic["created"]) : nil,+ title: topic["title"].try(:strip),+ custom_fields: {+ import_id: "nid:#{topic["nid"]}",+ },}endenddef import_forum_topics- puts '', "importing forum topics"+ puts "", "importing forum topics"- total_count = mysql_query(<<-SQL+ total_count = mysql_query(<<-SQL).first["count"]SELECT COUNT(*) countFROM forum_index fi, node nWHERE n.type = 'forum'AND fi.nid = n.nidAND n.status = 1SQL- ).first['count']batches(BATCH_SIZE) do |offset|- results = mysql_query(<<-SQL+ results = mysql_query(<<-SQL).to_aSELECT fi.nid nid,fi.title title,fi.tid tid,@@ -188,34 +175,33 @@ class ImportScripts::Drupal < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset};SQL- ).to_abreak if results.size < 1- next if all_records_exist? :posts, results.map { |p| "nid:#{p['nid']}" }+ next if all_records_exist? :posts, results.map { |p| "nid:#{p["nid"]}" }create_posts(results, total: total_count, offset: offset) do |row|- raw = preprocess_raw(row['body'])+ raw = preprocess_raw(row["body"])topic = {- id: "nid:#{row['nid']}",- user_id: user_id_from_imported_user_id(row['uid']) || -1,- category: category_id_from_imported_category_id(row['tid']),+ id: "nid:#{row["nid"]}",+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ category: category_id_from_imported_category_id(row["tid"]),raw: raw,- created_at: Time.zone.at(row['created']),- pinned_at: row['sticky'].to_i == 1 ? Time.zone.at(row['created']) : nil,- title: row['title'].try(:strip),- views: row['views']+ created_at: Time.zone.at(row["created"]),+ pinned_at: row["sticky"].to_i == 1 ? Time.zone.at(row["created"]) : nil,+ title: row["title"].try(:strip),+ views: row["views"],}- topic[:custom_fields] = { import_solved: true } if row['solved'].present?+ topic[:custom_fields] = { import_solved: true } if row["solved"].present?topicendendenddef import_replies- puts '', "creating replies in topics"+ puts "", "creating replies in topics"- total_count = mysql_query(<<-SQL+ total_count = mysql_query(<<-SQL).first["count"]SELECT COUNT(*) countFROM comment c,node n@@ -224,10 +210,9 @@ class ImportScripts::Drupal < ImportScripts::BaseAND n.type IN ('article', 'forum')AND n.status = 1SQL- ).first['count']batches(BATCH_SIZE) do |offset|- results = mysql_query(<<-SQL+ results = mysql_query(<<-SQL).to_aSELECT c.cid, c.pid, c.nid, c.uid, c.created,f.comment_body_value bodyFROM comment c,@@ -241,30 +226,29 @@ class ImportScripts::Drupal < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- ).to_abreak if results.size < 1- next if all_records_exist? :posts, results.map { |p| "cid:#{p['cid']}" }+ next if all_records_exist? :posts, results.map { |p| "cid:#{p["cid"]}" }create_posts(results, total: total_count, offset: offset) do |row|- topic_mapping = topic_lookup_from_imported_post_id("nid:#{row['nid']}")+ topic_mapping = topic_lookup_from_imported_post_id("nid:#{row["nid"]}")if topic_mapping && topic_id = topic_mapping[:topic_id]- raw = preprocess_raw(row['body'])+ raw = preprocess_raw(row["body"])h = {- id: "cid:#{row['cid']}",+ id: "cid:#{row["cid"]}",topic_id: topic_id,- user_id: user_id_from_imported_user_id(row['uid']) || -1,+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,raw: raw,- created_at: Time.zone.at(row['created']),+ created_at: Time.zone.at(row["created"]),}- if row['pid']- parent = topic_lookup_from_imported_post_id("cid:#{row['pid']}")+ if row["pid"]+ parent = topic_lookup_from_imported_post_id("cid:#{row["pid"]}")h[:reply_to_post_number] = parent[:post_number] if parent && parent[:post_number] > (1)endhelse- puts "No topic found for comment #{row['cid']}"+ puts "No topic found for comment #{row["cid"]}"nilendend@@ -275,7 +259,7 @@ class ImportScripts::Drupal < ImportScripts::Baseputs "", "importing post likes"batches(BATCH_SIZE) do |offset|- likes = mysql_query(<<-SQL+ likes = mysql_query(<<-SQL).to_aSELECT flagging_id,fid,entity_id,@@ -286,17 +270,20 @@ class ImportScripts::Drupal < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- ).to_abreak if likes.empty?likes.each do |l|- identifier = l['fid'] == 5 ? 'nid' : 'cid'- next unless user_id = user_id_from_imported_user_id(l['uid'])- next unless post_id = post_id_from_imported_post_id("#{identifier}:#{l['entity_id']}")+ identifier = l["fid"] == 5 ? "nid" : "cid"+ next unless user_id = user_id_from_imported_user_id(l["uid"])+ next unless post_id = post_id_from_imported_post_id("#{identifier}:#{l["entity_id"]}")next unless user = User.find_by(id: user_id)next unless post = Post.find_by(id: post_id)- PostActionCreator.like(user, post) rescue nil+ begin+ PostActionCreator.like(user, post)+ rescue StandardError+ nil+ endendendend@@ -304,7 +291,8 @@ class ImportScripts::Drupal < ImportScripts::Basedef mark_topics_as_solvedputs "", "marking topics as solved"- solved_topics = TopicCustomField.where(name: "import_solved").where(value: true).pluck(:topic_id)+ solved_topics =+ TopicCustomField.where(name: "import_solved").where(value: true).pluck(:topic_id)solved_topics.each do |topic_id|next unless topic = Topic.find(topic_id)@@ -336,8 +324,13 @@ class ImportScripts::Drupal < ImportScripts::Basebegincurrent_count += 1print_status(current_count, total_count, start_time)- SingleSignOnRecord.create!(user_id: user.id, external_id: external_id, external_email: user.email, last_payload: '')- rescue+ SingleSignOnRecord.create!(+ user_id: user.id,+ external_id: external_id,+ external_email: user.email,+ last_payload: "",+ )+ rescue StandardErrornextendend@@ -350,14 +343,13 @@ class ImportScripts::Drupal < ImportScripts::Basesuccess_count = 0fail_count = 0- total_count = mysql_query(<<-SQL+ total_count = mysql_query(<<-SQL).first["count"]SELECT count(field_post_attachment_fid) countFROM field_data_field_post_attachmentSQL- ).first["count"]batches(BATCH_SIZE) do |offset|- attachments = mysql_query(<<-SQL+ attachments = mysql_query(<<-SQL).to_aSELECT *FROM field_data_field_post_attachment fpLEFT JOIN file_managed fm@@ -365,7 +357,6 @@ class ImportScripts::Drupal < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- ).to_abreak if attachments.size < 1@@ -373,9 +364,11 @@ class ImportScripts::Drupal < ImportScripts::Basecurrent_count += 1print_status current_count, total_count- identifier = attachment['entity_type'] == "comment" ? "cid" : "nid"- next unless user_id = user_id_from_imported_user_id(attachment['uid'])- next unless post_id = post_id_from_imported_post_id("#{identifier}:#{attachment['entity_id']}")+ identifier = attachment["entity_type"] == "comment" ? "cid" : "nid"+ next unless user_id = user_id_from_imported_user_id(attachment["uid"])+ unless post_id = post_id_from_imported_post_id("#{identifier}:#{attachment["entity_id"]}")+ next+ endnext unless user = User.find(user_id)next unless post = Post.find(post_id)@@ -392,9 +385,14 @@ class ImportScripts::Drupal < ImportScripts::Basenew_raw = "#{new_raw}\n\n#{upload_html}" unless new_raw.include?(upload_html)if new_raw != post.raw- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, bypass_bump: true, edit_reason: "Import attachment from Drupal")+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ bypass_bump: true,+ edit_reason: "Import attachment from Drupal",+ )else- puts '', 'Skipped upload: already imported'+ puts "", "Skipped upload: already imported"endsuccess_count += 1@@ -406,13 +404,13 @@ class ImportScripts::Drupal < ImportScripts::Baseenddef create_permalinks- puts '', 'creating permalinks...'+ puts "", "creating permalinks..."Topic.listable_topics.find_each do |topic|begintcf = topic.custom_fields- if tcf && tcf['import_id']- node_id = tcf['import_id'][/nid:(\d+)/, 1]+ if tcf && tcf["import_id"]+ node_id = tcf["import_id"][/nid:(\d+)/, 1]slug = "/node/#{node_id}"Permalink.create(url: slug, topic_id: topic.id)end@@ -424,18 +422,16 @@ class ImportScripts::Drupal < ImportScripts::Baseenddef find_upload(post, attachment)- uri = attachment['uri'][/public:\/\/upload\/(.+)/, 1]+ uri = attachment["uri"][%r{public://upload/(.+)}, 1]real_filename = CGI.unescapeHTML(uri)file = File.join(ATTACHMENT_DIR, real_filename)unless File.exist?(file)- puts "Attachment file #{attachment['filename']} doesn't exist"+ puts "Attachment file #{attachment["filename"]} doesn't exist"tmpfile = "attachments_failed.txt"- filename = File.join('/tmp/', tmpfile)- File.open(filename, 'a') { |f|- f.puts attachment['filename']- }+ filename = File.join("/tmp/", tmpfile)+ File.open(filename, "a") { |f| f.puts attachment["filename"] }endupload = create_upload(post.user.id || -1, file, real_filename)@@ -452,13 +448,13 @@ class ImportScripts::Drupal < ImportScripts::Basedef preprocess_raw(raw)return if raw.blank?# quotes on new lines- raw.gsub!(/\[quote\](.+?)\[\/quote\]/im) { |quote|- quote.gsub!(/\[quote\](.+?)\[\/quote\]/im) { "\n#{$1}\n" }+ raw.gsub!(%r{\[quote\](.+?)\[/quote\]}im) do |quote|+ quote.gsub!(%r{\[quote\](.+?)\[/quote\]}im) { "\n#{$1}\n" }quote.gsub!(/\n(.+?)/) { "\n> #{$1}" }- }+ end# [QUOTE=<username>]...[/QUOTE]- raw.gsub!(/\[quote=([^;\]]+)\](.+?)\[\/quote\]/im) do+ raw.gsub!(%r{\[quote=([^;\]]+)\](.+?)\[/quote\]}im) dousername, quote = $1, $2"\n[quote=\"#{username}\"]\n#{quote}\n[/quote]\n"end@@ -468,7 +464,7 @@ class ImportScripts::Drupal < ImportScripts::Baseenddef postprocess_posts- puts '', 'postprocessing posts'+ puts "", "postprocessing posts"current = 0max = Post.count@@ -479,7 +475,7 @@ class ImportScripts::Drupal < ImportScripts::Basenew_raw = raw.dup# replace old topic to new topic links- new_raw.gsub!(/https:\/\/site.com\/forum\/topic\/(\d+)/im) do+ new_raw.gsub!(%r{https://site.com/forum/topic/(\d+)}im) dopost_id = post_id_from_imported_post_id("nid:#{$1}")next unless post_idtopic = Post.find(post_id).topic@@ -487,7 +483,7 @@ class ImportScripts::Drupal < ImportScripts::Baseend# replace old comment to reply links- new_raw.gsub!(/https:\/\/site.com\/comment\/(\d+)#comment-\d+/im) do+ new_raw.gsub!(%r{https://site.com/comment/(\d+)#comment-\d+}im) dopost_id = post_id_from_imported_post_id("cid:#{$1}")next unless post_idpost_ref = Post.find(post_id)@@ -498,8 +494,8 @@ class ImportScripts::Drupal < ImportScripts::Basepost.raw = new_rawpost.saveend- rescue- puts '', "Failed rewrite on post: #{post.id}"+ rescue StandardError+ puts "", "Failed rewrite on post: #{post.id}"ensureprint_status(current += 1, max)end@@ -507,15 +503,15 @@ class ImportScripts::Drupal < ImportScripts::Baseenddef import_gravatars- puts '', 'importing gravatars'+ puts "", "importing gravatars"current = 0max = User.countUser.find_each do |user|beginuser.create_user_avatar(user_id: user.id) unless user.user_avataruser.user_avatar.update_gravatar!- rescue- puts '', 'Failed avatar update on user #{user.id}'+ rescue StandardError+ puts "", 'Failed avatar update on user #{user.id}'ensureprint_status(current += 1, max)end@@ -523,15 +519,12 @@ class ImportScripts::Drupal < ImportScripts::Baseenddef parse_datetime(time)- DateTime.strptime(time, '%s')+ DateTime.strptime(time, "%s")enddef mysql_query(sql)@client.query(sql, cache_rows: true)end-end-if __FILE__ == $0- ImportScripts::Drupal.new.perform-end+ImportScripts::Drupal.new.perform if __FILE__ == $0diff --git a/script/import_scripts/drupal_json.rb b/script/import_scripts/drupal_json.rbindex d69f21e01bd..f97ae683e11 100644--- a/script/import_scripts/drupal_json.rb+++ b/script/import_scripts/drupal_json.rb@@ -5,7 +5,6 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Edit the constants and initialize method for your import data.class ImportScripts::DrupalJson < ImportScripts::Base-JSON_FILES_DIR = "/Users/techapj/Documents"def initialize@@ -28,20 +27,18 @@ class ImportScripts::DrupalJson < ImportScripts::Baseenddef import_users- puts '', "Importing users"+ puts "", "Importing users"create_users(@users_json) do |u|{id: u["uid"],name: u["name"],email: u["mail"],- created_at: Time.zone.at(u["created"].to_i)+ created_at: Time.zone.at(u["created"].to_i),}endEmailToken.delete_allendend-if __FILE__ == $0- ImportScripts::DrupalJson.new.perform-end+ImportScripts::DrupalJson.new.perform if __FILE__ == $0diff --git a/script/import_scripts/drupal_qa.rb b/script/import_scripts/drupal_qa.rbindex a8febbd41c0..948b04590dd 100644--- a/script/import_scripts/drupal_qa.rb+++ b/script/import_scripts/drupal_qa.rb@@ -5,41 +5,51 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")require File.expand_path(File.dirname(__FILE__) + "/drupal.rb")class ImportScripts::DrupalQA < ImportScripts::Drupal-def categories_query- result = @client.query("SELECT n.nid, GROUP_CONCAT(ti.tid) AS tids+ result =+ @client.query(+ "SELECT n.nid, GROUP_CONCAT(ti.tid) AS tidsFROM node AS nINNER JOIN taxonomy_index AS ti ON ti.nid = n.nidWHERE n.type = 'question'AND n.status = 1- GROUP BY n.nid")+ GROUP BY n.nid",+ )categories = {}result.each do |r|- tids = r['tids']+ tids = r["tids"]if tids.present?- tids = tids.split(',')+ tids = tids.split(",")categories[tids[0].to_i] = trueendend- @client.query("SELECT tid, name, description FROM taxonomy_term_data WHERE tid IN (#{categories.keys.join(',')})")+ @client.query(+ "SELECT tid, name, description FROM taxonomy_term_data WHERE tid IN (#{categories.keys.join(",")})",+ )enddef create_forum_topics+ puts "", "creating forum topics"- puts '', "creating forum topics"-- total_count = @client.query("+ total_count =+ @client.query(+ "SELECT COUNT(*) countFROM node nWHERE n.type = 'question'- AND n.status = 1;").first['count']+ AND n.status = 1;",+ ).first[+ "count"+ ]batch_size = 1000batches(batch_size) do |offset|- results = @client.query("+ results =+ @client.query(+ "SELECT n.nid,n.title,GROUP_CONCAT(t.tid) AS tid,@@ -54,40 +64,48 @@ class ImportScripts::DrupalQA < ImportScripts::DrupalGROUP BY n.nid, n.title, n.uid, n.created, f.body_valueLIMIT #{batch_size}OFFSET #{offset}- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| "nid:#{p['nid']}" }+ next if all_records_exist? :posts, results.map { |p| "nid:#{p["nid"]}" }create_posts(results, total: total_count, offset: offset) do |row|{- id: "nid:#{row['nid']}",- user_id: user_id_from_imported_user_id(row['uid']) || -1,- category: category_id_from_imported_category_id((row['tid'] || '').split(',')[0]),- raw: row['body'],- created_at: Time.zone.at(row['created']),+ id: "nid:#{row["nid"]}",+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ category: category_id_from_imported_category_id((row["tid"] || "").split(",")[0]),+ raw: row["body"],+ created_at: Time.zone.at(row["created"]),pinned_at: nil,- title: row['title'].try(:strip)+ title: row["title"].try(:strip),}endendenddef create_direct_replies- puts '', "creating replies in topics"+ puts "", "creating replies in topics"- total_count = @client.query("+ total_count =+ @client.query(+ "SELECT COUNT(*) countFROM node nWHERE n.type = 'answer'- AND n.status = 1;").first['count']+ AND n.status = 1;",+ ).first[+ "count"+ ]batch_size = 1000batches(batch_size) do |offset|-- results = @client.query("+ results =+ @client.query(+ "SELECT n.nid AS cid,q.field_answer_question_nid AS nid,n.uid,@@ -100,25 +118,27 @@ class ImportScripts::DrupalQA < ImportScripts::DrupalAND n.type = 'answer'LIMIT #{batch_size}OFFSET #{offset}- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| "cid:#{p['cid']}" }+ next if all_records_exist? :posts, results.map { |p| "cid:#{p["cid"]}" }create_posts(results, total: total_count, offset: offset) do |row|- topic_mapping = topic_lookup_from_imported_post_id("nid:#{row['nid']}")+ topic_mapping = topic_lookup_from_imported_post_id("nid:#{row["nid"]}")if topic_mapping && topic_id = topic_mapping[:topic_id]h = {- id: "cid:#{row['cid']}",+ id: "cid:#{row["cid"]}",topic_id: topic_id,- user_id: user_id_from_imported_user_id(row['uid']) || -1,- raw: row['body'],- created_at: Time.zone.at(row['created']),+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ raw: row["body"],+ created_at: Time.zone.at(row["created"]),}helse- puts "No topic found for answer #{row['cid']}"+ puts "No topic found for answer #{row["cid"]}"nilendend@@ -126,21 +146,27 @@ class ImportScripts::DrupalQA < ImportScripts::Drupalenddef create_nested_replies- puts '', "creating nested replies to posts in topics"+ puts "", "creating nested replies to posts in topics"- total_count = @client.query("+ total_count =+ @client.query(+ "SELECT COUNT(c.cid) countFROM node nINNER JOIN comment AS c ON n.nid = c.nidWHERE n.type = 'question'- AND n.status = 1;").first['count']+ AND n.status = 1;",+ ).first[+ "count"+ ]batch_size = 1000batches(batch_size) do |offset|-# WARNING: If there are more than 1000000 this might have to be revisited- results = @client.query("+ results =+ @client.query(+ "SELECT (c.cid + 1000000) as cid,c.nid,c.uid,@@ -153,45 +179,53 @@ class ImportScripts::DrupalQA < ImportScripts::DrupalAND n.type = 'question'LIMIT #{batch_size}OFFSET #{offset}- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| "cid:#{p['cid']}" }+ next if all_records_exist? :posts, results.map { |p| "cid:#{p["cid"]}" }create_posts(results, total: total_count, offset: offset) do |row|- topic_mapping = topic_lookup_from_imported_post_id("nid:#{row['nid']}")+ topic_mapping = topic_lookup_from_imported_post_id("nid:#{row["nid"]}")if topic_mapping && topic_id = topic_mapping[:topic_id]h = {- id: "cid:#{row['cid']}",+ id: "cid:#{row["cid"]}",topic_id: topic_id,- user_id: user_id_from_imported_user_id(row['uid']) || -1,- raw: row['body'],- created_at: Time.zone.at(row['created']),+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ raw: row["body"],+ created_at: Time.zone.at(row["created"]),}helse- puts "No topic found for comment #{row['cid']}"+ puts "No topic found for comment #{row["cid"]}"nilendendend- puts '', "creating nested replies to answers in topics"+ puts "", "creating nested replies to answers in topics"- total_count = @client.query("+ total_count =+ @client.query(+ "SELECT COUNT(c.cid) countFROM node nINNER JOIN comment AS c ON n.nid = c.nidWHERE n.type = 'answer'- AND n.status = 1;").first['count']+ AND n.status = 1;",+ ).first[+ "count"+ ]batch_size = 1000batches(batch_size) do |offset|-# WARNING: If there are more than 1000000 this might have to be revisited- results = @client.query("+ results =+ @client.query(+ "SELECT (c.cid + 1000000) as cid,q.field_answer_question_nid AS nid,c.uid,@@ -205,25 +239,27 @@ class ImportScripts::DrupalQA < ImportScripts::DrupalAND n.type = 'answer'LIMIT #{batch_size}OFFSET #{offset}- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| "cid:#{p['cid']}" }+ next if all_records_exist? :posts, results.map { |p| "cid:#{p["cid"]}" }create_posts(results, total: total_count, offset: offset) do |row|- topic_mapping = topic_lookup_from_imported_post_id("nid:#{row['nid']}")+ topic_mapping = topic_lookup_from_imported_post_id("nid:#{row["nid"]}")if topic_mapping && topic_id = topic_mapping[:topic_id]h = {- id: "cid:#{row['cid']}",+ id: "cid:#{row["cid"]}",topic_id: topic_id,- user_id: user_id_from_imported_user_id(row['uid']) || -1,- raw: row['body'],- created_at: Time.zone.at(row['created']),+ user_id: user_id_from_imported_user_id(row["uid"]) || -1,+ raw: row["body"],+ created_at: Time.zone.at(row["created"]),}helse- puts "No topic found for comment #{row['cid']}"+ puts "No topic found for comment #{row["cid"]}"nilendend@@ -234,9 +270,6 @@ class ImportScripts::DrupalQA < ImportScripts::Drupalcreate_direct_repliescreate_nested_repliesend-end-if __FILE__ == $0- ImportScripts::DrupalQA.new.perform-end+ImportScripts::DrupalQA.new.perform if __FILE__ == $0diff --git a/script/import_scripts/elgg.rb b/script/import_scripts/elgg.rbindex 6eb62eb0314..1293e171793 100644--- a/script/import_scripts/elgg.rb+++ b/script/import_scripts/elgg.rb@@ -1,22 +1,16 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Elgg < ImportScripts::Base-BATCH_SIZE ||= 1000def initializesuper- @client = Mysql2::Client.new(- host: "127.0.0.1",- port: "3306",- username: "",- database: "",- password: ""- )+ @client =+ Mysql2::Client.new(host: "127.0.0.1", port: "3306", username: "", database: "", password: "")SiteSetting.max_username_length = 50end@@ -31,7 +25,7 @@ class ImportScripts::Elgg < ImportScripts::Basedef create_avatar(user, guid)puts "#{@path}"# Put your avatar at the root of discourse in this folder:- path_prefix = 'import/data/www/'+ path_prefix = "import/data/www/"# https://github.com/Elgg/Elgg/blob/2fc9c1910a9169bbe4010026c61d8e41a5b56239/engine/classes/ElggDiskFilestore.php#L24# const BUCKET_SIZE = 5000;bucket_size = 5000@@ -40,13 +34,11 @@ class ImportScripts::Elgg < ImportScripts::Basebucket_id = [guid / bucket_size * bucket_size, 1].maxavatar_path = File.join(path_prefix, bucket_id.to_s, "/#{guid}/profile/#{guid}master.jpg")- if File.exist?(avatar_path)- @uploader.create_avatar(user, avatar_path)- end+ @uploader.create_avatar(user, avatar_path) if File.exist?(avatar_path)enddef grant_admin(user, is_admin)- if is_admin == 'yes'+ if is_admin == "yes"puts "", "#{user.username} is granted admin!"user.grant_admin!end@@ -56,10 +48,11 @@ class ImportScripts::Elgg < ImportScripts::Baseputs "", "importing users..."last_user_id = -1- total_users = mysql_query("select count(*) from elgg_users_entity where banned='no'").first["count"]+ total_users =+ mysql_query("select count(*) from elgg_users_entity where banned='no'").first["count"]batches(BATCH_SIZE) do |offset|- users = mysql_query(<<-SQL+ users = mysql_query(<<-SQL).to_aselect eue.guid, eue.username, eue.name, eue.email, eue.admin,max(case when ems1.string='cae_structure' then ems2.string end)cae_structure,max(case when ems1.string='location' then ems2.string end)location,@@ -76,7 +69,6 @@ class ImportScripts::Elgg < ImportScripts::Basegroup by eue.guidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?@@ -97,11 +89,12 @@ class ImportScripts::Elgg < ImportScripts::Basename: u["name"],website: u["website"],bio_raw: u["briefdescription"].to_s + " " + u["cae_structure"].to_s,- post_create_action: proc do |user|- create_avatar(user, u["guid"])- #add_user_to_group(user, u["cae_structure"])- grant_admin(user, u["admin"])- end+ post_create_action:+ proc do |user|+ create_avatar(user, u["guid"])+ #add_user_to_group(user, u["cae_structure"])+ grant_admin(user, u["admin"])+ end,}endend@@ -115,9 +108,9 @@ class ImportScripts::Elgg < ImportScripts::Basecreate_categories(categories) do |c|{- id: c['guid'],- name: CGI.unescapeHTML(c['name']),- description: CGI.unescapeHTML(c['description'])+ id: c["guid"],+ name: CGI.unescapeHTML(c["name"]),+ description: CGI.unescapeHTML(c["description"]),}endend@@ -125,10 +118,13 @@ class ImportScripts::Elgg < ImportScripts::Basedef import_topicsputs "", "creating topics"- total_count = mysql_query("select count(*) count from elgg_entities where subtype = 32;").first["count"]+ total_count =+ mysql_query("select count(*) count from elgg_entities where subtype = 32;").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECTee.guid id,owner_guid user_id,@@ -143,30 +139,35 @@ class ImportScripts::Elgg < ImportScripts::BaseORDER BY ee.guidLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|{- id: m['id'],- user_id: user_id_from_imported_user_id(m['user_id']) || -1,- raw: CGI.unescapeHTML(m['raw']),- created_at: Time.zone.at(m['created_at']),- category: category_id_from_imported_category_id(m['category_id']),- title: CGI.unescapeHTML(m['title']),- post_create_action: proc do |post|- tag_names = mysql_query("+ id: m["id"],+ user_id: user_id_from_imported_user_id(m["user_id"]) || -1,+ raw: CGI.unescapeHTML(m["raw"]),+ created_at: Time.zone.at(m["created_at"]),+ category: category_id_from_imported_category_id(m["category_id"]),+ title: CGI.unescapeHTML(m["title"]),+ post_create_action:+ proc do |post|+ tag_names =+ mysql_query(+ "select ms.stringfrom elgg_metadata mdjoin elgg_metastrings ms on md.value_id = ms.idwhere name_id = 43- and entity_guid = #{m['id']};- ").map { |tag| tag['string'] }- DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)- end+ and entity_guid = #{m["id"]};+ ",+ ).map { |tag| tag["string"] }+ DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)+ end,}endend@@ -179,10 +180,13 @@ class ImportScripts::Elgg < ImportScripts::Basedef import_postsputs "", "creating posts"- total_count = mysql_query("SELECT count(*) count FROM elgg_entities WHERE subtype = 42").first["count"]+ total_count =+ mysql_query("SELECT count(*) count FROM elgg_entities WHERE subtype = 42").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECTee.guid id,container_guid topic_id,@@ -195,19 +199,20 @@ class ImportScripts::Elgg < ImportScripts::BaseORDER BY ee.guidLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|{- id: m['id'],- user_id: user_id_from_imported_user_id(m['user_id']) || -1,- topic_id: topic_lookup_from_imported_post_id(m['topic_id'])[:topic_id],- raw: CGI.unescapeHTML(m['raw']),- created_at: Time.zone.at(m['created_at']),+ id: m["id"],+ user_id: user_id_from_imported_user_id(m["user_id"]) || -1,+ topic_id: topic_lookup_from_imported_post_id(m["topic_id"])[:topic_id],+ raw: CGI.unescapeHTML(m["raw"]),+ created_at: Time.zone.at(m["created_at"]),}endend@@ -216,7 +221,6 @@ class ImportScripts::Elgg < ImportScripts::Basedef mysql_query(sql)@client.query(sql, cache_rows: false)end-endImportScripts::Elgg.new.performdiff --git a/script/import_scripts/flarum_import.rb b/script/import_scripts/flarum_import.rbindex ea4eb3dddfe..737ee3a86e5 100644--- a/script/import_scripts/flarum_import.rb+++ b/script/import_scripts/flarum_import.rb@@ -1,60 +1,62 @@# frozen_string_literal: truerequire "mysql2"-require 'time'-require 'date'+require "time"+require "date"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::FLARUM < ImportScripts::Base#SET THE APPROPRIATE VALUES FOR YOUR MYSQL CONNECTION- FLARUM_HOST ||= ENV['FLARUM_HOST'] || "db_host"- FLARUM_DB ||= ENV['FLARUM_DB'] || "db_name"+ FLARUM_HOST ||= ENV["FLARUM_HOST"] || "db_host"+ FLARUM_DB ||= ENV["FLARUM_DB"] || "db_name"BATCH_SIZE ||= 1000- FLARUM_USER ||= ENV['FLARUM_USER'] || "db_user"- FLARUM_PW ||= ENV['FLARUM_PW'] || "db_user_pass"+ FLARUM_USER ||= ENV["FLARUM_USER"] || "db_user"+ FLARUM_PW ||= ENV["FLARUM_PW"] || "db_user_pass"def initializesuper- @client = Mysql2::Client.new(- host: FLARUM_HOST,- username: FLARUM_USER,- password: FLARUM_PW,- database: FLARUM_DB- )+ @client =+ Mysql2::Client.new(+ host: FLARUM_HOST,+ username: FLARUM_USER,+ password: FLARUM_PW,+ database: FLARUM_DB,+ )enddef execute-import_usersimport_categoriesimport_posts-enddef import_users- puts '', "creating users"- total_count = mysql_query("SELECT count(*) count FROM users;").first['count']+ puts "", "creating users"+ total_count = mysql_query("SELECT count(*) count FROM users;").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT id, username, email, joined_at, last_seen_at+ results =+ mysql_query(+ "SELECT id, username, email, joined_at, last_seen_atFROM usersLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1next if all_records_exist? :users, results.map { |u| u["id"].to_i }create_users(results, total: total_count, offset: offset) do |user|- { id: user['id'],- email: user['email'],- username: user['username'],- name: user['username'],- created_at: user['joined_at'],- last_seen_at: user['last_seen_at']+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ name: user["username"],+ created_at: user["joined_at"],+ last_seen_at: user["last_seen_at"],}endend@@ -63,30 +65,31 @@ class ImportScripts::FLARUM < ImportScripts::Basedef import_categoriesputs "", "importing top level categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT id, name, description, positionFROM tagsORDER BY position ASC- ").to_a+ ",+ ).to_a- create_categories(categories) do |category|- {- id: category["id"],- name: category["name"]- }- end+ create_categories(categories) { |category| { id: category["id"], name: category["name"] } }puts "", "importing children categories..."- children_categories = mysql_query("+ children_categories =+ mysql_query(+ "SELECT id, name, description, positionFROM tagsORDER BY position- ").to_a+ ",+ ).to_acreate_categories(children_categories) do |category|{- id: "child##{category['id']}",+ id: "child##{category["id"]}",name: category["name"],description: category["description"],}@@ -99,7 +102,9 @@ class ImportScripts::FLARUM < ImportScripts::Basetotal_count = mysql_query("SELECT count(*) count from posts").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.id id,d.id topic_id,d.title title,@@ -116,29 +121,30 @@ class ImportScripts::FLARUM < ImportScripts::BaseORDER BY p.created_atLIMIT #{BATCH_SIZE}OFFSET #{offset};- ").to_a+ ",+ ).to_abreak if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|skip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_FLARUM_post(m['raw'], m['id'])- mapped[:created_at] = Time.zone.at(m['created_at'])+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_FLARUM_post(m["raw"], m["id"])+ mapped[:created_at] = Time.zone.at(m["created_at"])- if m['id'] == m['first_post_id']- mapped[:category] = category_id_from_imported_category_id("child##{m['category_id']}")- mapped[:title] = CGI.unescapeHTML(m['title'])+ if m["id"] == m["first_post_id"]+ mapped[:category] = category_id_from_imported_category_id("child##{m["category_id"]}")+ mapped[:title] = CGI.unescapeHTML(m["title"])else- parent = topic_lookup_from_imported_post_id(m['first_post_id'])+ parent = topic_lookup_from_imported_post_id(m["first_post_id"])if parentmapped[:topic_id] = parent[:topic_id]else- puts "Parent post #{m['first_post_id']} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"+ puts "Parent post #{m["first_post_id"]} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"skip = trueendenddiff --git a/script/import_scripts/fluxbb.rb b/script/import_scripts/fluxbb.rbindex 38b84ed3c17..9af64457c80 100644--- a/script/import_scripts/fluxbb.rb+++ b/script/import_scripts/fluxbb.rb@@ -17,23 +17,23 @@ export FLUXBB_PREFIX=""# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/fluxbb.rbclass ImportScripts::FluxBB < ImportScripts::Base-- FLUXBB_HOST ||= ENV['FLUXBB_HOST'] || "localhost"- FLUXBB_DB ||= ENV['FLUXBB_DB'] || "fluxbb"+ FLUXBB_HOST ||= ENV["FLUXBB_HOST"] || "localhost"+ FLUXBB_DB ||= ENV["FLUXBB_DB"] || "fluxbb"BATCH_SIZE ||= 1000- FLUXBB_USER ||= ENV['FLUXBB_USER'] || "root"- FLUXBB_PW ||= ENV['FLUXBB_PW'] || ""- FLUXBB_PREFIX ||= ENV['FLUXBB_PREFIX'] || ""+ FLUXBB_USER ||= ENV["FLUXBB_USER"] || "root"+ FLUXBB_PW ||= ENV["FLUXBB_PW"] || ""+ FLUXBB_PREFIX ||= ENV["FLUXBB_PREFIX"] || ""def initializesuper- @client = Mysql2::Client.new(- host: FLUXBB_HOST,- username: FLUXBB_USER,- password: FLUXBB_PW,- database: FLUXBB_DB- )+ @client =+ Mysql2::Client.new(+ host: FLUXBB_HOST,+ username: FLUXBB_USER,+ password: FLUXBB_PW,+ database: FLUXBB_DB,+ )enddef execute@@ -45,64 +45,67 @@ class ImportScripts::FluxBB < ImportScripts::Baseenddef import_groups- puts '', "creating groups"+ puts "", "creating groups"- results = mysql_query(- "SELECT g_id id, g_title name, g_user_title title- FROM #{FLUXBB_PREFIX}groups")+ results =+ mysql_query(+ "SELECT g_id id, g_title name, g_user_title title+ FROM #{FLUXBB_PREFIX}groups",+ )- customgroups = results.select { |group| group['id'] > 2 }+ customgroups = results.select { |group| group["id"] > 2 }create_groups(customgroups) do |group|- { id: group['id'],- name: group['name'],- title: group['title'] }+ { id: group["id"], name: group["name"], title: group["title"] }endenddef import_users- puts '', "creating users"+ puts "", "creating users"- total_count = mysql_query("SELECT count(*) count FROM #{FLUXBB_PREFIX}users;").first['count']+ total_count = mysql_query("SELECT count(*) count FROM #{FLUXBB_PREFIX}users;").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT id, username, realname name, url website, email email, registered created_at,+ results =+ mysql_query(+ "SELECT id, username, realname name, url website, email email, registered created_at,registration_ip registration_ip_address, last_visit last_visit_time,last_email_sent last_emailed_at, location, group_idFROM #{FLUXBB_PREFIX}usersLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1next if all_records_exist? :users, results.map { |u| u["id"].to_i }create_users(results, total: total_count, offset: offset) do |user|- { id: user['id'],- email: user['email'],- username: user['username'],- name: user['name'],- created_at: Time.zone.at(user['created_at']),- website: user['website'],- registration_ip_address: user['registration_ip_address'],- last_seen_at: Time.zone.at(user['last_visit_time']),- last_emailed_at: user['last_emailed_at'] == nil ? 0 : Time.zone.at(user['last_emailed_at']),- location: user['location'],- moderator: user['group_id'] == 2,- admin: user['group_id'] == 1 }+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ name: user["name"],+ created_at: Time.zone.at(user["created_at"]),+ website: user["website"],+ registration_ip_address: user["registration_ip_address"],+ last_seen_at: Time.zone.at(user["last_visit_time"]),+ last_emailed_at:+ user["last_emailed_at"] == nil ? 0 : Time.zone.at(user["last_emailed_at"]),+ location: user["location"],+ moderator: user["group_id"] == 2,+ admin: user["group_id"] == 1,+ }end- groupusers = results.select { |user| user['group_id'] > 2 }+ groupusers = results.select { |user| user["group_id"] > 2 }groupusers.each do |user|- if user['group_id']- user_id = user_id_from_imported_user_id(user['id'])- group_id = group_id_from_imported_group_id(user['group_id'])+ if user["group_id"]+ user_id = user_id_from_imported_user_id(user["id"])+ group_id = group_id_from_imported_group_id(user["group_id"])- if user_id && group_id- GroupUser.find_or_create_by(user_id: user_id, group_id: group_id)- end+ GroupUser.find_or_create_by(user_id: user_id, group_id: group_id) if user_id && group_idendendend@@ -111,33 +114,34 @@ class ImportScripts::FluxBB < ImportScripts::Basedef import_categoriesputs "", "importing top level categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT id, cat_name name, disp_position positionFROM #{FLUXBB_PREFIX}categoriesORDER BY id ASC- ").to_a+ ",+ ).to_a- create_categories(categories) do |category|- {- id: category["id"],- name: category["name"]- }- end+ create_categories(categories) { |category| { id: category["id"], name: category["name"] } }puts "", "importing children categories..."- children_categories = mysql_query("+ children_categories =+ mysql_query(+ "SELECT id, forum_name name, forum_desc description, disp_position position, cat_id parent_category_idFROM #{FLUXBB_PREFIX}forumsORDER BY id- ").to_a+ ",+ ).to_acreate_categories(children_categories) do |category|{- id: "child##{category['id']}",+ id: "child##{category["id"]}",name: category["name"],description: category["description"],- parent_category_id: category_id_from_imported_category_id(category["parent_category_id"])+ parent_category_id: category_id_from_imported_category_id(category["parent_category_id"]),}endend@@ -148,7 +152,9 @@ class ImportScripts::FluxBB < ImportScripts::Basetotal_count = mysql_query("SELECT count(*) count from #{FLUXBB_PREFIX}posts").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.id id,t.id topic_id,t.forum_id category_id,@@ -163,29 +169,30 @@ class ImportScripts::FluxBB < ImportScripts::BaseORDER BY p.postedLIMIT #{BATCH_SIZE}OFFSET #{offset};- ").to_a+ ",+ ).to_abreak if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|skip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_fluxbb_post(m['raw'], m['id'])- mapped[:created_at] = Time.zone.at(m['created_at'])+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_fluxbb_post(m["raw"], m["id"])+ mapped[:created_at] = Time.zone.at(m["created_at"])- if m['id'] == m['first_post_id']- mapped[:category] = category_id_from_imported_category_id("child##{m['category_id']}")- mapped[:title] = CGI.unescapeHTML(m['title'])+ if m["id"] == m["first_post_id"]+ mapped[:category] = category_id_from_imported_category_id("child##{m["category_id"]}")+ mapped[:title] = CGI.unescapeHTML(m["title"])else- parent = topic_lookup_from_imported_post_id(m['first_post_id'])+ parent = topic_lookup_from_imported_post_id(m["first_post_id"])if parentmapped[:topic_id] = parent[:topic_id]else- puts "Parent post #{m['first_post_id']} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"+ puts "Parent post #{m["first_post_id"]} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"skip = trueendend@@ -196,16 +203,16 @@ class ImportScripts::FluxBB < ImportScripts::Baseenddef suspend_users- puts '', "updating banned users"+ puts "", "updating banned users"banned = 0failed = 0- total = mysql_query("SELECT count(*) count FROM #{FLUXBB_PREFIX}bans").first['count']+ total = mysql_query("SELECT count(*) count FROM #{FLUXBB_PREFIX}bans").first["count"]system_user = Discourse.system_usermysql_query("SELECT username, email FROM #{FLUXBB_PREFIX}bans").each do |b|- user = User.find_by_email(b['email'])+ user = User.find_by_email(b["email"])if useruser.suspended_at = Time.nowuser.suspended_till = 200.years.from_now@@ -218,7 +225,7 @@ class ImportScripts::FluxBB < ImportScripts::Basefailed += 1endelse- puts "Not found: #{b['email']}"+ puts "Not found: #{b["email"]}"failed += 1end@@ -233,15 +240,15 @@ class ImportScripts::FluxBB < ImportScripts::Bases.gsub!(/<!-- s(\S+) -->(?:.*)<!-- s(?:\S+) -->/, '\1')# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- s.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/, '[\2](\1)')+ s.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}, '[\2](\1)')# Many bbcode tags have a hash attached to them. Examples:# [url=https://google.com:1qh1i7ky]click here[/url:1qh1i7ky]# [quote="cybereality":b0wtlzex]Some text.[/quote:b0wtlzex]- s.gsub!(/:(?:\w{8})\]/, ']')+ s.gsub!(/:(?:\w{8})\]/, "]")# Remove video tags.- s.gsub!(/(^\[video=.*?\])|(\[\/video\]$)/, '')+ s.gsub!(%r{(^\[video=.*?\])|(\[/video\]$)}, "")s = CGI.unescapeHTML(s)@@ -249,7 +256,7 @@ class ImportScripts::FluxBB < ImportScripts::Base# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- s.gsub!(/\[http(s)?:\/\/(www\.)?/, '[')+ s.gsub!(%r{\[http(s)?://(www\.)?}, "[")senddiff --git a/script/import_scripts/friendsmegplus.rb b/script/import_scripts/friendsmegplus.rbindex d66eed12cc1..3bcab17c90e 100644--- a/script/import_scripts/friendsmegplus.rb+++ b/script/import_scripts/friendsmegplus.rb@@ -2,7 +2,7 @@require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'csv'+require "csv"# Importer for Friends+Me Google+ Exporter (F+MG+E) output.#@@ -32,18 +32,18 @@ require 'csv'# Edit values at the top of the script to fit your preferencesclass ImportScripts::FMGP < ImportScripts::Base-def initializesuper# Set this to the base URL for the site; required for importing videos# typically just 'https:' in production- @site_base_url = 'http://localhost:3000'+ @site_base_url = "http://localhost:3000"@system_user = Discourse.system_user- SiteSetting.max_image_size_kb = 40960- SiteSetting.max_attachment_size_kb = 40960+ SiteSetting.max_image_size_kb = 40_960+ SiteSetting.max_attachment_size_kb = 40_960# handle the same video extension as the rest of Discourse- SiteSetting.authorized_extensions = (SiteSetting.authorized_extensions.split("|") + ['mp4', 'mov', 'webm', 'ogv']).uniq.join("|")+ SiteSetting.authorized_extensions =+ (SiteSetting.authorized_extensions.split("|") + %w[mp4 mov webm ogv]).uniq.join("|")@invalid_bounce_score = 5.0@min_title_words = 3@max_title_words = 14@@ -76,7 +76,7 @@ class ImportScripts::FMGP < ImportScripts::Base@allowlist = nil# Tags to apply to every topic; empty Array to not have any tags applied everywhere- @globaltags = [ "gplus" ]+ @globaltags = ["gplus"]@imagefiles = nil@@ -101,34 +101,30 @@ class ImportScripts::FMGP < ImportScripts::Base@first_date = nil# every argument is a filename, do the right thing based on the file nameARGV.each do |arg|- if arg.end_with?('.csv')+ if arg.end_with?(".csv")# CSV files produced by F+MG+E have "URL";"IsDownloaded";"FileName";"FilePath";"FileSize"- CSV.foreach(arg, headers: true, col_sep: ';') do |row|- @images[row[0]] = {- filename: row[2],- filepath: row[3],- filesize: row[4]- }+ CSV.foreach(arg, headers: true, col_sep: ";") do |row|+ @images[row[0]] = { filename: row[2], filepath: row[3], filesize: row[4] }endelsif arg.end_with?("upload-paths.txt")@imagefiles = File.open(arg, "w")- elsif arg.end_with?('categories.json')+ elsif arg.end_with?("categories.json")@categories_filename = arg@categories = load_fmgp_json(arg)elsif arg.end_with?("usermap.json")@usermap = load_fmgp_json(arg)- elsif arg.end_with?('blocklist.json')+ elsif arg.end_with?("blocklist.json")@blocklist = load_fmgp_json(arg).map { |i| i.to_s }.to_set- elsif arg.end_with?('allowlist.json')+ elsif arg.end_with?("allowlist.json")@allowlist = load_fmgp_json(arg).map { |i| i.to_s }.to_set- elsif arg.end_with?('.json')+ elsif arg.end_with?(".json")@feeds << load_fmgp_json(arg)- elsif arg == '--dry-run'+ elsif arg == "--dry-run"@dryrun = trueelsif arg.start_with?("--last-date=")- @last_date = Time.zone.parse(arg.gsub(/.*=/, ''))+ @last_date = Time.zone.parse(arg.gsub(/.*=/, ""))elsif arg.start_with?("--first-date=")- @first_date = Time.zone.parse(arg.gsub(/.*=/, ''))+ @first_date = Time.zone.parse(arg.gsub(/.*=/, ""))elseraise RuntimeError.new("unknown argument #{arg}")end@@ -153,7 +149,6 @@ class ImportScripts::FMGP < ImportScripts::Base@blocked_posts = 0# count uploaded file size@totalsize = 0-enddef execute@@ -222,7 +217,9 @@ class ImportScripts::FMGP < ImportScripts::Basecategories_new = "#{@categories_filename}.new"File.open(categories_new, "w") do |f|f.write(@categories.to_json)- raise RuntimeError.new("Category file missing categories for #{incomplete_categories}, edit #{categories_new} and rename it to #{@category_filename} before running the same import")+ raise RuntimeError.new(+ "Category file missing categories for #{incomplete_categories}, edit #{categories_new} and rename it to #{@category_filename} before running the same import",+ )endendend@@ -233,28 +230,32 @@ class ImportScripts::FMGP < ImportScripts::Base@categories.each do |id, cat|if cat["parent"].present? && !cat["parent"].empty?# Two separate sub-categories can have the same name, so need to identify by parent- Category.where(name: cat["category"]).each do |category|- parent = Category.where(id: category.parent_category_id).first- @cats[id] = category if parent.name == cat["parent"]- end+ Category+ .where(name: cat["category"])+ .each do |category|+ parent = Category.where(id: category.parent_category_id).first+ @cats[id] = category if parent.name == cat["parent"]+ endelseif category = Category.where(name: cat["category"]).first@cats[id] = categoryelsif @create_categoriesparams = {}- params[:name] = cat['category']+ params[:name] = cat["category"]params[:id] = id- puts "Creating #{cat['category']}"+ puts "Creating #{cat["category"]}"category = create_category(params, id)@cats[id] = categoryendend- raise RuntimeError.new("Could not find category #{cat["category"]} for #{cat}") if @cats[id].nil?+ if @cats[id].nil?+ raise RuntimeError.new("Could not find category #{cat["category"]} for #{cat}")+ endendenddef import_users- puts '', "Importing Google+ post and comment author users..."+ puts "", "Importing Google+ post and comment author users..."# collect authors of both posts and comments@feeds.each do |feed|@@ -263,14 +264,10 @@ class ImportScripts::FMGP < ImportScripts::Basecommunity["categories"].each do |category|category["posts"].each do |post|import_author_user(post["author"])- if post["message"].present?- import_message_users(post["message"])- end+ import_message_users(post["message"]) if post["message"].present?post["comments"].each do |comment|import_author_user(comment["author"])- if comment["message"].present?- import_message_users(comment["message"])- end+ import_message_users(comment["message"]) if comment["message"].present?endendend@@ -282,12 +279,7 @@ class ImportScripts::FMGP < ImportScripts::Base# now create them allcreate_users(@newusers) do |id, u|- {- id: id,- email: u[:email],- name: u[:name],- post_create_action: u[:post_create_action]- }+ { id: id, email: u[:email], name: u[:name], post_create_action: u[:post_create_action] }endend@@ -308,7 +300,8 @@ class ImportScripts::FMGP < ImportScripts::Basedef import_google_user(id, name)if !@emails[id].present?- google_user_info = UserAssociatedAccount.find_by(provider_name: 'google_oauth2', provider_uid: id.to_i)+ google_user_info =+ UserAssociatedAccount.find_by(provider_name: "google_oauth2", provider_uid: id.to_i)if google_user_info.nil?# create new google user on system; expect this user to merge# when they later log in with google authentication@@ -320,36 +313,39 @@ class ImportScripts::FMGP < ImportScripts::Base@newusers[id] = {email: email,name: name,- post_create_action: proc do |newuser|- newuser.approved = true- newuser.approved_by_id = @system_user.id- newuser.approved_at = newuser.created_at- if @blocklist.include?(id.to_s)- now = DateTime.now- forever = 1000.years.from_now- # you can suspend as well if you want your blocklist to- # be hard to recover from- #newuser.suspended_at = now- #newuser.suspended_till = forever- newuser.silenced_till = forever- end- newuser.save- @users[id] = newuser- UserAssociatedAccount.create(provider_name: 'google_oauth2', user_id: newuser.id, provider_uid: id)- # Do not send email to the invalid email addresses- # this can be removed after merging with #7162- s = UserStat.where(user_id: newuser.id).first- s.bounce_score = @invalid_bounce_score- s.reset_bounce_score_after = 1000.years.from_now- s.save- end+ post_create_action:+ proc do |newuser|+ newuser.approved = true+ newuser.approved_by_id = @system_user.id+ newuser.approved_at = newuser.created_at+ if @blocklist.include?(id.to_s)+ now = DateTime.now+ forever = 1000.years.from_now+ # you can suspend as well if you want your blocklist to+ # be hard to recover from+ #newuser.suspended_at = now+ #newuser.suspended_till = forever+ newuser.silenced_till = forever+ end+ newuser.save+ @users[id] = newuser+ UserAssociatedAccount.create(+ provider_name: "google_oauth2",+ user_id: newuser.id,+ provider_uid: id,+ )+ # Do not send email to the invalid email addresses+ # this can be removed after merging with #7162+ s = UserStat.where(user_id: newuser.id).first+ s.bounce_score = @invalid_bounce_score+ s.reset_bounce_score_after = 1000.years.from_now+ s.save+ end,}else# user already on systemu = User.find(google_user_info.user_id)- if u.silenced? || u.suspended?- @blocklist.add(id)- end+ @blocklist.add(id) if u.silenced? || u.suspended?@users[id] = uemail = u.emailend@@ -362,7 +358,7 @@ class ImportScripts::FMGP < ImportScripts::Base# - A google+ post is a discourse topic# - A google+ comment is a discourse post- puts '', "Importing Google+ posts and comments..."+ puts "", "Importing Google+ posts and comments..."@feeds.each do |feed|feed["accounts"].each do |account|@@ -371,14 +367,16 @@ class ImportScripts::FMGP < ImportScripts::Basecategory["posts"].each do |post|# G+ post / Discourse topicimport_topic(post, category)- print("\r#{@topics_imported}/#{@posts_imported} topics/posts (skipped: #{@topics_skipped}/#{@posts_skipped} blocklisted: #{@blocked_topics}/#{@blocked_posts}) ")+ print(+ "\r#{@topics_imported}/#{@posts_imported} topics/posts (skipped: #{@topics_skipped}/#{@posts_skipped} blocklisted: #{@blocked_topics}/#{@blocked_posts}) ",+ )endendendendend- puts ''+ puts ""enddef import_topic(post, category)@@ -431,9 +429,7 @@ class ImportScripts::FMGP < ImportScripts::Basereturn nil if !@frst_date.nil? && created_at < @first_dateuser_id = user_id_from_imported_user_id(post_author_id)- if user_id.nil?- user_id = @users[post["author"]["id"]].id- end+ user_id = @users[post["author"]["id"]].id if user_id.nil?mapped = {id: post["id"],@@ -472,7 +468,8 @@ class ImportScripts::FMGP < ImportScripts::Basedef title_text(post, created_at)words = message_text(post["message"])- if words.empty? || words.join("").length < @min_title_characters || words.length < @min_title_words+ if words.empty? || words.join("").length < @min_title_characters ||+ words.length < @min_title_words# database has minimum length# short posts appear not to work well as titles most of the time (in practice)return untitled(post["author"]["name"], created_at)@@ -483,17 +480,13 @@ class ImportScripts::FMGP < ImportScripts::Base(@min_title_words..(words.length - 1)).each do |i|# prefer full stop- if words[i].end_with?(".")- lastword = i- end+ lastword = i if words[i].end_with?(".")endif lastword.nil?# fall back on other punctuation(@min_title_words..(words.length - 1)).each do |i|- if words[i].end_with?(',', ';', ':', '?')- lastword = i- end+ lastword = i if words[i].end_with?(",", ";", ":", "?")endend@@ -516,9 +509,7 @@ class ImportScripts::FMGP < ImportScripts::Basetext_types = [0, 3]message.each do |fragment|if text_types.include?(fragment[0])- fragment[1].split().each do |word|- words << word- end+ fragment[1].split().each { |word| words << word }elsif fragment[0] == 2# use the display text of a linkwords << fragment[1]@@ -543,14 +534,10 @@ class ImportScripts::FMGP < ImportScripts::Baselines << "\n#{formatted_link(post["image"]["proxy"])}\n"endif post["images"].present?- post["images"].each do |image|- lines << "\n#{formatted_link(image["proxy"])}\n"- end+ post["images"].each { |image| lines << "\n#{formatted_link(image["proxy"])}\n" }endif post["videos"].present?- post["videos"].each do |video|- lines << "\n#{formatted_link(video["proxy"])}\n"- end+ post["videos"].each { |video| lines << "\n#{formatted_link(video["proxy"])}\n" }endif post["link"].present? && post["link"]["url"].present?url = post["link"]["url"]@@ -575,12 +562,8 @@ class ImportScripts::FMGP < ImportScripts::Baseif fragment[2].nil?textelse- if fragment[2]["italic"].present?- text = "<i>#{text}</i>"- end- if fragment[2]["bold"].present?- text = "<b>#{text}</b>"- end+ text = "<i>#{text}</i>" if fragment[2]["italic"].present?+ text = "<b>#{text}</b>" if fragment[2]["bold"].present?if fragment[2]["strikethrough"].present?# s more likely than del to represent user intent?text = "<s>#{text}</s>"@@ -594,9 +577,7 @@ class ImportScripts::FMGP < ImportScripts::Baseformatted_link_text(fragment[2], fragment[1])elsif fragment[0] == 3# reference to a user- if @usermap.include?(fragment[2].to_s)- return "@#{@usermap[fragment[2].to_s]}"- end+ return "@#{@usermap[fragment[2].to_s]}" if @usermap.include?(fragment[2].to_s)if fragment[2].nil?# deleted G+ users show up with a null IDreturn "<b>+#{fragment[1]}</b>"@@ -606,12 +587,18 @@ class ImportScripts::FMGP < ImportScripts::Base# user was in this import's authors"@#{user.username} "else- if google_user_info = UserAssociatedAccount.find_by(provider_name: 'google_oauth2', provider_uid: fragment[2])+ if google_user_info =+ UserAssociatedAccount.find_by(+ provider_name: "google_oauth2",+ provider_uid: fragment[2],+ )# user was not in this import, but has logged in or been imported otherwiseuser = User.find(google_user_info.user_id)"@#{user.username} "else- raise RuntimeError.new("Google user #{fragment[1]} (id #{fragment[2]}) not imported") if !@dryrun+ if !@dryrun+ raise RuntimeError.new("Google user #{fragment[1]} (id #{fragment[2]}) not imported")+ end# if you want to fall back to their G+ name, just erase the raise above,# but this should not happen"<b>+#{fragment[1]}</b>"@@ -681,6 +668,4 @@ class ImportScripts::FMGP < ImportScripts::Baseendend-if __FILE__ == $0- ImportScripts::FMGP.new.perform-end+ImportScripts::FMGP.new.perform if __FILE__ == $0diff --git a/script/import_scripts/getsatisfaction.rb b/script/import_scripts/getsatisfaction.rbindex 50f8613e683..0458c84f946 100644--- a/script/import_scripts/getsatisfaction.rb+++ b/script/import_scripts/getsatisfaction.rb@@ -22,15 +22,14 @@# that correctly and will import the replies in the wrong order.# You should run `rake posts:reorder_posts` after the import.-require 'csv'-require 'set'+require "csv"+require "set"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'reverse_markdown' # gem 'reverse_markdown'+require "reverse_markdown" # gem 'reverse_markdown'# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/getsatisfaction.rb DIRNAMEclass ImportScripts::GetSatisfaction < ImportScripts::Base-IMPORT_ARCHIVED_TOPICS = false# The script classifies each topic as private when at least one associated category@@ -85,41 +84,43 @@ class ImportScripts::GetSatisfaction < ImportScripts::Baseprevious_line = nilFile.open(target_filename, "w") do |file|- File.open(source_filename).each_line do |line|- line.gsub!(/(?<![^\\]\\)\\"/, '""')- line.gsub!(/\\\\/, '\\')-- if previous_line- previous_line << "\n" unless line.starts_with?(",")- line = "#{previous_line}#{line}"- previous_line = nil+ File+ .open(source_filename)+ .each_line do |line|+ line.gsub!(/(?<![^\\]\\)\\"/, '""')+ line.gsub!(/\\\\/, '\\')++ if previous_line+ previous_line << "\n" unless line.starts_with?(",")+ line = "#{previous_line}#{line}"+ previous_line = nil+ end++ if line.gsub!(/,\+1\\\R$/m, ',"+1"').present?+ previous_line = line+ else+ file.puts(line)+ endend- if line.gsub!(/,\+1\\\R$/m, ',"+1"').present?- previous_line = line- else- file.puts(line)- end- end-file.puts(previous_line) if previous_lineendendenddef csv_parse(table_name)- CSV.foreach(csv_filename(table_name),- headers: true,- header_converters: :symbol,- skip_blanks: true,- encoding: 'bom|utf-8') { |row| yield row }+ CSV.foreach(+ csv_filename(table_name),+ headers: true,+ header_converters: :symbol,+ skip_blanks: true,+ encoding: "bom|utf-8",+ ) { |row| yield row }enddef total_rows(table_name)- CSV.foreach(csv_filename(table_name),- headers: true,- skip_blanks: true,- encoding: 'bom|utf-8')+ CSV+ .foreach(csv_filename(table_name), headers: true, skip_blanks: true, encoding: "bom|utf-8").inject(0) { |c, _| c + 1 }end@@ -138,13 +139,11 @@ class ImportScripts::GetSatisfaction < ImportScripts::Basename: row[:realname],username: row[:nickname],created_at: DateTime.parse(row[:joined_date]),- active: true+ active: true,}count += 1- if count % BATCH_SIZE == 0- import_users_batch!(users, count - users.length, total)- end+ import_users_batch!(users, count - users.length, total) if count % BATCH_SIZE == 0endimport_users_batch!(users, count - users.length, total)@@ -153,9 +152,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Basedef import_users_batch!(users, offset, total)return if users.empty?- create_users(users, offset: offset, total: total) do |user|- user- end+ create_users(users, offset: offset, total: total) { |user| user }users.clearend@@ -168,13 +165,11 @@ class ImportScripts::GetSatisfaction < ImportScripts::Baserows << {id: row[:category_id],name: row[:name],- description: row[:description].present? ? normalize_raw!(row[:description]) : nil+ description: row[:description].present? ? normalize_raw!(row[:description]) : nil,}end- create_categories(rows) do |row|- row- end+ create_categories(rows) { |row| row }enddef import_topic_id(topic_id)@@ -200,7 +195,13 @@ class ImportScripts::GetSatisfaction < ImportScripts::Baseelsetopic = map_post(row)topic[:id] = topic_id- topic[:title] = row[:subject].present? ? row[:subject].strip[0...255] : "Topic title missing"+ topic[:title] = (+ if row[:subject].present?+ row[:subject].strip[0...255]+ else+ "Topic title missing"+ end+ )topic[:category] = category_id(row)topic[:archived] = row[:archived_at].present?@@ -210,9 +211,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Basetopics << topiccount += 1- if count % BATCH_SIZE == 0- import_topics_batch!(topics, count - topics.length, total)- end+ import_topics_batch!(topics, count - topics.length, total) if count % BATCH_SIZE == 0endimport_topics_batch!(topics, count - topics.length, total)@@ -290,9 +289,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Baseposts << postcount += 1- if count % BATCH_SIZE == 0- import_posts_batch!(posts, count - posts.length, total)- end+ import_posts_batch!(posts, count - posts.length, total) if count % BATCH_SIZE == 0endimport_posts_batch!(posts, count - posts.length, total)@@ -324,7 +321,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Base{user_id: user_id_from_imported_user_id(row[:user_id]) || Discourse.system_user.id,created_at: DateTime.parse(row[:created_at]),- raw: normalize_raw!(row[:formatted_content])+ raw: normalize_raw!(row[:formatted_content]),}end@@ -334,7 +331,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Base# hoist codehoisted = {}- raw.gsub!(/(<pre>\s*)?<code>(.*?)<\/code>(\s*<\/pre>)?/mi) do+ raw.gsub!(%r{(<pre>\s*)?<code>(.*?)</code>(\s*</pre>)?}mi) docode = $2hoist = SecureRandom.hex# tidy code, wow, this is impressively crazy@@ -350,9 +347,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Base# in this case double space works best ... so oddraw.gsub!(" ", "\n\n")- hoisted.each do |hoist, code|- raw.gsub!(hoist, "\n```\n#{code}\n```\n")- end+ hoisted.each { |hoist, code| raw.gsub!(hoist, "\n```\n#{code}\n```\n") }raw = CGI.unescapeHTML(raw)raw = ReverseMarkdown.convert(raw)@@ -360,7 +355,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Baseenddef create_permalinks- puts '', 'Creating Permalinks...', ''+ puts "", "Creating Permalinks...", ""Topic.listable_topics.find_each do |topic|tcf = topic.first_post.custom_fields@@ -372,7 +367,6 @@ class ImportScripts::GetSatisfaction < ImportScripts::Baseendendend-endunless ARGV[0] && Dir.exist?(ARGV[0])diff --git a/script/import_scripts/google_groups.rb b/script/import_scripts/google_groups.rbindex 494346292c1..1b6fa4b420a 100755--- a/script/import_scripts/google_groups.rb+++ b/script/import_scripts/google_groups.rb@@ -20,19 +20,18 @@ DEFAULT_COOKIES_TXT = "/shared/import/cookies.txt"ABORT_AFTER_SKIPPED_TOPIC_COUNT = 10def driver- @driver ||= begin- chrome_args = ["disable-gpu"]- chrome_args << "headless" unless ENV["NOT_HEADLESS"] == '1'- chrome_args << "no-sandbox" if inside_container?- options = Selenium::WebDriver::Chrome::Options.new(args: chrome_args)- Selenium::WebDriver.for(:chrome, options: options)- end+ @driver ||=+ begin+ chrome_args = ["disable-gpu"]+ chrome_args << "headless" unless ENV["NOT_HEADLESS"] == "1"+ chrome_args << "no-sandbox" if inside_container?+ options = Selenium::WebDriver::Chrome::Options.new(args: chrome_args)+ Selenium::WebDriver.for(:chrome, options: options)+ endenddef inside_container?- File.foreach("/proc/1/cgroup") do |line|- return true if line.include?("docker")- end+ File.foreach("/proc/1/cgroup") { |line| return true if line.include?("docker") }falseend@@ -79,35 +78,38 @@ def base_urlenddef crawl_topics- 1.step(nil, 100).each do |start|- url = "#{base_url}/#{@groupname}[#{start}-#{start + 99}]"- get(url)-- begin- if start == 1 && find("h2").text == "Error 403"- exit_with_error(<<~TEXT.red.bold)+ 1+ .step(nil, 100)+ .each do |start|+ url = "#{base_url}/#{@groupname}[#{start}-#{start + 99}]"+ get(url)++ begin+ exit_with_error(<<~TEXT.red.bold) if start == 1 && find("h2").text == "Error 403"Unable to find topics. Try running the script with the "--domain example.com"option if you are a G Suite user and your group's URL contains a path withyour domain that looks like "/a/example.com".TEXT+ rescue Selenium::WebDriver::Error::NoSuchElementError+ # Ignore this error. It simply means there wasn't an error.end- rescue Selenium::WebDriver::Error::NoSuchElementError- # Ignore this error. It simply means there wasn't an error.- end- topic_urls = extract(".subject a[href*='#{@groupname}']") { |a| a["href"].sub("/d/topic/", "/forum/?_escaped_fragment_=topic/") }- break if topic_urls.size == 0+ topic_urls =+ extract(".subject a[href*='#{@groupname}']") do |a|+ a["href"].sub("/d/topic/", "/forum/?_escaped_fragment_=topic/")+ end+ break if topic_urls.size == 0- topic_urls.each do |topic_url|- crawl_topic(topic_url)+ topic_urls.each do |topic_url|+ crawl_topic(topic_url)- # abort if this in an incremental crawl and there were too many consecutive, skipped topics- if @finished && @skipped_topic_count > ABORT_AFTER_SKIPPED_TOPIC_COUNT- puts "Skipping all other topics, because this is an incremental crawl.".green- return+ # abort if this in an incremental crawl and there were too many consecutive, skipped topics+ if @finished && @skipped_topic_count > ABORT_AFTER_SKIPPED_TOPIC_COUNT+ puts "Skipping all other topics, because this is an incremental crawl.".green+ return+ endendend- endenddef crawl_topic(url)@@ -126,17 +128,14 @@ def crawl_topic(url)messages_crawled = falseextract(".subject a[href*='#{@groupname}']") do |a|- [- a["href"].sub("/d/msg/", "/forum/message/raw?msg="),- a["title"].empty?- ]+ [a["href"].sub("/d/msg/", "/forum/message/raw?msg="), a["title"].empty?]end.each do |msg_url, might_be_deleted|messages_crawled |= crawl_message(msg_url, might_be_deleted)end@skipped_topic_count = skippable && messages_crawled ? 0 : @skipped_topic_count + 1@scraped_topic_urls << url-rescue+rescue StandardErrorputs "Failed to scrape topic at #{url}".redraise if @abort_on_errorend@@ -144,18 +143,16 @@ enddef crawl_message(url, might_be_deleted)get(url)- filename = File.join(@path, "#{url[/#{@groupname}\/(.+)/, 1].sub("/", "-")}.eml")+ filename = File.join(@path, "#{url[%r{#{@groupname}/(.+)}, 1].sub("/", "-")}.eml")content = find("pre")["innerText"]if !@first_message_checked@first_message_checked = true- if content.match?(/From:.*\.\.\.@.*/i) && !@force_import- exit_with_error(<<~TEXT.red.bold)+ exit_with_error(<<~TEXT.red.bold) if content.match?(/From:.*\.\.\.@.*/i) && !@force_importIt looks like you do not have permissions to see email addresses. Aborting.Use the --force option to import anyway.TEXT- endendold_md5 = Digest::MD5.file(filename) if File.exist?(filename)@@ -169,7 +166,7 @@ rescue Selenium::WebDriver::Error::NoSuchElementErrorputs "Failed to scrape message at #{url}".redraise if @abort_on_errorend-rescue+rescue StandardErrorputs "Failed to scrape message at #{url}".redraise if @abort_on_errorend@@ -178,10 +175,7 @@ def loginputs "Logging in..."get("https://google.com/404")- add_cookies(- "myaccount.google.com",- "google.com"- )+ add_cookies("myaccount.google.com", "google.com")get("https://myaccount.google.com/?utm_source=sign_in_no_continue")@@ -193,20 +187,24 @@ def loginenddef add_cookies(*domains)- File.readlines(@cookies).each do |line|- parts = line.chomp.split("\t")- next if parts.size != 7 || !domains.any? { |domain| parts[0] =~ /^\.?#{Regexp.escape(domain)}$/ }-- driver.manage.add_cookie(- domain: parts[0],- httpOnly: "true".casecmp?(parts[1]),- path: parts[2],- secure: "true".casecmp?(parts[3]),- expires: parts[4] == "0" ? nil : DateTime.strptime(parts[4], "%s"),- name: parts[5],- value: parts[6]- )- end+ File+ .readlines(@cookies)+ .each do |line|+ parts = line.chomp.split("\t")+ if parts.size != 7 || !domains.any? { |domain| parts[0] =~ /^\.?#{Regexp.escape(domain)}$/ }+ next+ end++ driver.manage.add_cookie(+ domain: parts[0],+ httpOnly: "true".casecmp?(parts[1]),+ path: parts[2],+ secure: "true".casecmp?(parts[3]),+ expires: parts[4] == "0" ? nil : DateTime.strptime(parts[4], "%s"),+ name: parts[5],+ value: parts[6],+ )+ endenddef wait_for_url@@ -240,10 +238,7 @@ def crawlcrawl_topics@finished = trueensure- File.write(status_filename, {- finished: @finished,- urls: @scraped_topic_urls- }.to_yaml)+ File.write(status_filename, { finished: @finished, urls: @scraped_topic_urls }.to_yaml)endelapsed = Time.now - start_time@@ -258,20 +253,25 @@ def parse_arguments@abort_on_error = false@cookies = DEFAULT_COOKIES_TXT if File.exist?(DEFAULT_COOKIES_TXT)- parser = OptionParser.new do |opts|- opts.banner = "Usage: google_groups.rb [options]"-- opts.on("-g", "--groupname GROUPNAME") { |v| @groupname = v }- opts.on("-d", "--domain DOMAIN") { |v| @domain = v }- opts.on("-c", "--cookies PATH", "path to cookies.txt") { |v| @cookies = v }- opts.on("--path PATH", "output path for emails") { |v| @path = v }- opts.on("-f", "--force", "force import when user isn't allowed to see email addresses") { @force_import = true }- opts.on("-a", "--abort-on-error", "abort crawl on error instead of skipping message") { @abort_on_error = true }- opts.on("-h", "--help") do- puts opts- exit+ parser =+ OptionParser.new do |opts|+ opts.banner = "Usage: google_groups.rb [options]"++ opts.on("-g", "--groupname GROUPNAME") { |v| @groupname = v }+ opts.on("-d", "--domain DOMAIN") { |v| @domain = v }+ opts.on("-c", "--cookies PATH", "path to cookies.txt") { |v| @cookies = v }+ opts.on("--path PATH", "output path for emails") { |v| @path = v }+ opts.on("-f", "--force", "force import when user isn't allowed to see email addresses") do+ @force_import = true+ end+ opts.on("-a", "--abort-on-error", "abort crawl on error instead of skipping message") do+ @abort_on_error = true+ end+ opts.on("-h", "--help") do+ puts opts+ exit+ endend- endbeginparser.parse!@@ -279,10 +279,12 @@ def parse_argumentsexit_with_error(e.message, "", parser)end- mandatory = [:groupname, :cookies]+ mandatory = %i[groupname cookies]missing = mandatory.select { |name| instance_variable_get("@#{name}").nil? }- exit_with_error("Missing arguments: #{missing.join(', ')}".red.bold, "", parser, "") if missing.any?+ if missing.any?+ exit_with_error("Missing arguments: #{missing.join(", ")}".red.bold, "", parser, "")+ endexit_with_error("cookies.txt not found at #{@cookies}".red.bold, "") if !File.exist?(@cookies)@path = File.join(DEFAULT_OUTPUT_PATH, @groupname) if @path.nil?diff --git a/script/import_scripts/higher_logic.rb b/script/import_scripts/higher_logic.rbindex fe6e19641dd..06820311264 100644--- a/script/import_scripts/higher_logic.rb+++ b/script/import_scripts/higher_logic.rb@@ -4,7 +4,6 @@ require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::HigherLogic < ImportScripts::Base-HIGHERLOGIC_DB = "higherlogic"BATCH_SIZE = 1000ATTACHMENT_DIR = "/shared/import/data/attachments"@@ -12,11 +11,7 @@ class ImportScripts::HigherLogic < ImportScripts::Basedef initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- database: HIGHERLOGIC_DB- )+ @client = Mysql2::Client.new(host: "localhost", username: "root", database: HIGHERLOGIC_DB)enddef execute@@ -29,7 +24,7 @@ class ImportScripts::HigherLogic < ImportScripts::Baseenddef import_groups- puts '', 'importing groups'+ puts "", "importing groups"groups = mysql_query <<-SQLSELECT CommunityKey, CommunityName@@ -37,16 +32,11 @@ class ImportScripts::HigherLogic < ImportScripts::BaseORDER BY CommunityNameSQL- create_groups(groups) do |group|- {- id: group['CommunityKey'],- name: group['CommunityName']- }- end+ create_groups(groups) { |group| { id: group["CommunityKey"], name: group["CommunityName"] } }enddef import_users- puts '', 'importing users'+ puts "", "importing users"total_count = mysql_query("SELECT count(*) FROM Contact").first["count"]batches(BATCH_SIZE) do |offset|@@ -59,43 +49,42 @@ class ImportScripts::HigherLogic < ImportScripts::Basebreak if results.size < 1- next if all_records_exist? :users, results.map { |u| u['ContactKey'] }+ next if all_records_exist? :users, results.map { |u| u["ContactKey"] }create_users(results, total: total_count, offset: offset) do |user|- next if user['EmailAddress'].blank?+ next if user["EmailAddress"].blank?{- id: user['ContactKey'],- email: user['EmailAddress'],- name: "#{user['FirstName']} #{user['LastName']}",- created_at: user['CreatedOn'] == nil ? 0 : Time.zone.at(user['CreatedOn']),- bio_raw: user['Bio'],- active: user['UserStatus'] == "Active",- admin: user['HLAdminFlag'] == 1+ id: user["ContactKey"],+ email: user["EmailAddress"],+ name: "#{user["FirstName"]} #{user["LastName"]}",+ created_at: user["CreatedOn"] == nil ? 0 : Time.zone.at(user["CreatedOn"]),+ bio_raw: user["Bio"],+ active: user["UserStatus"] == "Active",+ admin: user["HLAdminFlag"] == 1,}endendenddef import_group_users- puts '', 'importing group users'+ puts "", "importing group users"- group_users = mysql_query(<<-SQL+ group_users = mysql_query(<<-SQL).to_aSELECT CommunityKey, ContactKeyFROM CommunityMemberSQL- ).to_agroup_users.each do |row|- next unless user_id = user_id_from_imported_user_id(row['ContactKey'])- next unless group_id = group_id_from_imported_group_id(row['CommunityKey'])- puts '', '.'+ next unless user_id = user_id_from_imported_user_id(row["ContactKey"])+ next unless group_id = group_id_from_imported_group_id(row["CommunityKey"])+ puts "", "."GroupUser.find_or_create_by(user_id: user_id, group_id: group_id)endenddef import_categories- puts '', 'importing categories'+ puts "", "importing categories"categories = mysql_query <<-SQLSELECT DiscussionKey, DiscussionName@@ -103,15 +92,12 @@ class ImportScripts::HigherLogic < ImportScripts::BaseSQLcreate_categories(categories) do |category|- {- id: category['DiscussionKey'],- name: category['DiscussionName']- }+ { id: category["DiscussionKey"], name: category["DiscussionName"] }endenddef import_posts- puts '', 'importing topics and posts'+ puts "", "importing topics and posts"total_count = mysql_query("SELECT count(*) FROM DiscussionPost").first["count"]batches(BATCH_SIZE) do |offset|@@ -131,28 +117,28 @@ class ImportScripts::HigherLogic < ImportScripts::BaseSQLbreak if results.size < 1- next if all_records_exist? :posts, results.map { |p| p['MessageKey'] }+ next if all_records_exist? :posts, results.map { |p| p["MessageKey"] }create_posts(results, total: total_count, offset: offset) do |post|- raw = preprocess_raw(post['Body'])+ raw = preprocess_raw(post["Body"])mapped = {- id: post['MessageKey'],- user_id: user_id_from_imported_user_id(post['ContactKey']),+ id: post["MessageKey"],+ user_id: user_id_from_imported_user_id(post["ContactKey"]),raw: raw,- created_at: Time.zone.at(post['CreatedOn']),+ created_at: Time.zone.at(post["CreatedOn"]),}- if post['ParentMessageKey'].nil?- mapped[:category] = category_id_from_imported_category_id(post['DiscussionKey']).to_i- mapped[:title] = CGI.unescapeHTML(post['Subject'])- mapped[:pinned] = post['PinnedFlag'] == 1+ if post["ParentMessageKey"].nil?+ mapped[:category] = category_id_from_imported_category_id(post["DiscussionKey"]).to_i+ mapped[:title] = CGI.unescapeHTML(post["Subject"])+ mapped[:pinned] = post["PinnedFlag"] == 1else- topic = topic_lookup_from_imported_post_id(post['ParentMessageKey'])+ topic = topic_lookup_from_imported_post_id(post["ParentMessageKey"])if topic.present?mapped[:topic_id] = topic[:topic_id]else- puts "Parent post #{post['ParentMessageKey']} doesn't exist. Skipping."+ puts "Parent post #{post["ParentMessageKey"]} doesn't exist. Skipping."nextendend@@ -163,20 +149,19 @@ class ImportScripts::HigherLogic < ImportScripts::Baseenddef import_attachments- puts '', 'importing attachments'+ puts "", "importing attachments"count = 0- total_attachments = mysql_query(<<-SQL+ total_attachments = mysql_query(<<-SQL).first["count"]SELECT COUNT(*) countFROM LibraryEntryFile lJOIN DiscussionPost p ON p.AttachmentDocumentKey = l.DocumentKeyWHERE p.CreatedOn > '2020-01-01 00:00:00'SQL- ).first['count']batches(BATCH_SIZE) do |offset|- attachments = mysql_query(<<-SQL+ attachments = mysql_query(<<-SQL).to_aSELECT l.VersionName,l.FileExtension,p.MessageKey@@ -186,17 +171,16 @@ class ImportScripts::HigherLogic < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- ).to_abreak if attachments.empty?attachments.each do |a|print_status(count += 1, total_attachments, get_start_time("attachments"))- original_filename = "#{a['VersionName']}.#{a['FileExtension']}"+ original_filename = "#{a["VersionName"]}.#{a["FileExtension"]}"path = File.join(ATTACHMENT_DIR, original_filename)if File.exist?(path)- if post = Post.find(post_id_from_imported_post_id(a['MessageKey']))+ if post = Post.find(post_id_from_imported_post_id(a["MessageKey"]))filename = File.basename(original_filename)upload = create_upload(post.user.id, path, filename)@@ -205,7 +189,9 @@ class ImportScripts::HigherLogic < ImportScripts::Basepost.raw << "\n\n" << htmlpost.save!- PostUpload.create!(post: post, upload: upload) unless PostUpload.where(post: post, upload: upload).exists?+ unless PostUpload.where(post: post, upload: upload).exists?+ PostUpload.create!(post: post, upload: upload)+ endendendend@@ -217,7 +203,7 @@ class ImportScripts::HigherLogic < ImportScripts::Baseraw = body.dup# trim off any post text beyond ---- to remove email threading- raw = raw.slice(0..(raw.index('------'))) || raw+ raw = raw.slice(0..(raw.index("------"))) || rawraw = HtmlToMarkdown.new(raw).to_markdownrawdiff --git a/script/import_scripts/ipboard.rb b/script/import_scripts/ipboard.rbindex dcd8cb03f52..4f5c5ed0bd4 100644--- a/script/import_scripts/ipboard.rb+++ b/script/import_scripts/ipboard.rb@@ -3,13 +3,13 @@require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'+require "htmlentities"begin- require 'reverse_markdown' # https://github.com/jqr/php-serialize+ require "reverse_markdown" # https://github.com/jqr/php-serializerescue LoadErrorputs- puts 'reverse_markdown not found.'- puts 'Add to Gemfile, like this: '+ puts "reverse_markdown not found."+ puts "Add to Gemfile, like this: "putsputs "echo gem \\'reverse_markdown\\' >> Gemfile"puts "bundle install"@@ -32,28 +32,27 @@ export USERDIR="user"=endclass ImportScripts::IpboardSQL < ImportScripts::Base-- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "ipboard"- DB_PW ||= ENV['DB_PW'] || "ipboard"- DB_USER ||= ENV['DB_USER'] || "ipboard"- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "ipb_"- IMPORT_AFTER ||= ENV['IMPORT_AFTER'] || "1970-01-01"- UPLOADS ||= ENV['UPLOADS'] || "http://UPLOADS+LOCATION+IS+NOT+SET/uploads"- USERDIR ||= ENV['USERDIR'] || "user"- URL ||= ENV['URL'] || "https://forum.example.com"- AVATARS_DIR ||= ENV['AVATARS_DIR'] || '/home/pfaffman/data/example.com/avatars/'+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "ipboard"+ DB_PW ||= ENV["DB_PW"] || "ipboard"+ DB_USER ||= ENV["DB_USER"] || "ipboard"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "ipb_"+ IMPORT_AFTER ||= ENV["IMPORT_AFTER"] || "1970-01-01"+ UPLOADS ||= ENV["UPLOADS"] || "http://UPLOADS+LOCATION+IS+NOT+SET/uploads"+ USERDIR ||= ENV["USERDIR"] || "user"+ URL ||= ENV["URL"] || "https://forum.example.com"+ AVATARS_DIR ||= ENV["AVATARS_DIR"] || "/home/pfaffman/data/example.com/avatars/"BATCH_SIZE = 1000ID_FIRST = trueQUIET = trueDEBUG = false- GALLERY_CAT_ID = 1234567- GALLERY_CAT_NAME = 'galeria'- EMO_DIR ||= ENV['EMO_DIR'] || "default"+ GALLERY_CAT_ID = 1_234_567+ GALLERY_CAT_NAME = "galeria"+ EMO_DIR ||= ENV["EMO_DIR"] || "default"OLD_FORMAT = falseif OLD_FORMATMEMBERS_TABLE = "#{TABLE_PREFIX}core_members"- FORUMS_TABLE = "#{TABLE_PREFIX}forums_forums"+ FORUMS_TABLE = "#{TABLE_PREFIX}forums_forums"POSTS_TABLE = "#{TABLE_PREFIX}forums_posts"TOPICS_TABLE = "#{TABLE_PREFIX}forums_topics"else@@ -89,8 +88,8 @@ class ImportScripts::IpboardSQL < ImportScripts::Base# TODO figure this outputs "WARNING: permalink_normalizations not set!!!"sleep 1- #raw = "[ORIGINAL POST](#{URL}/topic/#{id}-#{slug})\n\n" + raw- #SiteSetting.permalink_normalizations='/topic/(.*t)\?.*/\1'+ #raw = "[ORIGINAL POST](#{URL}/topic/#{id}-#{slug})\n\n" + raw+ #SiteSetting.permalink_normalizations='/topic/(.*t)\?.*/\1'else# remove stuff after a "?" and work for urls that end in .htmlSiteSetting.permalink_normalizations = '/(.*t)[?.].*/\1'@@ -98,21 +97,15 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseenddef initialize- if IMPORT_AFTER > "1970-01-01"- print_warning("Importing data after #{IMPORT_AFTER}")- end+ print_warning("Importing data after #{IMPORT_AFTER}") if IMPORT_AFTER > "1970-01-01"super@htmlentities = HTMLEntities.newbegin- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- password: DB_PW,- database: DB_NAME- )+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, password: DB_PW, database: DB_NAME)rescue Exception => e- puts '=' * 50+ puts "=" * 50puts e.messageputs <<~TEXTCannot log in to database.@@ -151,18 +144,24 @@ class ImportScripts::IpboardSQL < ImportScripts::Base# NOT SUPPORTED import_gallery_topicsupdate_tl0create_permalinks-enddef import_users- puts '', "creating users"+ puts "", "creating users"- total_count = mysql_query("SELECT count(*) count FROM #{MEMBERS_TABLE}- WHERE last_activity > UNIX_TIMESTAMP(STR_TO_DATE('#{IMPORT_AFTER}', '%Y-%m-%d'));").first['count']+ total_count =+ mysql_query(+ "SELECT count(*) count FROM #{MEMBERS_TABLE}+ WHERE last_activity > UNIX_TIMESTAMP(STR_TO_DATE('#{IMPORT_AFTER}', '%Y-%m-%d'));",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|#notes: no location, url,- results = mysql_query("+ results =+ mysql_query(+ "SELECT member_id id,name username,member_group_id usergroup,@@ -184,58 +183,64 @@ class ImportScripts::IpboardSQL < ImportScripts::BaseAND member_group_id = g_idorder by member_id ASCLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1- next if all_records_exist? :users, results.map { |u| u['id'].to_i }+ next if all_records_exist? :users, results.map { |u| u["id"].to_i }create_users(results, total: total_count, offset: offset) do |user|- next if user['email'].blank?- next if user['username'].blank?- next if @lookup.user_id_from_imported_user_id(user['id'])-- birthday = Date.parse("#{user['bday_year']}-#{user['bday_month']}-#{user['bday_day']}") rescue nil+ next if user["email"].blank?+ next if user["username"].blank?+ next if @lookup.user_id_from_imported_user_id(user["id"])++ birthday =+ begin+ Date.parse("#{user["bday_year"]}-#{user["bday_month"]}-#{user["bday_day"]}")+ rescue StandardError+ nil+ end# TODO: what about timezones?- next if user['id'] == 0- { id: user['id'],- email: user['email'],- username: user['username'],- avatar_url: user['avatar_url'],- title: user['member_type'],- created_at: user['created_at'] == nil ? 0 : Time.zone.at(user['created_at']),+ next if user["id"] == 0+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ avatar_url: user["avatar_url"],+ title: user["member_type"],+ created_at: user["created_at"] == nil ? 0 : Time.zone.at(user["created_at"]),# bio_raw: user['bio_raw'],- registration_ip_address: user['registration_ip_address'],+ registration_ip_address: user["registration_ip_address"],# birthday: birthday,- last_seen_at: user['last_seen_at'] == nil ? 0 : Time.zone.at(user['last_seen_at']),- admin: /^Admin/.match(user['member_type']) ? true : false,- moderator: /^MOD/.match(user['member_type']) ? true : false,- post_create_action: proc do |newuser|- if user['avatar_url'] && user['avatar_url'].length > 0- photo_path = AVATARS_DIR + user['avatar_url']- if File.exist?(photo_path)- begin- upload = create_upload(newuser.id, photo_path, File.basename(photo_path))- if upload && upload.persisted?- newuser.import_mode = false- newuser.create_user_avatar- newuser.import_mode = true- newuser.user_avatar.update(custom_upload_id: upload.id)- newuser.update(uploaded_avatar_id: upload.id)- else- puts "Error: Upload did not persist for #{photo_path}!"+ last_seen_at: user["last_seen_at"] == nil ? 0 : Time.zone.at(user["last_seen_at"]),+ admin: /^Admin/.match(user["member_type"]) ? true : false,+ moderator: /^MOD/.match(user["member_type"]) ? true : false,+ post_create_action:+ proc do |newuser|+ if user["avatar_url"] && user["avatar_url"].length > 0+ photo_path = AVATARS_DIR + user["avatar_url"]+ if File.exist?(photo_path)+ begin+ upload = create_upload(newuser.id, photo_path, File.basename(photo_path))+ if upload && upload.persisted?+ newuser.import_mode = false+ newuser.create_user_avatar+ newuser.import_mode = true+ newuser.user_avatar.update(custom_upload_id: upload.id)+ newuser.update(uploaded_avatar_id: upload.id)+ else+ puts "Error: Upload did not persist for #{photo_path}!"+ end+ rescue SystemCallError => err+ puts "Could not import avatar #{photo_path}: #{err.message}"end- rescue SystemCallError => err- puts "Could not import avatar #{photo_path}: #{err.message}"+ else+ puts "avatar file not found at #{photo_path}"end- else- puts "avatar file not found at #{photo_path}"end- end- if user['banned'] != 0- suspend_user(newuser)- end- end+ suspend_user(newuser) if user["banned"] != 0+ end,}endend@@ -244,7 +249,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Basedef suspend_user(user)user.suspended_at = Time.nowuser.suspended_till = 200.years.from_now- ban_reason = 'Account deactivated by administrator'+ ban_reason = "Account deactivated by administrator"user_option = user.user_optionuser_option.email_digests = false@@ -266,45 +271,50 @@ class ImportScripts::IpboardSQL < ImportScripts::Basedef import_image_categoriesputs "", "importing image categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT category_id id,category_name_seo name,category_parent_id as parent_idFROM #{TABLE_PREFIX}gallery_categoriesORDER BY id ASC- ").to_a+ ",+ ).to_a- category_names = mysql_query("+ category_names =+ mysql_query(+ "SELECT DISTINCT word_key, word_default titleFROM #{TABLE_PREFIX}core_sys_lang_words where word_app='gallery'AND word_key REGEXP 'gallery_category_[0-9]+$'ORDER BY word_key ASC- ").to_a+ ",+ ).to_acat_map = {}puts "Creating gallery_cat_map"category_names.each do |name|- title = name['title']- word_key = name['word_key']+ title = name["title"]+ word_key = name["word_key"]puts "Processing #{word_key}: #{title}"- id = word_key.gsub('gallery_category_', '')+ id = word_key.gsub("gallery_category_", "")next if cat_map[id]cat_map[id] = cat_map.has_value?(title) ? title + " " + id : titleputs "#{id} => #{cat_map[id]}"end- params = { id: GALLERY_CAT_ID,- name: GALLERY_CAT_NAME }+ params = { id: GALLERY_CAT_ID, name: GALLERY_CAT_NAME }create_category(params, params[:id])create_categories(categories) do |category|- id = (category['id']).to_s+ id = (category["id"]).to_sname = CGI.unescapeHTML(cat_map[id]){- id: id + 'gal',+ id: id + "gal",name: name,parent_category_id: @lookup.category_id_from_imported_category_id(GALLERY_CAT_ID),- color: random_category_color+ color: random_category_color,}endend@@ -312,34 +322,34 @@ class ImportScripts::IpboardSQL < ImportScripts::Basedef import_categoriesputs "", "importing categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT id,name name,parent_id as parent_idFROM #{FORUMS_TABLE}ORDER BY parent_id ASC- ").to_a+ ",+ ).to_atop_level_categories = categories.select { |c| c["parent.id"] == -1 }create_categories(top_level_categories) do |category|- id = category['id'].to_s- name = category['name']- {- id: id,- name: name,- }+ id = category["id"].to_s+ name = category["name"]+ { id: id, name: name }endchildren_categories = categories.select { |c| c["parent.id"] != -1 }create_categories(children_categories) do |category|- id = category['id'].to_s- name = category['name']+ id = category["id"].to_s+ name = category["name"]{id: id,name: name,- parent_category_id: @lookup.category_id_from_imported_category_id(category['parent_id']),- color: random_category_color+ parent_category_id: @lookup.category_id_from_imported_category_id(category["parent_id"]),+ color: random_category_color,}endend@@ -347,13 +357,17 @@ class ImportScripts::IpboardSQL < ImportScripts::Basedef import_topicsputs "", "importing topics..."- total_count = mysql_query("SELECT count(*) count FROM #{POSTS_TABLE}+ total_count =+ mysql_query(+ "SELECT count(*) count FROM #{POSTS_TABLE}WHERE post_date > UNIX_TIMESTAMP(STR_TO_DATE('#{IMPORT_AFTER}', '%Y-%m-%d'))- AND new_topic=1;")- .first['count']+ AND new_topic=1;",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- discussions = mysql_query(<<-SQL+ discussions = mysql_query(<<-SQL)SELECT #{TOPICS_TABLE}.tid tid,#{TOPICS_TABLE}.forum_id category,#{POSTS_TABLE}.pid pid,@@ -371,29 +385,29 @@ class ImportScripts::IpboardSQL < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )break if discussions.size < 1- next if all_records_exist? :posts, discussions.map { |t| "discussion#" + t['tid'].to_s }+ next if all_records_exist? :posts, discussions.map { |t| "discussion#" + t["tid"].to_s }create_posts(discussions, total: total_count, offset: offset) do |discussion|- slug = discussion['slug']- id = discussion['tid']- raw = clean_up(discussion['raw'])+ slug = discussion["slug"]+ id = discussion["tid"]+ raw = clean_up(discussion["raw"]){- id: "discussion#" + discussion['tid'].to_s,- user_id: user_id_from_imported_user_id(discussion['user_id']) || Discourse::SYSTEM_USER_ID,- title: CGI.unescapeHTML(discussion['title']),- category: category_id_from_imported_category_id(discussion['category'].to_s),+ id: "discussion#" + discussion["tid"].to_s,+ user_id:+ user_id_from_imported_user_id(discussion["user_id"]) || Discourse::SYSTEM_USER_ID,+ title: CGI.unescapeHTML(discussion["title"]),+ category: category_id_from_imported_category_id(discussion["category"].to_s),raw: raw,- pinned_at: discussion['pinned'].to_i == 1 ? Time.zone.at(discussion['created_at']) : nil,- created_at: Time.zone.at(discussion['created_at']),+ pinned_at: discussion["pinned"].to_i == 1 ? Time.zone.at(discussion["created_at"]) : nil,+ created_at: Time.zone.at(discussion["created_at"]),}endendend- def array_from_members_string(invited_members = 'a:3:{i:0;i:22629;i:1;i:21837;i:2;i:22234;}')+ def array_from_members_string(invited_members = "a:3:{i:0;i:22629;i:1;i:21837;i:2;i:22234;}")out = []count_regex = /a:(\d)+:/count = count_regex.match(invited_members)[1]@@ -403,7 +417,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Basei = m[1]rest.sub!(i_regex, "")puts "i: #{i}, #{rest}"- out += [ i.to_i ]+ out += [i.to_i]endoutend@@ -411,12 +425,13 @@ class ImportScripts::IpboardSQL < ImportScripts::Basedef import_private_messagesputs "", "importing private messages..."- topic_count = mysql_query("SELECT COUNT(msg_id) count FROM #{TABLE_PREFIX}message_posts").first["count"]+ topic_count =+ mysql_query("SELECT COUNT(msg_id) count FROM #{TABLE_PREFIX}message_posts").first["count"]last_private_message_topic_id = -1batches(BATCH_SIZE) do |offset|- private_messages = mysql_query(<<-SQL+ private_messages = mysql_query(<<-SQL)SELECT msg_id pmtextid,msg_topic_id topic_id,msg_author_id fromuserid,@@ -433,12 +448,12 @@ class ImportScripts::IpboardSQL < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )puts "Processing #{private_messages.count} messages"break if private_messages.count < 1puts "Processing . . . "- private_messages = private_messages.reject { |pm| @lookup.post_already_imported?("pm-#{pm['pmtextid']}") }+ private_messages =+ private_messages.reject { |pm| @lookup.post_already_imported?("pm-#{pm["pmtextid"]}") }title_username_of_pm_first_post = {}@@ -446,11 +461,16 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseskip = falsemapped = {}- mapped[:id] = "pm-#{m['pmtextid']}"- mapped[:user_id] = user_id_from_imported_user_id(m['fromuserid']) || Discourse::SYSTEM_USER_ID- mapped[:raw] = clean_up(m['message']) rescue nil- mapped[:created_at] = Time.zone.at(m['dateline'])- title = @htmlentities.decode(m['title']).strip[0...255]+ mapped[:id] = "pm-#{m["pmtextid"]}"+ mapped[:user_id] = user_id_from_imported_user_id(m["fromuserid"]) ||+ Discourse::SYSTEM_USER_ID+ mapped[:raw] = begin+ clean_up(m["message"])+ rescue StandardError+ nil+ end+ mapped[:created_at] = Time.zone.at(m["dateline"])+ title = @htmlentities.decode(m["title"]).strip[0...255]topic_id = nilnext if mapped[:raw].blank?@@ -459,9 +479,9 @@ class ImportScripts::IpboardSQL < ImportScripts::Basetarget_usernames = []target_userids = []begin- to_user_array = [ m['to_user_id'] ] + array_from_members_string(m['touserarray'])- rescue- puts "#{m['pmtextid']} -- #{m['touserarray']}"+ to_user_array = [m["to_user_id"]] + array_from_members_string(m["touserarray"])+ rescue StandardError+ puts "#{m["pmtextid"]} -- #{m["touserarray"]}"skip = trueend@@ -477,8 +497,8 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseputs "Can't find user: #{to_user}"endend- rescue- puts "skipping pm-#{m['pmtextid']} `to_user_array` is broken -- #{to_user_array.inspect}"+ rescue StandardError+ puts "skipping pm-#{m["pmtextid"]} `to_user_array` is broken -- #{to_user_array.inspect}"skip = trueend@@ -486,30 +506,32 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseparticipants << mapped[:user_id]beginparticipants.sort!- rescue+ rescue StandardErrorputs "one of the participant's id is nil -- #{participants.inspect}"end- if last_private_message_topic_id != m['topic_id']- last_private_message_topic_id = m['topic_id']- puts "New message: #{m['topic_id']}: #{title} from #{m['fromuserid']} (#{mapped[:user_id]})" unless QUIET+ if last_private_message_topic_id != m["topic_id"]+ last_private_message_topic_id = m["topic_id"]+ unless QUIET+ puts "New message: #{m["topic_id"]}: #{title} from #{m["fromuserid"]} (#{mapped[:user_id]})"+ end# topic post message- topic_id = m['topic_id']+ topic_id = m["topic_id"]mapped[:title] = titlemapped[:archetype] = Archetype.private_message- mapped[:target_usernames] = target_usernames.join(',')+ mapped[:target_usernames] = target_usernames.join(",")if mapped[:target_usernames].size < 1 # pm with yourself?# skip = truemapped[:target_usernames] = "system"- puts "pm-#{m['pmtextid']} has no target (#{m['touserarray']})"+ puts "pm-#{m["pmtextid"]} has no target (#{m["touserarray"]})"endelse # replytopic_id = topic_lookup_from_imported_post_id("pm-#{topic_id}")- if !topic_id- skip = true- end+ skip = true if !topic_idmapped[:topic_id] = topic_id- puts "Reply message #{topic_id}: #{m['topic_id']}: from #{m['fromuserid']} (#{mapped[:user_id]})" unless QUIET+ unless QUIET+ puts "Reply message #{topic_id}: #{m["topic_id"]}: from #{m["fromuserid"]} (#{mapped[:user_id]})"+ endend# puts "#{target_usernames} -- #{mapped[:target_usernames]}"# puts "Adding #{mapped}"@@ -524,9 +546,13 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseputs "", "importing gallery albums..."gallery_count = 0- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}gallery_images- ;")- .first['count']+ total_count =+ mysql_query(+ "SELECT count(*) count FROM #{TABLE_PREFIX}gallery_images+ ;",+ ).first[+ "count"+ ]# NOTE: for imports with huge numbers of galleries, this needs to use limits@@ -546,7 +572,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Base# SQL# )- images = mysql_query(<<-SQL+ images = mysql_query(<<-SQL)SELECT #{TABLE_PREFIX}gallery_albums.album_id tid,#{TABLE_PREFIX}gallery_albums.album_category_id category,@@ -570,43 +596,46 @@ class ImportScripts::IpboardSQL < ImportScripts::BaseSQL- )-break if images.size < 1- next if all_records_exist? :posts, images.map { |t| "gallery#" + t['tid'].to_s + t['image_id'].to_s }+ if all_records_exist? :posts,+ images.map { |t| "gallery#" + t["tid"].to_s + t["image_id"].to_s }+ next+ end- last_id = images.first['tid']- raw = "Gallery ID: #{last_id}\n" + clean_up(images.first['raw'])- raw += "#{clean_up(images.first['description'])}\n"+ last_id = images.first["tid"]+ raw = "Gallery ID: #{last_id}\n" + clean_up(images.first["raw"])+ raw += "#{clean_up(images.first["description"])}\n"last_gallery = images.first.dupcreate_posts(images, total: total_count, offset: offset) do |gallery|- id = gallery['tid'].to_i+ id = gallery["tid"].to_i#puts "ID: #{id}, last_id: #{last_id}, image: #{gallery['image_id']}"if id == last_id- raw += "### #{gallery['caption']}\n"- raw += "#{UPLOADS}/#{gallery['orig']}\n"+ raw += "### #{gallery["caption"]}\n"+ raw += "#{UPLOADS}/#{gallery["orig"]}\n"last_gallery = gallery.dupnextelseinsert_raw = raw.dup- last_id = gallery['tid']+ last_id = gallery["tid"]if DEBUG- raw = "Gallery ID: #{last_id}\n" + clean_up(gallery['raw'])- raw += "Cat: #{last_gallery['category'].to_s} - #{category_id_from_imported_category_id(last_gallery['category'].to_s + 'gal')}"+ raw = "Gallery ID: #{last_id}\n" + clean_up(gallery["raw"])+ raw +=+ "Cat: #{last_gallery["category"].to_s} - #{category_id_from_imported_category_id(last_gallery["category"].to_s + "gal")}"end- raw += "#{clean_up(images.first['description'])}\n"- raw += "### #{gallery['caption']}\n"- if DEBUG- raw += "User #{gallery['user_id']}, image_id: #{gallery['image_id']}\n"- end- raw += "#{UPLOADS}/#{gallery['orig']}\n"+ raw += "#{clean_up(images.first["description"])}\n"+ raw += "### #{gallery["caption"]}\n"+ raw += "User #{gallery["user_id"]}, image_id: #{gallery["image_id"]}\n" if DEBUG+ raw += "#{UPLOADS}/#{gallery["orig"]}\n"gallery_count += 1- puts "#{gallery_count}--Cat: #{last_gallery['category'].to_s} ==> #{category_id_from_imported_category_id(last_gallery['category'].to_s + 'gal')}" unless QUIET+ unless QUIET+ puts "#{gallery_count}--Cat: #{last_gallery["category"].to_s} ==> #{category_id_from_imported_category_id(last_gallery["category"].to_s + "gal")}"+ end{- id: "gallery#" + last_gallery['tid'].to_s + last_gallery['image_id'].to_s,- user_id: user_id_from_imported_user_id(last_gallery['user_id']) || Discourse::SYSTEM_USER_ID,- title: CGI.unescapeHTML(last_gallery['title']),- category: category_id_from_imported_category_id(last_gallery['category'].to_s + 'gal'),+ id: "gallery#" + last_gallery["tid"].to_s + last_gallery["image_id"].to_s,+ user_id:+ user_id_from_imported_user_id(last_gallery["user_id"]) || Discourse::SYSTEM_USER_ID,+ title: CGI.unescapeHTML(last_gallery["title"]),+ category: category_id_from_imported_category_id(last_gallery["category"].to_s + "gal"),raw: insert_raw,}end@@ -630,11 +659,11 @@ class ImportScripts::IpboardSQL < ImportScripts::Basedef import_commentsputs "", "importing gallery comments..."- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}gallery_comments;")- .first['count']+ total_count =+ mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}gallery_comments;").first["count"]batches(BATCH_SIZE) do |offset|- comments = mysql_query(<<-SQL+ comments = mysql_query(<<-SQL)SELECT #{TABLE_PREFIX}gallery_comments.tid tid,#{TABLE_PREFIX}gallery_topics.forum_id category,@@ -652,20 +681,19 @@ class ImportScripts::IpboardSQL < ImportScripts::BaseOFFSET #{offset}SQL- )break if comments.size < 1- next if all_records_exist? :posts, comments.map { |comment| "comment#" + comment['pid'].to_s }+ next if all_records_exist? :posts, comments.map { |comment| "comment#" + comment["pid"].to_s }create_posts(comments, total: total_count, offset: offset) do |comment|- next unless t = topic_lookup_from_imported_post_id("discussion#" + comment['tid'].to_s)- next if comment['raw'].blank?+ next unless t = topic_lookup_from_imported_post_id("discussion#" + comment["tid"].to_s)+ next if comment["raw"].blank?{- id: "comment#" + comment['pid'].to_s,- user_id: user_id_from_imported_user_id(comment['user_id']) || Discourse::SYSTEM_USER_ID,+ id: "comment#" + comment["pid"].to_s,+ user_id: user_id_from_imported_user_id(comment["user_id"]) || Discourse::SYSTEM_USER_ID,topic_id: t[:topic_id],- raw: clean_up(comment['raw']),- created_at: Time.zone.at(comment['created_at'])+ raw: clean_up(comment["raw"]),+ created_at: Time.zone.at(comment["created_at"]),}endend@@ -674,13 +702,17 @@ class ImportScripts::IpboardSQL < ImportScripts::Basedef import_postsputs "", "importing posts..."- total_count = mysql_query("SELECT count(*) count FROM #{POSTS_TABLE}+ total_count =+ mysql_query(+ "SELECT count(*) count FROM #{POSTS_TABLE}WHERE post_date > UNIX_TIMESTAMP(STR_TO_DATE('#{IMPORT_AFTER}', '%Y-%m-%d'))- AND new_topic=0;")- .first['count']+ AND new_topic=0;",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- comments = mysql_query(<<-SQL+ comments = mysql_query(<<-SQL)SELECT #{TOPICS_TABLE}.tid tid,#{TOPICS_TABLE}.forum_id category,#{POSTS_TABLE}.pid pid,@@ -696,20 +728,19 @@ class ImportScripts::IpboardSQL < ImportScripts::BaseLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )break if comments.size < 1- next if all_records_exist? :posts, comments.map { |comment| "comment#" + comment['pid'].to_s }+ next if all_records_exist? :posts, comments.map { |comment| "comment#" + comment["pid"].to_s }create_posts(comments, total: total_count, offset: offset) do |comment|- next unless t = topic_lookup_from_imported_post_id("discussion#" + comment['tid'].to_s)- next if comment['raw'].blank?+ next unless t = topic_lookup_from_imported_post_id("discussion#" + comment["tid"].to_s)+ next if comment["raw"].blank?{- id: "comment#" + comment['pid'].to_s,- user_id: user_id_from_imported_user_id(comment['user_id']) || Discourse::SYSTEM_USER_ID,+ id: "comment#" + comment["pid"].to_s,+ user_id: user_id_from_imported_user_id(comment["user_id"]) || Discourse::SYSTEM_USER_ID,topic_id: t[:topic_id],- raw: clean_up(comment['raw']),- created_at: Time.zone.at(comment['created_at'])+ raw: clean_up(comment["raw"]),+ created_at: Time.zone.at(comment["created_at"]),}endend@@ -719,59 +750,61 @@ class ImportScripts::IpboardSQL < ImportScripts::Base# this makes proper quotes with user/topic/post references.# I'm not clear if it is for just some bizarre imported data, or it might ever be useful# It should be integrated into the Nokogiri section of clean_up, though.- @doc = Nokogiri::XML("<html>" + raw + "</html>")+ @doc = Nokogiri.XML("<html>" + raw + "</html>")# handle <blockquote>s with links to original post- @doc.css('blockquote[class=ipsQuote]').each do |b|- # puts "\n#{'#'*50}\n#{b}\n\nCONTENT: #{b['data-ipsquote-contentid']}"- # b.options = Nokogiri::XML::ParseOptions::STRICT- imported_post_id = b['data-ipsquote-contentcommentid'].to_s- content_type = b['data-ipsquote-contenttype'].to_s- content_class = b['data-ipsquote-contentclass'].to_s- content_id = b['data-ipsquote-contentid'].to_s || b['data-cid'].to_s- topic_lookup = topic_lookup_from_imported_post_id("comment#" + imported_post_id)- post_lookup = topic_lookup_from_imported_post_id("discussion#" + content_id)- post = topic_lookup ? topic_lookup[:post_number] : nil- topic = topic_lookup ? topic_lookup[:topic_id] : nil- post ||= post_lookup ? post_lookup[:post_number] : nil- topic ||= post_lookup ? post_lookup[:topic_id] : nil-- # TODO: consider: <blockquote class="ipsStyle_spoiler" data-ipsspoiler="">- # consider: <pre class="ipsCode prettyprint">- # TODO make sure it's the imported username- # TODO: do _s still get \-escaped?- ips_username = b['data-ipsquote-username'] || b['data-author']- username = ips_username- new_text = ""- if DEBUG- # new_text += "post: #{imported_post_id} --> #{post_lookup} --> |#{post}|<br>\n"- # new_text += "topic: #{content_id} --> #{topic_lookup} --> |#{topic}|<br>\n"- # new_text += "user: #{ips_username} --> |#{username}|<br>\n"- # new_text += "class: #{content_class}<br>\n"- # new_text += "type: #{content_type}<br>\n"- if content_class.length > 0 && content_class != "forums_Topic"- new_text += "UNEXPECTED CONTENT CLASS! #{content_class}<br>\n"- end- if content_type.length > 0 && content_type != "forums"- new_text += "UNEXPECTED CONTENT TYPE! #{content_type}<br>\n"+ @doc+ .css("blockquote[class=ipsQuote]")+ .each do |b|+ # puts "\n#{'#'*50}\n#{b}\n\nCONTENT: #{b['data-ipsquote-contentid']}"+ # b.options = Nokogiri::XML::ParseOptions::STRICT+ imported_post_id = b["data-ipsquote-contentcommentid"].to_s+ content_type = b["data-ipsquote-contenttype"].to_s+ content_class = b["data-ipsquote-contentclass"].to_s+ content_id = b["data-ipsquote-contentid"].to_s || b["data-cid"].to_s+ topic_lookup = topic_lookup_from_imported_post_id("comment#" + imported_post_id)+ post_lookup = topic_lookup_from_imported_post_id("discussion#" + content_id)+ post = topic_lookup ? topic_lookup[:post_number] : nil+ topic = topic_lookup ? topic_lookup[:topic_id] : nil+ post ||= post_lookup ? post_lookup[:post_number] : nil+ topic ||= post_lookup ? post_lookup[:topic_id] : nil++ # TODO: consider: <blockquote class="ipsStyle_spoiler" data-ipsspoiler="">+ # consider: <pre class="ipsCode prettyprint">+ # TODO make sure it's the imported username+ # TODO: do _s still get \-escaped?+ ips_username = b["data-ipsquote-username"] || b["data-author"]+ username = ips_username+ new_text = ""+ if DEBUG+ # new_text += "post: #{imported_post_id} --> #{post_lookup} --> |#{post}|<br>\n"+ # new_text += "topic: #{content_id} --> #{topic_lookup} --> |#{topic}|<br>\n"+ # new_text += "user: #{ips_username} --> |#{username}|<br>\n"+ # new_text += "class: #{content_class}<br>\n"+ # new_text += "type: #{content_type}<br>\n"+ if content_class.length > 0 && content_class != "forums_Topic"+ new_text += "UNEXPECTED CONTENT CLASS! #{content_class}<br>\n"+ end+ if content_type.length > 0 && content_type != "forums"+ new_text += "UNEXPECTED CONTENT TYPE! #{content_type}<br>\n"+ end+ # puts "#{'-'*20} and NOWWWWW!!!! \n #{new_text}"end- # puts "#{'-'*20} and NOWWWWW!!!! \n #{new_text}"- end- if post && topic && username- quote = "\n[quote=\"#{username}, post:#{post}, topic: #{topic}\"]\n\n"- else- if username && username.length > 1- quote = "\n[quote=\"#{username}\"]\n\n"+ if post && topic && username+ quote = "\n[quote=\"#{username}, post:#{post}, topic: #{topic}\"]\n\n"else- quote = "\n[quote]\n"+ if username && username.length > 1+ quote = "\n[quote=\"#{username}\"]\n\n"+ else+ quote = "\n[quote]\n"+ end+ # new_doc = Nokogiri::XML("<div>#{new_text}</div>")end- # new_doc = Nokogiri::XML("<div>#{new_text}</div>")+ puts "QUOTE: #{quote}"+ sleep 1+ b.content = quote + b.content + "\n[/quote]\n"+ b.name = "div"end- puts "QUOTE: #{quote}"- sleep 1- b.content = quote + b.content + "\n[/quote]\n"- b.name = 'div'- endraw = @doc.to_htmlend@@ -783,24 +816,30 @@ class ImportScripts::IpboardSQL < ImportScripts::Base# TODO what about uploads?# raw.gsub!(/<fileStore.core_Attachment>/,UPLOADS)raw.gsub!(/<br>/, "\n\n")- raw.gsub!(/<br \/>/, "\n\n")- raw.gsub!(/<p> <\/p>/, "\n\n")+ raw.gsub!(%r{<br />}, "\n\n")+ raw.gsub!(%r{<p> </p>}, "\n\n")raw.gsub!(/\[hr\]/, "\n***\n")raw.gsub!(/'/, "'")- raw.gsub!(/\[url="(.+?)"\]http.+?\[\/url\]/, "\\1\n")- raw.gsub!(/\[media\](.+?)\[\/media\]/, "\n\\1\n\n")- raw.gsub!(/\[php\](.+?)\[\/php\]/m) { |m| "\n\n```php\n\n" + @htmlentities.decode($1.gsub(/\n\n/, "\n")) + "\n\n```\n\n" }- raw.gsub!(/\[code\](.+?)\[\/code\]/m) { |m| "\n\n```\n\n" + @htmlentities.decode($1.gsub(/\n\n/, "\n")) + "\n\n```\n\n" }- raw.gsub!(/\[list\](.+?)\[\/list\]/m) { |m| "\n" + $1.gsub(/\[\*\]/, "\n- ") + "\n\n" }+ raw.gsub!(%r{\[url="(.+?)"\]http.+?\[/url\]}, "\\1\n")+ raw.gsub!(%r{\[media\](.+?)\[/media\]}, "\n\\1\n\n")+ raw.gsub!(%r{\[php\](.+?)\[/php\]}m) do |m|+ "\n\n```php\n\n" + @htmlentities.decode($1.gsub(/\n\n/, "\n")) + "\n\n```\n\n"+ end+ raw.gsub!(%r{\[code\](.+?)\[/code\]}m) do |m|+ "\n\n```\n\n" + @htmlentities.decode($1.gsub(/\n\n/, "\n")) + "\n\n```\n\n"+ end+ raw.gsub!(%r{\[list\](.+?)\[/list\]}m) { |m| "\n" + $1.gsub(/\[\*\]/, "\n- ") + "\n\n" }raw.gsub!(/\[quote\]/, "\n[quote]\n")- raw.gsub!(/\[\/quote\]/, "\n[/quote]\n")- raw.gsub!(/date=\'(.+?)\'/, '')- raw.gsub!(/timestamp=\'(.+?)\' /, '')+ raw.gsub!(%r{\[/quote\]}, "\n[/quote]\n")+ raw.gsub!(/date=\'(.+?)\'/, "")+ raw.gsub!(/timestamp=\'(.+?)\' /, "")quote_regex = /\[quote name=\'(.+?)\'\s+post=\'(\d+?)\'\s*\]/while quote = quote_regex.match(raw)# get IPB post number and find Discourse post and topic number- puts "----------------------------------------\nName: #{quote[1]}, post: #{quote[2]}" unless QUIET+ unless QUIET+ puts "----------------------------------------\nName: #{quote[1]}, post: #{quote[2]}"+ endimported_post_id = quote[2].to_stopic_lookup = topic_lookup_from_imported_post_id("comment#" + imported_post_id)post_lookup = topic_lookup_from_imported_post_id("discussion#" + imported_post_id)@@ -826,21 +865,24 @@ class ImportScripts::IpboardSQL < ImportScripts::Basewhile attach = attach_regex.match(raw)attach_id = attach[1]attachments =- mysql_query("SELECT attach_location as loc,+ mysql_query(+ "SELECT attach_location as loc,attach_file as filenameFROM #{ATTACHMENT_TABLE}- WHERE attach_id=#{attach_id}")+ WHERE attach_id=#{attach_id}",+ )if attachments.count < 1puts "Attachment #{attach_id} not found."attach_string = "Attachment #{attach_id} not found."else- attach_url = "#{UPLOADS}/#{attachments.first['loc'].gsub(' ', '%20')}"- if attachments.first['filename'].match(/(png|jpg|jpeg|gif)$/)+ attach_url = "#{UPLOADS}/#{attachments.first["loc"].gsub(" ", "%20")}"+ if attachments.first["filename"].match(/(png|jpg|jpeg|gif)$/)# images are rendered as a link that contains the image- attach_string = "#{attach_id}\n\n[![#{attachments.first['filename']}](#{attach_url})](#{attach_url})\n"+ attach_string =+ "#{attach_id}\n\n[![#{attachments.first["filename"]}](#{attach_url})](#{attach_url})\n"else# other attachments are simple download links- attach_string = "#{attach_id}\n\n[#{attachments.first['filename']}](#{attach_url})\n"+ attach_string = "#{attach_id}\n\n[#{attachments.first["filename"]}](#{attach_url})\n"endendraw.sub!(attach_regex, attach_string)@@ -850,7 +892,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseenddef random_category_color- colors = SiteSetting.category_colors.split('|')+ colors = SiteSetting.category_colors.split("|")colors[rand(colors.count)]end@@ -865,78 +907,78 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseraw.gsub!(/<fileStore.core_Attachment>/, UPLOADS)raw.gsub!(/<br>/, "\n")- @doc = Nokogiri::XML("<html>" + raw + "</html>")+ @doc = Nokogiri.XML("<html>" + raw + "</html>")# handle <blockquote>s with links to original post- @doc.css('blockquote[class=ipsQuote]').each do |b|- imported_post_id = b['data-ipsquote-contentcommentid'].to_s- content_type = b['data-ipsquote-contenttype'].to_s- content_class = b['data-ipsquote-contentclass'].to_s- content_id = b['data-ipsquote-contentid'].to_s || b['data-cid'].to_s- topic_lookup = topic_lookup_from_imported_post_id("comment#" + imported_post_id)- post_lookup = topic_lookup_from_imported_post_id("discussion#" + content_id)- post = topic_lookup ? topic_lookup[:post_number] : nil- topic = topic_lookup ? topic_lookup[:topic_id] : nil- post ||= post_lookup ? post_lookup[:post_number] : nil- topic ||= post_lookup ? post_lookup[:topic_id] : nil-- # TODO: consider: <blockquote class="ipsStyle_spoiler" data-ipsspoiler="">- # consider: <pre class="ipsCode prettyprint">- ips_username = b['data-ipsquote-username'] || b['data-author']- username = ips_username- new_text = ""- if DEBUG- if content_class.length > 0 && content_class != "forums_Topic"- new_text += "UNEXPECTED CONTENT CLASS! #{content_class}<br>\n"- end- if content_type.length > 0 && content_type != "forums"- new_text += "UNEXPECTED CONTENT TYPE! #{content_type}<br>\n"+ @doc+ .css("blockquote[class=ipsQuote]")+ .each do |b|+ imported_post_id = b["data-ipsquote-contentcommentid"].to_s+ content_type = b["data-ipsquote-contenttype"].to_s+ content_class = b["data-ipsquote-contentclass"].to_s+ content_id = b["data-ipsquote-contentid"].to_s || b["data-cid"].to_s+ topic_lookup = topic_lookup_from_imported_post_id("comment#" + imported_post_id)+ post_lookup = topic_lookup_from_imported_post_id("discussion#" + content_id)+ post = topic_lookup ? topic_lookup[:post_number] : nil+ topic = topic_lookup ? topic_lookup[:topic_id] : nil+ post ||= post_lookup ? post_lookup[:post_number] : nil+ topic ||= post_lookup ? post_lookup[:topic_id] : nil++ # TODO: consider: <blockquote class="ipsStyle_spoiler" data-ipsspoiler="">+ # consider: <pre class="ipsCode prettyprint">+ ips_username = b["data-ipsquote-username"] || b["data-author"]+ username = ips_username+ new_text = ""+ if DEBUG+ if content_class.length > 0 && content_class != "forums_Topic"+ new_text += "UNEXPECTED CONTENT CLASS! #{content_class}<br>\n"+ end+ if content_type.length > 0 && content_type != "forums"+ new_text += "UNEXPECTED CONTENT TYPE! #{content_type}<br>\n"+ endend- end- if post && topic && username- quote = "[quote=\"#{username}, post:#{post}, topic: #{topic}\"]\n\n"- else- if username && username.length > 1- quote = "[quote=\"#{username}\"]\n\n"+ if post && topic && username+ quote = "[quote=\"#{username}, post:#{post}, topic: #{topic}\"]\n\n"else- quote = "[quote]\n"+ if username && username.length > 1+ quote = "[quote=\"#{username}\"]\n\n"+ else+ quote = "[quote]\n"+ endend+ b.content = quote + b.content + "\n[/quote]\n"+ b.name = "div"end- b.content = quote + b.content + "\n[/quote]\n"- b.name = 'div'- end- @doc.css('object param embed').each do |embed|- embed.replace("\n#{embed['src']}\n")- end+ @doc.css("object param embed").each { |embed| embed.replace("\n#{embed["src"]}\n") }# handle <iframe data-embedcontent>s with links to original post# no examples in recent import- @doc.css('iframe[data-embedcontent]').each do |d|- d.to_s.match(/\-([0-9]+)t/)- imported_post_id = $1- if imported_post_id- puts "Searching for #{imported_post_id}" unless QUIET- topic_lookup = topic_lookup_from_imported_post_id("discussion#" + imported_post_id)- topic = topic_lookup ? topic_lookup[:topic_id] : nil- if topic- url = URL + "/t/#{topic}"- d.to_s.match(/comment=([0-9]+)&/)- content_id = $1 || "-1"- if content_id- post_lookup = topic_lookup_from_imported_post_id("comment#" + content_id)- post = topic_lookup ? topic_lookup[:post_number] : 1- url += "/#{post}"+ @doc+ .css("iframe[data-embedcontent]")+ .each do |d|+ d.to_s.match(/\-([0-9]+)t/)+ imported_post_id = $1+ if imported_post_id+ puts "Searching for #{imported_post_id}" unless QUIET+ topic_lookup = topic_lookup_from_imported_post_id("discussion#" + imported_post_id)+ topic = topic_lookup ? topic_lookup[:topic_id] : nil+ if topic+ url = URL + "/t/#{topic}"+ d.to_s.match(/comment=([0-9]+)&/)+ content_id = $1 || "-1"+ if content_id+ post_lookup = topic_lookup_from_imported_post_id("comment#" + content_id)+ post = topic_lookup ? topic_lookup[:post_number] : 1+ url += "/#{post}"+ end+ d.content = urlend- d.content = urlend+ d.name = "div"end- d.name = 'div'- end- @doc.css('div[class=ipsQuote_citation]').each do |d|- d.remove- end+ @doc.css("div[class=ipsQuote_citation]").each { |d| d.remove }raw = @doc.to_html@@ -948,7 +990,7 @@ class ImportScripts::IpboardSQL < ImportScripts::Base# un \-escape _s in usernames in [quote]sraw.gsub!(/^\[quote=.+?_.*$/) do |match|- match = match.gsub('\_', '_')+ match = match.gsub('\_', "_")matchendraw@@ -964,35 +1006,52 @@ class ImportScripts::IpboardSQL < ImportScripts::Baseenddef create_permalinks- puts '', 'Creating redirects...', ''+ puts "", "Creating redirects...", ""# TODO: permalink normalizations: /(.*t)\?.*/\1- puts '', 'Users...', ''+ puts "", "Users...", ""User.find_each do |u|ucf = u.custom_fieldsif ucf && ucf["import_id"] && ucf["import_username"]username = UrlHelper.encode_component(ucf["import_username"])- Permalink.create(url: "#{USERDIR}/#{ucf['import_id']}-#{username}", external_url: "/users/#{u.username}") rescue nil- print '.'+ begin+ Permalink.create(+ url: "#{USERDIR}/#{ucf["import_id"]}-#{username}",+ external_url: "/users/#{u.username}",+ )+ rescue StandardError+ nil+ end+ print "."endend- puts '', 'Posts...', ''+ puts "", "Posts...", ""Post.find_each do |post|pcf = post.custom_fieldsif pcf && pcf["import_id"]if post.post_number == 1topic = post.topic- id = pcf["import_id"].split('#').last+ id = pcf["import_id"].split("#").lastslug = topic.slugif ID_FIRST- Permalink.create(url: "topic/#{id}-#{slug}", topic_id: topic.id) rescue nil+ begin+ Permalink.create(url: "topic/#{id}-#{slug}", topic_id: topic.id)+ rescue StandardError+ nil+ endunless QUIET- print_warning("#{URL}topic/#{id}-#{slug} --> http://localhost:3000/topic/#{id}-#{slug}")+ print_warning(+ "#{URL}topic/#{id}-#{slug} --> http://localhost:3000/topic/#{id}-#{slug}",+ )endelse- Permalink.create(url: "#{slug}-#{id}t", topic_id: topic.id) rescue nil+ begin+ Permalink.create(url: "#{slug}-#{id}t", topic_id: topic.id)+ rescue StandardError+ nil+ endunless QUIETprint_warning("#{URL}/#{slug}-#{id}t --> http://localhost:3000/t/#{topic.id}")end@@ -1003,27 +1062,28 @@ class ImportScripts::IpboardSQL < ImportScripts::Base# print_warning("forum_entry-id-#{id}.html --> http://localhost:3000/t/#{topic.id}/#{post.id}")# endend- print '.'+ print "."endend- puts '', 'Categories...', ''+ puts "", "Categories...", ""Category.find_each do |cat|ccf = cat.custom_fieldsnext unless id = ccf["import_id"]- slug = cat['slug']- unless QUIET- print_warning("/forum/#{URL}-#{slug}-#{id} --> /c/#{slug}")+ slug = cat["slug"]+ print_warning("/forum/#{URL}-#{slug}-#{id} --> /c/#{slug}") unless QUIET+ begin+ Permalink.create(url: "/forum/#{id}-#{slug}", category_id: cat.id)+ rescue StandardError+ nilend- Permalink.create(url: "/forum/#{id}-#{slug}", category_id: cat.id) rescue nil- print '.'+ print "."endenddef print_warning(message)$stderr.puts "#{message}"end-endImportScripts::IpboardSQL.new.performdiff --git a/script/import_scripts/ipboard3.rb b/script/import_scripts/ipboard3.rbindex 2ea180c901b..482ac57d549 100644--- a/script/import_scripts/ipboard3.rb+++ b/script/import_scripts/ipboard3.rb@@ -5,19 +5,19 @@ require "reverse_markdown"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::IPBoard3 < ImportScripts::Base-- BATCH_SIZE ||= 5000+ BATCH_SIZE ||= 5000UPLOADS_DIR ||= "/path/to/uploads"def initializesuper- @client = Mysql2::Client.new(- host: ENV["DB_HOST"] || "localhost",- username: ENV["DB_USER"] || "root",- password: ENV["DB_PW"],- database: ENV["DB_NAME"],- )+ @client =+ Mysql2::Client.new(+ host: ENV["DB_HOST"] || "localhost",+ username: ENV["DB_USER"] || "root",+ password: ENV["DB_PW"],+ database: ENV["DB_NAME"],+ )@client.query("SET character_set_results = binary")end@@ -39,7 +39,7 @@ class ImportScripts::IPBoard3 < ImportScripts::Basetotal_users = mysql_query("SELECT COUNT(*) count FROM members").first["count"]batches(BATCH_SIZE) do |offset|- users = mysql_query(<<~SQL+ users = mysql_query(<<~SQL).to_aSELECT member_id id, name@@ -59,7 +59,6 @@ class ImportScripts::IPBoard3 < ImportScripts::BaseORDER BY member_idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?@@ -67,7 +66,9 @@ class ImportScripts::IPBoard3 < ImportScripts::Basecreate_users(users, total: total_users, offset: offset) do |u|next if user_id_from_imported_user_id(u["id"])- %W{name email title pp_about_me}.each { |k| u[k]&.encode!("utf-8", "utf-8", invalid: :replace, undef: :replace, replace: "") }+ %W[name email title pp_about_me].each do |k|+ u[k]&.encode!("utf-8", "utf-8", invalid: :replace, undef: :replace, replace: "")+ endnext if u["name"].blank? && !Email.is_valid?(u["email"]){@@ -77,30 +78,38 @@ class ImportScripts::IPBoard3 < ImportScripts::Basecreated_at: Time.zone.at(u["joined"]),registration_ip_address: u["ip_address"],title: CGI.unescapeHTML(u["title"].presence || ""),- date_of_birth: (Date.parse(u["date_of_birth"]) rescue nil),+ date_of_birth:+ (+ begin+ Date.parse(u["date_of_birth"])+ rescue StandardError+ nil+ end+ ),last_seen_at: Time.zone.at(u["last_activity"]),admin: !!(u["g_title"] =~ /admin/i),moderator: !!(u["g_title"] =~ /moderator/i),bio_raw: clean_up(u["pp_about_me"]),- post_create_action: proc do |new_user|- if u["member_banned"] == 1- new_user.update(suspended_at: DateTime.now, suspended_till: 100.years.from_now)- elsif u["pp_main_photo"].present?- path = File.join(UPLOADS_DIR, u["pp_main_photo"])- if File.exist?(path)- begin- upload = create_upload(new_user.id, path, File.basename(path))- if upload.persisted?- new_user.create_user_avatar- new_user.user_avatar.update(custom_upload_id: upload.id)- new_user.update(uploaded_avatar_id: upload.id)+ post_create_action:+ proc do |new_user|+ if u["member_banned"] == 1+ new_user.update(suspended_at: DateTime.now, suspended_till: 100.years.from_now)+ elsif u["pp_main_photo"].present?+ path = File.join(UPLOADS_DIR, u["pp_main_photo"])+ if File.exist?(path)+ begin+ upload = create_upload(new_user.id, path, File.basename(path))+ if upload.persisted?+ new_user.create_user_avatar+ new_user.user_avatar.update(custom_upload_id: upload.id)+ new_user.update(uploaded_avatar_id: upload.id)+ end+ rescue StandardError+ # don't careend- rescue- # don't careendend- end- end+ end,}endend@@ -109,10 +118,11 @@ class ImportScripts::IPBoard3 < ImportScripts::Basedef import_categoriesputs "", "importing categories..."- categories = mysql_query("SELECT id, parent_id, name, description, position FROM forums ORDER BY id").to_a+ categories =+ mysql_query("SELECT id, parent_id, name, description, position FROM forums ORDER BY id").to_aparent_categories = categories.select { |c| c["parent_id"] == -1 }- child_categories = categories.select { |c| c["parent_id"] != -1 }+ child_categories = categories.select { |c| c["parent_id"] != -1 }create_categories(parent_categories) do |c|next if category_id_from_imported_category_id(c["id"])@@ -142,7 +152,7 @@ class ImportScripts::IPBoard3 < ImportScripts::Base@closed_topic_ids = []last_topic_id = -1- total_topics = mysql_query(<<~SQL+ total_topics = mysql_query(<<~SQL).first["count"]SELECT COUNT(*) countFROM topicsJOIN posts ON tid = topic_id@@ -152,10 +162,9 @@ class ImportScripts::IPBoard3 < ImportScripts::BaseAND approved = 1AND queued = 0SQL- ).first["count"]batches(BATCH_SIZE) do |offset|- topics = mysql_query(<<~SQL+ topics = mysql_query(<<~SQL).to_aSELECT tid id, title, state@@ -176,7 +185,6 @@ class ImportScripts::IPBoard3 < ImportScripts::BaseORDER BY tidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if topics.empty?@@ -206,17 +214,16 @@ class ImportScripts::IPBoard3 < ImportScripts::Baseputs "", "importing posts..."last_post_id = -1- total_posts = mysql_query(<<~SQL+ total_posts = mysql_query(<<~SQL).first["count"]SELECT COUNT(*) countFROM postsWHERE new_topic = 0AND pdelete_time = 0AND queued = 0SQL- ).first["count"]batches(BATCH_SIZE) do |offset|- posts = mysql_query(<<~SQL+ posts = mysql_query(<<~SQL).to_aSELECT pid id, author_id, post_date@@ -230,7 +237,6 @@ class ImportScripts::IPBoard3 < ImportScripts::BaseORDER BY pidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if posts.empty?@@ -276,17 +282,16 @@ class ImportScripts::IPBoard3 < ImportScripts::Baseputs "", "import personal topics..."last_personal_topic_id = -1- total_personal_topics = mysql_query(<<~SQL+ total_personal_topics = mysql_query(<<~SQL).first["count"]SELECT COUNT(*) countFROM message_topicsJOIN message_posts ON msg_topic_id = mt_idWHERE mt_is_deleted = 0AND msg_is_first_post = 1SQL- ).first["count"]batches(BATCH_SIZE) do |offset|- personal_topics = mysql_query(<<~SQL+ personal_topics = mysql_query(<<~SQL).to_aSELECT mt_id id, mt_date, mt_title@@ -302,7 +307,6 @@ class ImportScripts::IPBoard3 < ImportScripts::BaseORDER BY mt_idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if personal_topics.empty?@@ -312,7 +316,8 @@ class ImportScripts::IPBoard3 < ImportScripts::Basenext if post_id_from_imported_post_id("pt-#{pt["id"]}")user_id = user_id_from_imported_user_id(pt["mt_starter_id"]) || -1- user_ids = [pt["mt_to_member_id"]] + pt["mt_invited_members"].scan(/i:(\d+);/).flatten.map(&:to_i)+ user_ids =+ [pt["mt_to_member_id"]] + pt["mt_invited_members"].scan(/i:(\d+);/).flatten.map(&:to_i)user_ids.map! { |id| user_id_from_imported_user_id(id) }user_ids.compact!user_ids.uniq!@@ -334,10 +339,13 @@ class ImportScripts::IPBoard3 < ImportScripts::Baseputs "", "importing personal posts..."last_personal_post_id = -1- total_personal_posts = mysql_query("SELECT COUNT(*) count FROM message_posts WHERE msg_is_first_post = 0").first["count"]+ total_personal_posts =+ mysql_query("SELECT COUNT(*) count FROM message_posts WHERE msg_is_first_post = 0").first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- personal_posts = mysql_query(<<~SQL+ personal_posts = mysql_query(<<~SQL).to_aSELECT msg_id id, msg_topic_id, msg_date@@ -349,7 +357,6 @@ class ImportScripts::IPBoard3 < ImportScripts::BaseORDER BY msg_idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if personal_posts.empty?@@ -374,27 +381,32 @@ class ImportScripts::IPBoard3 < ImportScripts::Basedef clean_up(raw, user_id = -1)raw.encode!("utf-8", "utf-8", invalid: :replace, undef: :replace, replace: "")- raw.gsub!(/<(.+)> <\/\1>/, "\n\n")+ raw.gsub!(%r{<(.+)> </\1>}, "\n\n")doc = Nokogiri::HTML5.fragment(raw)- doc.css("blockquote.ipsBlockquote").each do |bq|- post_id = post_id_from_imported_post_id(bq["data-cid"])- if post = Post.find_by(id: post_id)- bq.replace %{<br>[quote="#{post.user.username},post:#{post.post_number},topic:#{post.topic_id}"]\n#{bq.inner_html}\n[/quote]<br>}+ doc+ .css("blockquote.ipsBlockquote")+ .each do |bq|+ post_id = post_id_from_imported_post_id(bq["data-cid"])+ if post = Post.find_by(id: post_id)+ bq.replace %{<br>[quote="#{post.user.username},post:#{post.post_number},topic:#{post.topic_id}"]\n#{bq.inner_html}\n[/quote]<br>}+ endend- endmarkdown = ReverseMarkdown.convert(doc.to_html)markdown.gsub!(/\[attachment=(\d+):.+\]/) do- if a = mysql_query("SELECT attach_file, attach_location FROM attachments WHERE attach_id = #{$1}").first+ if a =+ mysql_query(+ "SELECT attach_file, attach_location FROM attachments WHERE attach_id = #{$1}",+ ).firstpath = File.join(UPLOADS_DIR, a["attach_location"])if File.exist?(path)beginupload = create_upload(user_id, path, a["attach_file"])return html_for_upload(upload, a["attach_file"]) if upload.persisted?- rescue+ rescue StandardErrorendendend@@ -406,7 +418,6 @@ class ImportScripts::IPBoard3 < ImportScripts::Basedef mysql_query(sql)@client.query(sql)end-endImportScripts::IPBoard3.new.performdiff --git a/script/import_scripts/jforum.rb b/script/import_scripts/jforum.rbindex 1c1136f2084..808b3e3e034 100644--- a/script/import_scripts/jforum.rb+++ b/script/import_scripts/jforum.rb@@ -1,25 +1,26 @@# frozen_string_literal: truerequire "mysql2"-require_relative 'base'+require_relative "base"class ImportScripts::JForum < ImportScripts::BaseBATCH_SIZE = 1000- REMOTE_AVATAR_REGEX ||= /\Ahttps?:\/\//i+ REMOTE_AVATAR_REGEX ||= %r{\Ahttps?://}idef initializesuper@settings = YAML.safe_load(File.read(ARGV.first), symbolize_names: true)- @database_client = Mysql2::Client.new(- host: @settings[:database][:host],- port: @settings[:database][:port],- username: @settings[:database][:username],- password: @settings[:database][:password],- database: @settings[:database][:schema],- reconnect: true- )+ @database_client =+ Mysql2::Client.new(+ host: @settings[:database][:host],+ port: @settings[:database][:port],+ username: @settings[:database][:username],+ password: @settings[:database][:password],+ database: @settings[:database][:schema],+ reconnect: true,+ )enddef execute@@ -39,7 +40,7 @@ class ImportScripts::JForum < ImportScripts::Baseenddef import_users- puts '', 'creating users'+ puts "", "creating users"total_count = count("SELECT COUNT(1) AS count FROM jforum_users")last_user_id = 0@@ -69,9 +70,7 @@ class ImportScripts::JForum < ImportScripts::Baseactive: row[:user_active] == 1,location: row[:user_from],custom_fields: user_custom_fields(row),- post_create_action: proc do |user|- import_avatar(user, row[:user_avatar])- end+ post_create_action: proc { |user| import_avatar(user, row[:user_avatar]) },}endend@@ -84,13 +83,14 @@ class ImportScripts::JForum < ImportScripts::Base@settings[:custom_fields].map do |field|columns << (field[:alias] ? "#{field[:column]} AS #{field[:alias]}" : field[:column])end- ", #{columns.join(', ')}"+ ", #{columns.join(", ")}"enddef user_fields- @user_fields ||= begin- Hash[UserField.all.map { |field| [field.name, field] }]- end+ @user_fields ||=+ begin+ Hash[UserField.all.map { |field| [field.name, field] }]+ endenddef user_custom_fields(row)@@ -124,7 +124,11 @@ class ImportScripts::JForum < ImportScripts::Baseif File.file?(path)@uploader.create_avatar(user, path)elsif avatar_source.match?(REMOTE_AVATAR_REGEX)- UserAvatar.import_url_for_user(avatar_source, user) rescue nil+ begin+ UserAvatar.import_url_for_user(avatar_source, user)+ rescue StandardError+ nil+ endendend@@ -218,10 +222,11 @@ class ImportScripts::JForum < ImportScripts::Baseid: "C#{row[:categories_id]}",name: row[:title],position: row[:display_order],- post_create_action: proc do |category|- url = File.join(@settings[:permalink_prefix], "forums/list/#{row[:categories_id]}.page")- Permalink.create(url: url, category_id: category.id) unless Permalink.find_by(url: url)- end+ post_create_action:+ proc do |category|+ url = File.join(@settings[:permalink_prefix], "forums/list/#{row[:categories_id]}.page")+ Permalink.create(url: url, category_id: category.id) unless Permalink.find_by(url: url)+ end,}end@@ -237,17 +242,19 @@ class ImportScripts::JForum < ImportScripts::Basename: row[:forum_name],description: row[:forum_desc],position: row[:forum_order],- parent_category_id: @lookup.category_id_from_imported_category_id("C#{row[:categories_id]}"),- post_create_action: proc do |category|- url = File.join(@settings[:permalink_prefix], "forums/show/#{row[:forum_id]}.page")- Permalink.create(url: url, category_id: category.id) unless Permalink.find_by(url: url)- end+ parent_category_id:+ @lookup.category_id_from_imported_category_id("C#{row[:categories_id]}"),+ post_create_action:+ proc do |category|+ url = File.join(@settings[:permalink_prefix], "forums/show/#{row[:forum_id]}.page")+ Permalink.create(url: url, category_id: category.id) unless Permalink.find_by(url: url)+ end,}endenddef import_posts- puts '', 'creating topics and posts'+ puts "", "creating topics and posts"total_count = count("SELECT COUNT(1) AS count FROM jforum_posts")last_post_id = 0@@ -286,7 +293,7 @@ class ImportScripts::JForum < ImportScripts::Baseuser_id: user_id,created_at: row[:post_time],raw: post_text,- import_topic_id: row[:topic_id]+ import_topic_id: row[:topic_id],}if row[:topic_acceptedanswer_post_id] == row[:post_id]@@ -312,7 +319,9 @@ class ImportScripts::JForum < ImportScripts::BaseTopicViewItem.add(post.topic_id, row[:poster_ip], post.user_id, post.created_at, true)end- mapped[:tags] = @tags_by_import_forum_id[row[:forum_id]] if @settings[:import_categories_as_tags]+ mapped[:tags] = @tags_by_import_forum_id[row[:forum_id]] if @settings[+ :import_categories_as_tags+ ]mapped[:category] = @lookup.category_id_from_imported_category_id(row[:forum_id])mapped@@ -470,7 +479,11 @@ class ImportScripts::JForum < ImportScripts::Basecategory_id = @lookup.category_id_from_imported_category_id(row[:forum_id])if user && category_id- CategoryUser.set_notification_level_for_category(user, NotificationLevels.all[:watching], category_id)+ CategoryUser.set_notification_level_for_category(+ user,+ NotificationLevels.all[:watching],+ category_id,+ )endend@@ -511,7 +524,11 @@ class ImportScripts::JForum < ImportScripts::Basetopic = @lookup.topic_lookup_from_imported_post_id(row[:topic_first_post_id])if user_id && topic- TopicUser.change(user_id, topic[:topic_id], notification_level: NotificationLevels.all[:watching])+ TopicUser.change(+ user_id,+ topic[:topic_id],+ notification_level: NotificationLevels.all[:watching],+ )endcurrent_index += 1@@ -545,17 +562,17 @@ class ImportScripts::JForum < ImportScripts::Baseenddef fix_bbcode_tag!(tag:, text:)- text.gsub!(/\s+(\[#{tag}\].*?\[\/#{tag}\])/im, '\1')+ text.gsub!(%r{\s+(\[#{tag}\].*?\[/#{tag}\])}im, '\1')text.gsub!(/(\[#{tag}.*?\])(?!$)/i) { "#{$1}\n" }text.gsub!(/((?<!^)\[#{tag}.*?\])/i) { "\n#{$1}" }- text.gsub!(/(\[\/#{tag}\])(?!$)/i) { "#{$1}\n" }- text.gsub!(/((?<!^)\[\/#{tag}\])/i) { "\n#{$1}" }+ text.gsub!(%r{(\[/#{tag}\])(?!$)}i) { "#{$1}\n" }+ text.gsub!(%r{((?<!^)\[/#{tag}\])}i) { "\n#{$1}" }enddef fix_inline_bbcode!(tag:, text:)- text.gsub!(/\[(#{tag}.*?)\](.*?)\[\/#{tag}\]/im) do+ text.gsub!(%r{\[(#{tag}.*?)\](.*?)\[/#{tag}\]}im) dobeginning_tag = $1content = $2.gsub(/(\n{2,})/) { "[/#{tag}]#{$1}[#{beginning_tag}]" }"[#{beginning_tag}]#{content}[/#{tag}]"diff --git a/script/import_scripts/jive.rb b/script/import_scripts/jive.rbindex f380b2bfee2..9361ba28e33 100644--- a/script/import_scripts/jive.rb+++ b/script/import_scripts/jive.rb@@ -1,12 +1,11 @@# frozen_string_literal: true# Jive importer-require 'nokogiri'-require 'csv'+require "nokogiri"+require "csv"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Jive < ImportScripts::Base-BATCH_SIZE = 1000CATEGORY_IDS = [2023, 2003, 2004, 2042, 2036, 2029] # categories that should be imported@@ -17,9 +16,9 @@ class ImportScripts::Jive < ImportScripts::Baseputs "loading post mappings..."@post_number_map = {}- Post.pluck(:id, :post_number).each do |post_id, post_number|- @post_number_map[post_id] = post_number- end+ Post+ .pluck(:id, :post_number)+ .each { |post_id, post_number| @post_number_map[post_id] = post_number }enddef created_post(post)@@ -47,19 +46,13 @@ class ImportScripts::Jive < ImportScripts::Baseenddef initialize(cols)- cols.each_with_index do |col, idx|- self.class.public_send(:define_method, col) do- @row[idx]- end- end+ cols.each_with_index { |col, idx| self.class.public_send(:define_method, col) { @row[idx] } }endenddef load_user_batch!(users, offset, total)if users.length > 0- create_users(users, offset: offset, total: total) do |user|- user- end+ create_users(users, offset: offset, total: total) { |user| user }users.clearendend@@ -72,53 +65,55 @@ class ImportScripts::Jive < ImportScripts::Basecurrent_row = +""double_quote_count = 0- File.open(filename).each_line do |line|-- line.gsub!(/\\(.{1})/) { |m| m[-1] == '"' ? '""' : m[-1] }- line.strip!-- current_row << "\n" unless current_row.empty?- current_row << line-- double_quote_count += line.scan('"').count+ File+ .open(filename)+ .each_line do |line|+ line.gsub!(/\\(.{1})/) { |m| m[-1] == '"' ? '""' : m[-1] }+ line.strip!++ current_row << "\n" unless current_row.empty?+ current_row << line++ double_quote_count += line.scan('"').count++ next if double_quote_count % 2 == 1++ raw =+ begin+ CSV.parse(current_row)+ rescue CSV::MalformedCSVError => e+ puts e.message+ puts "*" * 100+ puts "Bad row skipped, line is: #{line}"+ puts+ puts current_row+ puts+ puts "double quote count is : #{double_quote_count}"+ puts "*" * 100++ current_row = ""+ double_quote_count = 0+ next+ end[+ 0+ ]++ if first+ row = RowResolver.create(raw)++ current_row = ""+ double_quote_count = 0+ first = false+ next+ end- if double_quote_count % 2 == 1- next- end+ row.load(raw)- raw = begin- CSV.parse(current_row)- rescue CSV::MalformedCSVError => e- puts e.message- puts "*" * 100- puts "Bad row skipped, line is: #{line}"- puts- puts current_row- puts- puts "double quote count is : #{double_quote_count}"- puts "*" * 100-- current_row = ""- double_quote_count = 0- next- end[0]-- if first- row = RowResolver.create(raw)+ yield rowcurrent_row = ""double_quote_count = 0- first = false- nextend-- row.load(raw)-- yield row-- current_row = ""- double_quote_count = 0- endenddef total_rows(table)@@ -129,13 +124,9 @@ class ImportScripts::Jive < ImportScripts::Baseputs "", "importing groups..."rows = []- csv_parse("groups") do |row|- rows << { id: row.groupid, name: row.name }- end+ csv_parse("groups") { |row| rows << { id: row.groupid, name: row.name } }- create_groups(rows) do |row|- row- end+ create_groups(rows) { |row| row }enddef import_users@@ -147,15 +138,12 @@ class ImportScripts::Jive < ImportScripts::Basetotal = total_rows("users")csv_parse("users") do |row|-id = row.useridemail = "#{row.email}"# fake it- if row.email.blank? || row.email !~ /@/- email = fake_email- end+ email = fake_email if row.email.blank? || row.email !~ /@/name = "#{row.firstname} #{row.lastname}"username = row.username@@ -175,14 +163,11 @@ class ImportScripts::Jive < ImportScripts::Basecreated_at: created_at,last_seen_at: last_seen_at,active: is_activated.to_i == 1,- approved: true+ approved: true,}count += 1- if count % BATCH_SIZE == 0- load_user_batch! users, count - users.length, total- end-+ load_user_batch! users, count - users.length, total if count % BATCH_SIZE == 0endload_user_batch! users, count, total@@ -195,9 +180,7 @@ class ImportScripts::Jive < ImportScripts::Baseuser_id = user_id_from_imported_user_id(row.userid)group_id = group_id_from_imported_group_id(row.groupid)- if user_id && group_id- GroupUser.find_or_create_by(user_id: user_id, group_id: group_id)- end+ GroupUser.find_or_create_by(user_id: user_id, group_id: group_id) if user_id && group_idendend@@ -209,9 +192,7 @@ class ImportScripts::Jive < ImportScripts::Baserows << { id: row.communityid, name: "#{row.name} (#{row.communityid})" }end- create_categories(rows) do |row|- row- end+ create_categories(rows) { |row| row }enddef normalize_raw!(raw)@@ -219,9 +200,7 @@ class ImportScripts::Jive < ImportScripts::Baseraw = raw[5..-6]doc = Nokogiri::HTML5.fragment(raw)- doc.css('img').each do |img|- img.remove if img['class'] == "jive-image"- end+ doc.css("img").each { |img| img.remove if img["class"] == "jive-image" }raw = doc.to_htmlraw = raw[4..-1]@@ -231,7 +210,6 @@ class ImportScripts::Jive < ImportScripts::Basedef import_post_batch!(posts, topics, offset, total)create_posts(posts, total: total, offset: offset) do |post|-mapped = {}mapped[:id] = post[:id]@@ -271,7 +249,7 @@ class ImportScripts::Jive < ImportScripts::Basemappedend- posts.clear+ posts.clearenddef import_posts@@ -281,7 +259,6 @@ class ImportScripts::Jive < ImportScripts::Basethread_map = {}csv_parse("messages") do |thread|-next unless CATEGORY_IDS.include?(thread.containerid.to_i)if !thread.parentmessageid@@ -291,32 +268,38 @@ class ImportScripts::Jive < ImportScripts::Base#IMAGE UPLOADERif thread.imagecount- Dir.foreach("/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}") do |item|- next if item == ('.') || item == ('..') || item == ('.DS_Store')- photo_path = "/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}/#{item}"+ Dir.foreach(+ "/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}",+ ) do |item|+ next if item == (".") || item == ("..") || item == (".DS_Store")+ photo_path =+ "/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}/#{item}"upload = create_upload(thread.userid, photo_path, File.basename(photo_path))- if upload.persisted?- puts "Image upload is successful for #{photo_path}, new path is #{upload.url}!"- thread.body.gsub!(item, upload.url)- else- puts "Error: Image upload is not successful for #{photo_path}!"- end+ if upload.persisted?+ puts "Image upload is successful for #{photo_path}, new path is #{upload.url}!"+ thread.body.gsub!(item, upload.url)+ else+ puts "Error: Image upload is not successful for #{photo_path}!"+ endendend#ATTACHMENT UPLOADERif thread.attachmentcount- Dir.foreach("/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}") do |item|- next if item == ('.') || item == ('..') || item == ('.DS_Store')- attach_path = "/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}/#{item}"+ Dir.foreach(+ "/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}",+ ) do |item|+ next if item == (".") || item == ("..") || item == (".DS_Store")+ attach_path =+ "/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}/#{item}"upload = create_upload(thread.userid, attach_path, File.basename(attach_path))- if upload.persisted?- puts "Attachment upload is successful for #{attach_path}, new path is #{upload.url}!"- thread.body.gsub!(item, upload.url)- thread.body << "<br/><br/> #{attachment_html(upload, item)}"- else- puts "Error: Attachment upload is not successful for #{attach_path}!"- end+ if upload.persisted?+ puts "Attachment upload is successful for #{attach_path}, new path is #{upload.url}!"+ thread.body.gsub!(item, upload.url)+ thread.body << "<br/><br/> #{attachment_html(upload, item)}"+ else+ puts "Error: Attachment upload is not successful for #{attach_path}!"+ endendend@@ -329,7 +312,6 @@ class ImportScripts::Jive < ImportScripts::Basebody: normalize_raw!(thread.body || thread.subject || "<missing>"),created_at: DateTime.parse(thread.creationdate),}-endend@@ -348,35 +330,40 @@ class ImportScripts::Jive < ImportScripts::Basenext unless CATEGORY_IDS.include?(thread.containerid.to_i)if thread.parentmessageid-#IMAGE UPLOADERif thread.imagecount- Dir.foreach("/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}") do |item|- next if item == ('.') || item == ('..') || item == ('.DS_Store')- photo_path = "/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}/#{item}"+ Dir.foreach(+ "/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}",+ ) do |item|+ next if item == (".") || item == ("..") || item == (".DS_Store")+ photo_path =+ "/var/www/discourse/script/import_scripts/jive/img/#{thread.messageid}/#{item}"upload = create_upload(thread.userid, photo_path, File.basename(photo_path))- if upload.persisted?- puts "Image upload is successful for #{photo_path}, new path is #{upload.url}!"- thread.body.gsub!(item, upload.url)- else- puts "Error: Image upload is not successful for #{photo_path}!"- end+ if upload.persisted?+ puts "Image upload is successful for #{photo_path}, new path is #{upload.url}!"+ thread.body.gsub!(item, upload.url)+ else+ puts "Error: Image upload is not successful for #{photo_path}!"+ endendend#ATTACHMENT UPLOADERif thread.attachmentcount- Dir.foreach("/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}") do |item|- next if item == ('.') || item == ('..') || item == ('.DS_Store')- attach_path = "/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}/#{item}"+ Dir.foreach(+ "/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}",+ ) do |item|+ next if item == (".") || item == ("..") || item == (".DS_Store")+ attach_path =+ "/var/www/discourse/script/import_scripts/jive/attach/#{thread.messageid}/#{item}"upload = create_upload(thread.userid, attach_path, File.basename(attach_path))- if upload.persisted?- puts "Attachment upload is successful for #{attach_path}, new path is #{upload.url}!"- thread.body.gsub!(item, upload.url)- thread.body << "<br/><br/> #{attachment_html(upload, item)}"- else- puts "Error: Attachment upload is not successful for #{attach_path}!"- end+ if upload.persisted?+ puts "Attachment upload is successful for #{attach_path}, new path is #{upload.url}!"+ thread.body.gsub!(item, upload.url)+ thread.body << "<br/><br/> #{attachment_html(upload, item)}"+ else+ puts "Error: Attachment upload is not successful for #{attach_path}!"+ endendend@@ -386,7 +373,7 @@ class ImportScripts::Jive < ImportScripts::Baseuser_id: thread.userid,title: thread.subject,body: normalize_raw!(thread.body),- created_at: DateTime.parse(thread.creationdate)+ created_at: DateTime.parse(thread.creationdate),}posts << rowcount += 1@@ -399,7 +386,6 @@ class ImportScripts::Jive < ImportScripts::Baseimport_post_batch!(posts, topic_map, count - posts.length, total) if posts.length > 0end-endunless ARGV[0] && Dir.exist?(ARGV[0])diff --git a/script/import_scripts/jive_api.rb b/script/import_scripts/jive_api.rbindex 4c7cbfad190..7a84231b730 100644--- a/script/import_scripts/jive_api.rb+++ b/script/import_scripts/jive_api.rb@@ -7,7 +7,6 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# https://developers.jivesoftware.com/api/v3/cloud/rest/index.htmlclass ImportScripts::JiveApi < ImportScripts::Base-USER_COUNT ||= 1000POST_COUNT ||= 100STAFF_GUARDIAN ||= Guardian.new(Discourse.system_user)@@ -16,37 +15,141 @@ class ImportScripts::JiveApi < ImportScripts::Base############################## WHOLE CATEGORY OF CONTENT ##############################-# Announcement & News- { jive_object: { type: 37, id: 1004 }, filters: { created_after: 1.year.ago, type: "post" }, category_id: 7 },+ {+ jive_object: {+ type: 37,+ id: 1004,+ },+ filters: {+ created_after: 1.year.ago,+ type: "post",+ },+ category_id: 7,+ },# Questions & Answers / General Discussions- { jive_object: { type: 14, id: 2006 }, filters: { created_after: 6.months.ago, type: "discussion" }, category: Proc.new { |c| c["question"] ? 5 : 21 } },+ {+ jive_object: {+ type: 14,+ id: 2006,+ },+ filters: {+ created_after: 6.months.ago,+ type: "discussion",+ },+ category: Proc.new { |c| c["question"] ? 5 : 21 },+ },# Anywhere beta- { jive_object: { type: 14, id: 2052 }, filters: { created_after: 6.months.ago, type: "discussion" }, category_id: 22 },+ {+ jive_object: {+ type: 14,+ id: 2052,+ },+ filters: {+ created_after: 6.months.ago,+ type: "discussion",+ },+ category_id: 22,+ },# Tips & Tricks{ jive_object: { type: 37, id: 1284 }, filters: { type: "post" }, category_id: 6 },{ jive_object: { type: 37, id: 1319 }, filters: { type: "post" }, category_id: 6 },{ jive_object: { type: 37, id: 1177 }, filters: { type: "post" }, category_id: 6 },{ jive_object: { type: 37, id: 1165 }, filters: { type: "post" }, category_id: 6 },# Ambassadors- { jive_object: { type: 700, id: 1001 }, filters: { type: "discussion" }, authenticated: true, category_id: 8 },+ {+ jive_object: {+ type: 700,+ id: 1001,+ },+ filters: {+ type: "discussion",+ },+ authenticated: true,+ category_id: 8,+ },# Experts- { jive_object: { type: 700, id: 1034 }, filters: { type: "discussion" }, authenticated: true, category_id: 15 },+ {+ jive_object: {+ type: 700,+ id: 1034,+ },+ filters: {+ type: "discussion",+ },+ authenticated: true,+ category_id: 15,+ },# Feature Requests{ jive_object: { type: 14, id: 2015 }, filters: { type: "idea" }, category_id: 31 },-##################### SELECTED CONTENT #####################-# Announcement & News- { jive_object: { type: 37, id: 1004 }, filters: { entities: { 38 => [1345, 1381, 1845, 2046, 2060, 2061] } }, category_id: 7 },+ {+ jive_object: {+ type: 37,+ id: 1004,+ },+ filters: {+ entities: {+ 38 => [1345, 1381, 1845, 2046, 2060, 2061],+ },+ },+ category_id: 7,+ },# Problem Solving- { jive_object: { type: 14, id: 2006 }, filters: { entities: { 2 => [116685, 160745, 177010, 223482, 225036, 233228, 257882, 285103, 292297, 345243, 363250, 434546] } }, category_id: 10 },+ {+ jive_object: {+ type: 14,+ id: 2006,+ },+ filters: {+ entities: {+ 2 => [+ 116_685,+ 160_745,+ 177_010,+ 223_482,+ 225_036,+ 233_228,+ 257_882,+ 285_103,+ 292_297,+ 345_243,+ 363_250,+ 434_546,+ ],+ },+ },+ category_id: 10,+ },# General Discussions- { jive_object: { type: 14, id: 2006 }, filters: { entities: { 2 => [178203, 188350, 312734] } }, category_id: 21 },+ {+ jive_object: {+ type: 14,+ id: 2006,+ },+ filters: {+ entities: {+ 2 => [178_203, 188_350, 312_734],+ },+ },+ category_id: 21,+ },# Questions & Answers- { jive_object: { type: 14, id: 2006 }, filters: { entities: { 2 => [418811] } }, category_id: 5 },+ {+ jive_object: {+ type: 14,+ id: 2006,+ },+ filters: {+ entities: {+ 2 => [418_811],+ },+ },+ category_id: 5,+ },]def initialize@@ -75,9 +178,7 @@ class ImportScripts::JiveApi < ImportScripts::Basepeople = get("people/email/#{user.email}?fields=initialLogin,-resources", true)if people && people["initialLogin"].present?created_at = DateTime.parse(people["initialLogin"])- if user.created_at > created_at- user.update_columns(created_at: created_at)- end+ user.update_columns(created_at: created_at) if user.created_at > created_atendendend@@ -89,7 +190,11 @@ class ImportScripts::JiveApi < ImportScripts::Basestart_index = [0, UserCustomField.where(name: "import_id").count - USER_COUNT].maxloop do- users = get("people/@all?fields=initialLogin,emails,displayName,mentionName,thumbnailUrl,-resources&count=#{USER_COUNT}&startIndex=#{start_index}", true)+ users =+ get(+ "people/@all?fields=initialLogin,emails,displayName,mentionName,thumbnailUrl,-resources&count=#{USER_COUNT}&startIndex=#{start_index}",+ true,+ )create_users(users["list"], offset: imported_users) do |user|{id: user["id"],@@ -113,7 +218,11 @@ class ImportScripts::JiveApi < ImportScripts::BaseTO_IMPORT.each do |to_import|puts Time.nowentity = to_import[:jive_object]- places = get("places?fields=placeID,name,-resources&filter=entityDescriptor(#{entity[:type]},#{entity[:id]})", to_import[:authenticated])+ places =+ get(+ "places?fields=placeID,name,-resources&filter=entityDescriptor(#{entity[:type]},#{entity[:id]})",+ to_import[:authenticated],+ )import_place_contents(places["list"][0], to_import) if places && places["list"].present?endend@@ -125,19 +234,28 @@ class ImportScripts::JiveApi < ImportScripts::Baseif to_import.dig(:filters, :entities).present?path = "contents"- entities = to_import[:filters][:entities].flat_map { |type, ids| ids.map { |id| "#{type},#{id}" } }+ entities =+ to_import[:filters][:entities].flat_map { |type, ids| ids.map { |id| "#{type},#{id}" } }filters = "filter=entityDescriptor(#{entities.join(",")})"elsepath = "places/#{place["placeID"]}/contents"filters = +"filter=status(published)"if to_import[:filters]- filters << "&filter=type(#{to_import[:filters][:type]})" if to_import[:filters][:type].present?- filters << "&filter=creationDate(null,#{to_import[:filters][:created_after].strftime("%Y-%m-%dT%TZ")})" if to_import[:filters][:created_after].present?+ if to_import[:filters][:type].present?+ filters << "&filter=type(#{to_import[:filters][:type]})"+ end+ if to_import[:filters][:created_after].present?+ filters << "&filter=creationDate(null,#{to_import[:filters][:created_after].strftime("%Y-%m-%dT%TZ")})"+ endendendloop do- contents = get("#{path}?#{filters}&sort=dateCreatedAsc&count=#{POST_COUNT}&startIndex=#{start_index}", to_import[:authenticated])+ contents =+ get(+ "#{path}?#{filters}&sort=dateCreatedAsc&count=#{POST_COUNT}&startIndex=#{start_index}",+ to_import[:authenticated],+ )contents["list"].each do |content|content_id = content["contentID"].presence || "#{content["type"]}_#{content["id"]}"@@ -149,7 +267,8 @@ class ImportScripts::JiveApi < ImportScripts::Basecreated_at: content["published"],title: @htmlentities.decode(content["subject"]),raw: process_raw(content["content"]["text"]),- user_id: user_id_from_imported_user_id(content["author"]["id"]) || Discourse::SYSTEM_USER_ID,+ user_id:+ user_id_from_imported_user_id(content["author"]["id"]) || Discourse::SYSTEM_USER_ID,views: content["viewCount"],custom_fields: custom_fields,}@@ -165,10 +284,16 @@ class ImportScripts::JiveApi < ImportScripts::Baseif parent_post&.id && parent_post&.topic_idresources = content["resources"]- import_likes(resources["likes"]["ref"], parent_post.id) if content["likeCount"].to_i > 0 && resources.dig("likes", "ref").present?+ if content["likeCount"].to_i > 0 && resources.dig("likes", "ref").present?+ import_likes(resources["likes"]["ref"], parent_post.id)+ endif content["replyCount"].to_i > 0- import_comments(resources["comments"]["ref"], parent_post.topic_id, to_import) if resources.dig("comments", "ref").present?- import_messages(resources["messages"]["ref"], parent_post.topic_id, to_import) if resources.dig("messages", "ref").present?+ if resources.dig("comments", "ref").present?+ import_comments(resources["comments"]["ref"], parent_post.topic_id, to_import)+ end+ if resources.dig("messages", "ref").present?+ import_messages(resources["messages"]["ref"], parent_post.topic_id, to_import)+ endendendend@@ -198,7 +323,11 @@ class ImportScripts::JiveApi < ImportScripts::Basestart_index = 0loop do- comments = get("#{url}?hierarchical=false&count=#{POST_COUNT}&startIndex=#{start_index}", to_import[:authenticated])+ comments =+ get(+ "#{url}?hierarchical=false&count=#{POST_COUNT}&startIndex=#{start_index}",+ to_import[:authenticated],+ )break if comments["error"]comments["list"].each do |comment|next if post_id_from_imported_post_id(comment["id"])@@ -207,9 +336,12 @@ class ImportScripts::JiveApi < ImportScripts::Baseid: comment["id"],created_at: comment["published"],topic_id: topic_id,- user_id: user_id_from_imported_user_id(comment["author"]["id"]) || Discourse::SYSTEM_USER_ID,+ user_id:+ user_id_from_imported_user_id(comment["author"]["id"]) || Discourse::SYSTEM_USER_ID,raw: process_raw(comment["content"]["text"]),- custom_fields: { import_id: comment["id"] },+ custom_fields: {+ import_id: comment["id"],+ },}if (parent_post_id = comment["parentID"]).to_i > 0@@ -234,7 +366,11 @@ class ImportScripts::JiveApi < ImportScripts::Basestart_index = 0loop do- messages = get("#{url}?hierarchical=false&count=#{POST_COUNT}&startIndex=#{start_index}", to_import[:authenticated])+ messages =+ get(+ "#{url}?hierarchical=false&count=#{POST_COUNT}&startIndex=#{start_index}",+ to_import[:authenticated],+ )break if messages["error"]messages["list"].each do |message|next if post_id_from_imported_post_id(message["id"])@@ -243,9 +379,12 @@ class ImportScripts::JiveApi < ImportScripts::Baseid: message["id"],created_at: message["published"],topic_id: topic_id,- user_id: user_id_from_imported_user_id(message["author"]["id"]) || Discourse::SYSTEM_USER_ID,+ user_id:+ user_id_from_imported_user_id(message["author"]["id"]) || Discourse::SYSTEM_USER_ID,raw: process_raw(message["content"]["text"]),- custom_fields: { import_id: message["id"] },+ custom_fields: {+ import_id: message["id"],+ },}post[:custom_fields][:is_accepted_answer] = true if message["answer"]@@ -280,20 +419,25 @@ class ImportScripts::JiveApi < ImportScripts::Baseputs "", "importing bookmarks..."start_index = 0- fields = "fields=author.id,favoriteObject.id,-resources,-author.resources,-favoriteObject.resources"+ fields =+ "fields=author.id,favoriteObject.id,-resources,-author.resources,-favoriteObject.resources"filter = "&filter=creationDate(null,2016-01-01T00:00:00Z)"loop do- favorites = get("contents?#{fields}&filter=type(favorite)#{filter}&sort=dateCreatedAsc&count=#{POST_COUNT}&startIndex=#{start_index}")- bookmarks_to_create = favorites["list"].map do |favorite|- next unless user_id = user_id_from_imported_user_id(favorite["author"]["id"])- next unless post_id = post_id_from_imported_post_id(favorite["favoriteObject"]["id"])- { user_id: user_id, post_id: post_id }- end.flatten-- create_bookmarks(bookmarks_to_create) do |row|- row- end+ favorites =+ get(+ "contents?#{fields}&filter=type(favorite)#{filter}&sort=dateCreatedAsc&count=#{POST_COUNT}&startIndex=#{start_index}",+ )+ bookmarks_to_create =+ favorites["list"]+ .map do |favorite|+ next unless user_id = user_id_from_imported_user_id(favorite["author"]["id"])+ next unless post_id = post_id_from_imported_post_id(favorite["favoriteObject"]["id"])+ { user_id: user_id, post_id: post_id }+ end+ .flatten++ create_bookmarks(bookmarks_to_create) { |row| row }break if favorites["list"].size < POST_COUNT || favorites.dig("links", "next").blank?break unless start_index = favorites["links"]["next"][/startIndex=(\d+)/, 1]@@ -304,22 +448,26 @@ class ImportScripts::JiveApi < ImportScripts::Basedoc = Nokogiri::HTML5.fragment(raw)# convert emoticon- doc.css("span.emoticon-inline").each do |span|- name = span["class"][/emoticon_(\w+)/, 1]&.downcase- name && Emoji.exists?(name) ? span.replace(":#{name}:") : span.remove- end+ doc+ .css("span.emoticon-inline")+ .each do |span|+ name = span["class"][/emoticon_(\w+)/, 1]&.downcase+ name && Emoji.exists?(name) ? span.replace(":#{name}:") : span.remove+ end# convert mentionsdoc.css("a.jive-link-profile-small").each { |a| a.replace("@#{a.content}") }# fix links- doc.css("a[href]").each do |a|- if a["href"]["#{@base_uri}/docs/DOC-"]- a["href"] = a["href"][/#{Regexp.escape(@base_uri)}\/docs\/DOC-\d+/]- elsif a["href"][@base_uri]- a.replace(a.inner_html)+ doc+ .css("a[href]")+ .each do |a|+ if a["href"]["#{@base_uri}/docs/DOC-"]+ a["href"] = a["href"][%r{#{Regexp.escape(@base_uri)}/docs/DOC-\d+}]+ elsif a["href"][@base_uri]+ a.replace(a.inner_html)+ endend- endhtml = doc.at(".jive-rendered-content").to_html@@ -341,17 +489,22 @@ class ImportScripts::JiveApi < ImportScripts::Basedef get(url_or_path, authenticated = false)tries ||= 3- command = ["curl", "--silent"]+ command = %w[curl --silent]command << "--user \"#{@username}:#{@password}\"" if !!authenticated- command << (url_or_path.start_with?("http") ? "\"#{url_or_path}\"" : "\"#{@base_uri}/api/core/v3/#{url_or_path}\"")+ command << (+ if url_or_path.start_with?("http")+ "\"#{url_or_path}\""+ else+ "\"#{@base_uri}/api/core/v3/#{url_or_path}\""+ end+ )puts command.join(" ") if ENV["VERBOSE"] == "1"JSON.parse `#{command.join(" ")}`- rescue+ rescue StandardErrorretry if (tries -= 1) >= 0end-endImportScripts::JiveApi.new.performdiff --git a/script/import_scripts/json_generic.rb b/script/import_scripts/json_generic.rbindex 5d6efd4f975..433fe86db9e 100755--- a/script/import_scripts/json_generic.rb+++ b/script/import_scripts/json_generic.rb@@ -6,8 +6,7 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Edit the constants and initialize method for your import data.class ImportScripts::JsonGeneric < ImportScripts::Base-- JSON_FILE_PATH = ENV['JSON_FILE']+ JSON_FILE_PATH = ENV["JSON_FILE"]BATCH_SIZE ||= 1000def initialize@@ -30,24 +29,18 @@ class ImportScripts::JsonGeneric < ImportScripts::Baseenddef username_for(name)- result = name.downcase.gsub(/[^a-z0-9\-\_]/, '')+ result = name.downcase.gsub(/[^a-z0-9\-\_]/, "")- if result.blank?- result = Digest::SHA1.hexdigest(name)[0...10]- end+ result = Digest::SHA1.hexdigest(name)[0...10] if result.blank?resultenddef import_users- puts '', "Importing users"+ puts "", "Importing users"users = []- @imported_json['topics'].each do |t|- t['posts'].each do |p|- users << p['author'].scrub- end- end+ @imported_json["topics"].each { |t| t["posts"].each { |p| users << p["author"].scrub } }users.uniq!create_users(users) do |u|@@ -56,7 +49,7 @@ class ImportScripts::JsonGeneric < ImportScripts::Baseusername: username_for(u),name: u,email: "#{username_for(u)}@example.com",- created_at: Time.now+ created_at: Time.now,}endend@@ -67,8 +60,8 @@ class ImportScripts::JsonGeneric < ImportScripts::Basetopics = 0posts = 0- @imported_json['topics'].each do |t|- first_post = t['posts'][0]+ @imported_json["topics"].each do |t|+ first_post = t["posts"][0]next unless first_posttopic = {@@ -77,25 +70,32 @@ class ImportScripts::JsonGeneric < ImportScripts::Baseraw: first_post["body"],created_at: Time.zone.parse(first_post["date"]),cook_method: Post.cook_methods[:raw_html],- title: t['title'],- category: ENV['CATEGORY_ID'],- custom_fields: { import_id: "pid:#{first_post['id']}" }+ title: t["title"],+ category: ENV["CATEGORY_ID"],+ custom_fields: {+ import_id: "pid:#{first_post["id"]}",+ },}- topic[:pinned_at] = Time.zone.parse(first_post["date"]) if t['pinned']+ topic[:pinned_at] = Time.zone.parse(first_post["date"]) if t["pinned"]topics += 1parent_post = create_post(topic, topic[:id])- t['posts'][1..-1].each do |p|- create_post({- id: p["id"],- topic_id: parent_post.topic_id,- user_id: user_id_from_imported_user_id(username_for(p["author"])) || -1,- raw: p["body"],- created_at: Time.zone.parse(p["date"]),- cook_method: Post.cook_methods[:raw_html],- custom_fields: { import_id: "pid:#{p['id']}" }- }, p['id'])+ t["posts"][1..-1].each do |p|+ create_post(+ {+ id: p["id"],+ topic_id: parent_post.topic_id,+ user_id: user_id_from_imported_user_id(username_for(p["author"])) || -1,+ raw: p["body"],+ created_at: Time.zone.parse(p["date"]),+ cook_method: Post.cook_methods[:raw_html],+ custom_fields: {+ import_id: "pid:#{p["id"]}",+ },+ },+ p["id"],+ )posts += 1endend@@ -104,6 +104,4 @@ class ImportScripts::JsonGeneric < ImportScripts::Baseendend-if __FILE__ == $0- ImportScripts::JsonGeneric.new.perform-end+ImportScripts::JsonGeneric.new.perform if __FILE__ == $0diff --git a/script/import_scripts/kunena.rb b/script/import_scripts/kunena.rbindex d0c08320446..5f8ac7256f9 100644--- a/script/import_scripts/kunena.rb+++ b/script/import_scripts/kunena.rb@@ -4,7 +4,6 @@ require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Kunena < ImportScripts::Base-KUNENA_DB = "kunena"def initialize@@ -12,12 +11,13 @@ class ImportScripts::Kunena < ImportScripts::Base@users = {}- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- #password: "password",- database: KUNENA_DB- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ #password: "password",+ database: KUNENA_DB,+ )enddef execute@@ -26,7 +26,8 @@ class ImportScripts::Kunena < ImportScripts::Baseputs "creating users"create_users(@users) do |id, user|- { id: id,+ {+ id: id,email: user[:email],username: user[:username],created_at: user[:created_at],@@ -34,15 +35,25 @@ class ImportScripts::Kunena < ImportScripts::Basemoderator: user[:moderator] ? true : false,admin: user[:admin] ? true : false,suspended_at: user[:suspended] ? Time.zone.now : nil,- suspended_till: user[:suspended] ? 100.years.from_now : nil }+ suspended_till: user[:suspended] ? 100.years.from_now : nil,+ }end@users = nil- create_categories(@client.query("SELECT id, parent, name, description, ordering FROM jos_kunena_categories ORDER BY parent, id;")) do |c|- h = { id: c['id'], name: c['name'], description: c['description'], position: c['ordering'].to_i }- if c['parent'].to_i > 0- h[:parent_category_id] = category_id_from_imported_category_id(c['parent'])+ create_categories(+ @client.query(+ "SELECT id, parent, name, description, ordering FROM jos_kunena_categories ORDER BY parent, id;",+ ),+ ) do |c|+ h = {+ id: c["id"],+ name: c["name"],+ description: c["description"],+ position: c["ordering"].to_i,+ }+ if c["parent"].to_i > 0+ h[:parent_category_id] = category_id_from_imported_category_id(c["parent"])endhend@@ -50,9 +61,9 @@ class ImportScripts::Kunena < ImportScripts::Baseimport_postsbegin- create_admin(email: '[email protected]', username: UserNameSuggester.suggest('neil'))+ create_admin(email: "[email protected]", username: UserNameSuggester.suggest("neil"))rescue => e- puts '', "Failed to create admin user"+ puts "", "Failed to create admin user"puts e.messageendend@@ -61,38 +72,50 @@ class ImportScripts::Kunena < ImportScripts::Base# Need to merge data from joomla with kunenaputs "fetching Joomla users data from mysql"- results = @client.query("SELECT id, username, email, registerDate FROM jos_users;", cache_rows: false)+ results =+ @client.query("SELECT id, username, email, registerDate FROM jos_users;", cache_rows: false)results.each do |u|- next unless u['id'].to_i > (0) && u['username'].present? && u['email'].present?- username = u['username'].gsub(' ', '_').gsub(/[^A-Za-z0-9_]/, '')[0, User.username_length.end]+ next unless u["id"].to_i > (0) && u["username"].present? && u["email"].present?+ username = u["username"].gsub(" ", "_").gsub(/[^A-Za-z0-9_]/, "")[0, User.username_length.end]if username.length < User.username_length.firstusername = username * User.username_length.firstend- @users[u['id'].to_i] = { id: u['id'].to_i, username: username, email: u['email'], created_at: u['registerDate'] }+ @users[u["id"].to_i] = {+ id: u["id"].to_i,+ username: username,+ email: u["email"],+ created_at: u["registerDate"],+ }endputs "fetching Kunena user data from mysql"- results = @client.query("SELECT userid, signature, moderator, banned FROM jos_kunena_users;", cache_rows: false)+ results =+ @client.query(+ "SELECT userid, signature, moderator, banned FROM jos_kunena_users;",+ cache_rows: false,+ )results.each do |u|- next unless u['userid'].to_i > 0- user = @users[u['userid'].to_i]+ next unless u["userid"].to_i > 0+ user = @users[u["userid"].to_i]if user- user[:bio] = u['signature']- user[:moderator] = (u['moderator'].to_i == 1)- user[:suspended] = u['banned'].present?+ user[:bio] = u["signature"]+ user[:moderator] = (u["moderator"].to_i == 1)+ user[:suspended] = u["banned"].present?endendenddef import_posts- puts '', "creating topics and posts"+ puts "", "creating topics and posts"- total_count = @client.query("SELECT COUNT(*) count FROM jos_kunena_messages m;").first['count']+ total_count = @client.query("SELECT COUNT(*) count FROM jos_kunena_messages m;").first["count"]batch_size = 1000batches(batch_size) do |offset|- results = @client.query("+ results =+ @client.query(+ "SELECT m.id id,m.thread thread,m.parent parent,@@ -107,31 +130,33 @@ class ImportScripts::Kunena < ImportScripts::BaseORDER BY m.idLIMIT #{batch_size}OFFSET #{offset};- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| p['id'].to_i }+ next if all_records_exist? :posts, results.map { |p| p["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|skip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['userid']) || -1+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["userid"]) || -1mapped[:raw] = m["message"]- mapped[:created_at] = Time.zone.at(m['time'])+ mapped[:created_at] = Time.zone.at(m["time"])- if m['id'] == m['thread']- mapped[:category] = category_id_from_imported_category_id(m['catid'])- mapped[:title] = m['subject']+ if m["id"] == m["thread"]+ mapped[:category] = category_id_from_imported_category_id(m["catid"])+ mapped[:title] = m["subject"]else- parent = topic_lookup_from_imported_post_id(m['parent'])+ parent = topic_lookup_from_imported_post_id(m["parent"])if parentmapped[:topic_id] = parent[:topic_id]mapped[:reply_to_post_number] = parent[:post_number] if parent[:post_number] > 1else- puts "Parent post #{m['parent']} doesn't exist. Skipping #{m["id"]}: #{m["subject"][0..40]}"+ puts "Parent post #{m["parent"]} doesn't exist. Skipping #{m["id"]}: #{m["subject"][0..40]}"skip = trueendenddiff --git a/script/import_scripts/kunena3.rb b/script/import_scripts/kunena3.rbindex d7e98448f8e..3744eed575f 100644--- a/script/import_scripts/kunena3.rb+++ b/script/import_scripts/kunena3.rb@@ -19,27 +19,21 @@ export PARENT_FIELD="parent_id" # "parent" in some versions=endclass ImportScripts::Kunena < ImportScripts::Base-- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "kunena"- DB_USER ||= ENV['DB_USER'] || "kunena"- DB_PW ||= ENV['DB_PW'] || "kunena"- KUNENA_PREFIX ||= ENV['KUNENA_PREFIX'] || "jos_" # "iff_" sometimes- IMAGE_PREFIX ||= ENV['IMAGE_PREFIX'] || "http://EXAMPLE.com/media/kunena/attachments"- PARENT_FIELD ||= ENV['PARENT_FIELD'] || "parent_id" # "parent" in some versions+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "kunena"+ DB_USER ||= ENV["DB_USER"] || "kunena"+ DB_PW ||= ENV["DB_PW"] || "kunena"+ KUNENA_PREFIX ||= ENV["KUNENA_PREFIX"] || "jos_" # "iff_" sometimes+ IMAGE_PREFIX ||= ENV["IMAGE_PREFIX"] || "http://EXAMPLE.com/media/kunena/attachments"+ PARENT_FIELD ||= ENV["PARENT_FIELD"] || "parent_id" # "parent" in some versionsdef initialize-super@users = {}- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- password: DB_PW,- database: DB_NAME- )+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, password: DB_PW, database: DB_NAME)enddef execute@@ -48,7 +42,8 @@ class ImportScripts::Kunena < ImportScripts::Baseputs "creating users"create_users(@users) do |id, user|- { id: id,+ {+ id: id,email: user[:email],username: user[:username],created_at: user[:created_at],@@ -56,15 +51,25 @@ class ImportScripts::Kunena < ImportScripts::Basemoderator: user[:moderator] ? true : false,admin: user[:admin] ? true : false,suspended_at: user[:suspended] ? Time.zone.now : nil,- suspended_till: user[:suspended] ? 100.years.from_now : nil }+ suspended_till: user[:suspended] ? 100.years.from_now : nil,+ }end@users = nil- create_categories(@client.query("SELECT id, #{PARENT_FIELD} as parent_id, name, description, ordering FROM #{KUNENA_PREFIX}kunena_categories ORDER BY #{PARENT_FIELD}, id;")) do |c|- h = { id: c['id'], name: c['name'], description: c['description'], position: c['ordering'].to_i }- if c['parent_id'].to_i > 0- h[:parent_category_id] = category_id_from_imported_category_id(c['parent_id'])+ create_categories(+ @client.query(+ "SELECT id, #{PARENT_FIELD} as parent_id, name, description, ordering FROM #{KUNENA_PREFIX}kunena_categories ORDER BY #{PARENT_FIELD}, id;",+ ),+ ) do |c|+ h = {+ id: c["id"],+ name: c["name"],+ description: c["description"],+ position: c["ordering"].to_i,+ }+ if c["parent_id"].to_i > 0+ h[:parent_category_id] = category_id_from_imported_category_id(c["parent_id"])endhend@@ -72,9 +77,9 @@ class ImportScripts::Kunena < ImportScripts::Baseimport_postsbegin- create_admin(email: '[email protected]', username: UserNameSuggester.suggest('CHAMGEME'))+ create_admin(email: "[email protected]", username: UserNameSuggester.suggest("CHAMGEME"))rescue => e- puts '', "Failed to create admin user"+ puts "", "Failed to create admin user"puts e.messageendend@@ -83,38 +88,54 @@ class ImportScripts::Kunena < ImportScripts::Base# Need to merge data from joomla with kunenaputs "fetching Joomla users data from mysql"- results = @client.query("SELECT id, username, email, registerDate FROM #{KUNENA_PREFIX}users;", cache_rows: false)+ results =+ @client.query(+ "SELECT id, username, email, registerDate FROM #{KUNENA_PREFIX}users;",+ cache_rows: false,+ )results.each do |u|- next unless u['id'].to_i > (0) && u['username'].present? && u['email'].present?- username = u['username'].gsub(' ', '_').gsub(/[^A-Za-z0-9_]/, '')[0, User.username_length.end]+ next unless u["id"].to_i > (0) && u["username"].present? && u["email"].present?+ username = u["username"].gsub(" ", "_").gsub(/[^A-Za-z0-9_]/, "")[0, User.username_length.end]if username.length < User.username_length.firstusername = username * User.username_length.firstend- @users[u['id'].to_i] = { id: u['id'].to_i, username: username, email: u['email'], created_at: u['registerDate'] }+ @users[u["id"].to_i] = {+ id: u["id"].to_i,+ username: username,+ email: u["email"],+ created_at: u["registerDate"],+ }endputs "fetching Kunena user data from mysql"- results = @client.query("SELECT userid, signature, moderator, banned FROM #{KUNENA_PREFIX}kunena_users;", cache_rows: false)+ results =+ @client.query(+ "SELECT userid, signature, moderator, banned FROM #{KUNENA_PREFIX}kunena_users;",+ cache_rows: false,+ )results.each do |u|- next unless u['userid'].to_i > 0- user = @users[u['userid'].to_i]+ next unless u["userid"].to_i > 0+ user = @users[u["userid"].to_i]if user- user[:bio] = u['signature']- user[:moderator] = (u['moderator'].to_i == 1)- user[:suspended] = u['banned'].present?+ user[:bio] = u["signature"]+ user[:moderator] = (u["moderator"].to_i == 1)+ user[:suspended] = u["banned"].present?endendenddef import_posts- puts '', "creating topics and posts"+ puts "", "creating topics and posts"- total_count = @client.query("SELECT COUNT(*) count FROM #{KUNENA_PREFIX}kunena_messages m;").first['count']+ total_count =+ @client.query("SELECT COUNT(*) count FROM #{KUNENA_PREFIX}kunena_messages m;").first["count"]batch_size = 1000batches(batch_size) do |offset|- results = @client.query("+ results =+ @client.query(+ "SELECT m.id id,m.thread thread,m.parent parent,@@ -129,33 +150,38 @@ class ImportScripts::Kunena < ImportScripts::BaseORDER BY m.idLIMIT #{batch_size}OFFSET #{offset};- ", cache_rows: false)+ ",+ cache_rows: false,+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |p| p['id'].to_i }+ next if all_records_exist? :posts, results.map { |p| p["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|skip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['userid']) || -1+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["userid"]) || -1- id = m['userid']- mapped[:raw] = m["message"].gsub(/\[attachment=[0-9]+\](.+?)\[\/attachment\]/, "\n#{IMAGE_PREFIX}/#{id}/\\1")- mapped[:created_at] = Time.zone.at(m['time'])+ id = m["userid"]+ mapped[:raw] = m["message"].gsub(+ %r{\[attachment=[0-9]+\](.+?)\[/attachment\]},+ "\n#{IMAGE_PREFIX}/#{id}/\\1",+ )+ mapped[:created_at] = Time.zone.at(m["time"])- if m['parent'] == 0- mapped[:category] = category_id_from_imported_category_id(m['catid'])- mapped[:title] = m['subject']+ if m["parent"] == 0+ mapped[:category] = category_id_from_imported_category_id(m["catid"])+ mapped[:title] = m["subject"]else- parent = topic_lookup_from_imported_post_id(m['parent'])+ parent = topic_lookup_from_imported_post_id(m["parent"])if parentmapped[:topic_id] = parent[:topic_id]mapped[:reply_to_post_number] = parent[:post_number] if parent[:post_number] > 1else- puts "Parent post #{m['parent']} doesn't exist. Skipping #{m["id"]}: #{m["subject"][0..40]}"+ puts "Parent post #{m["parent"]} doesn't exist. Skipping #{m["id"]}: #{m["subject"][0..40]}"skip = trueendenddiff --git a/script/import_scripts/lithium.rb b/script/import_scripts/lithium.rbindex 1d258e7cac0..1e81e084806 100644--- a/script/import_scripts/lithium.rb+++ b/script/import_scripts/lithium.rb@@ -12,16 +12,14 @@# that was done using import_scripts/support/convert_mysql_xml_to_mysql.rb#-require 'mysql2'-require 'csv'-require 'reverse_markdown'+require "mysql2"+require "csv"+require "reverse_markdown"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'+require "htmlentities"# remove table conversion-[:table, :td, :tr, :th, :thead, :tbody].each do |tag|- ReverseMarkdown::Converters.unregister(tag)-end+%i[table td tr th thead tbody].each { |tag| ReverseMarkdown::Converters.unregister(tag) }class ImportScripts::Lithium < ImportScripts::BaseBATCH_SIZE = 1000@@ -29,11 +27,11 @@ class ImportScripts::Lithium < ImportScripts::Base# CHANGE THESE BEFORE RUNNING THE IMPORTERDATABASE = "wd"PASSWORD = "password"- AVATAR_DIR = '/tmp/avatars'- ATTACHMENT_DIR = '/tmp/attachments'- UPLOAD_DIR = '/tmp/uploads'+ AVATAR_DIR = "/tmp/avatars"+ ATTACHMENT_DIR = "/tmp/attachments"+ UPLOAD_DIR = "/tmp/uploads"- OLD_DOMAIN = 'community.wd.com'+ OLD_DOMAIN = "community.wd.com"TEMP = ""@@ -44,11 +42,10 @@ class ImportScripts::Lithium < ImportScripts::Base{ name: "user_field_3", profile: "industry" },]- LITHIUM_PROFILE_FIELDS = "'profile.jobtitle', 'profile.company', 'profile.industry', 'profile.location'"+ LITHIUM_PROFILE_FIELDS =+ "'profile.jobtitle', 'profile.company', 'profile.industry', 'profile.location'"- USERNAME_MAPPINGS = {- "admins": "admin_user"- }.with_indifferent_access+ USERNAME_MAPPINGS = { admins: "admin_user" }.with_indifferent_accessdef initializesuper@@ -57,16 +54,16 @@ class ImportScripts::Lithium < ImportScripts::Base@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- password: PASSWORD,- database: DATABASE- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ password: PASSWORD,+ database: DATABASE,+ )enddef execute-@max_start_id = Post.maximum(:id)import_groups@@ -94,10 +91,7 @@ class ImportScripts::Lithium < ImportScripts::BaseSQLcreate_groups(groups) do |group|- {- id: group["name"],- name: @htmlentities.decode(group["name"]).strip- }+ { id: group["name"], name: @htmlentities.decode(group["name"]).strip }endend@@ -106,7 +100,10 @@ class ImportScripts::Lithium < ImportScripts::Baseuser_count = mysql_query("SELECT COUNT(*) count FROM users").first["count"]avatar_files = Dir.entries(AVATAR_DIR)- duplicate_emails = mysql_query("SELECT email_lower FROM users GROUP BY email_lower HAVING COUNT(email_lower) > 1").map { |e| [e["email_lower"], 0] }.to_h+ duplicate_emails =+ mysql_query(+ "SELECT email_lower FROM users GROUP BY email_lower HAVING COUNT(email_lower) > 1",+ ).map { |e| [e["email_lower"], 0] }.to_hbatches(BATCH_SIZE) do |offset|users = mysql_query <<-SQL@@ -134,8 +131,8 @@ class ImportScripts::Lithium < ImportScripts::Basecreate_users(users, total: user_count, offset: offset) do |user|user_id = user["id"]- profile = profiles.select { |p| p["user_id"] == user_id }- result = profile.select { |p| p["param"] == "profile.location" }+ profile = profiles.select { |p| p["user_id"] == user_id }+ result = profile.select { |p| p["param"] == "profile.location" }location = result.count > 0 ? result.first["nvalue"] : nilusername = user["login_canon"]username = USERNAME_MAPPINGS[username] if USERNAME_MAPPINGS[username].present?@@ -158,31 +155,32 @@ class ImportScripts::Lithium < ImportScripts::Base# title: @htmlentities.decode(user["usertitle"]).strip,# primary_group_id: group_id_from_imported_group_id(user["usergroupid"]),created_at: unix_time(user["registration_time"]),- post_create_action: proc do |u|- @old_username_to_new_usernames[user["login_canon"]] = u.username-- # import user avatar- sso_id = u.custom_fields["sso_id"]- if sso_id.present?- prefix = "#{AVATAR_DIR}/#{sso_id}_"- file = get_file(prefix + "actual.jpeg")- file ||= get_file(prefix + "profile.jpeg")-- if file.present?- upload = UploadCreator.new(file, file.path, type: "avatar").create_for(u.id)- u.create_user_avatar unless u.user_avatar-- if !u.user_avatar.contains_upload?(upload.id)- u.user_avatar.update_columns(custom_upload_id: upload.id)-- if u.uploaded_avatar_id.nil? ||- !u.user_avatar.contains_upload?(u.uploaded_avatar_id)- u.update_columns(uploaded_avatar_id: upload.id)+ post_create_action:+ proc do |u|+ @old_username_to_new_usernames[user["login_canon"]] = u.username++ # import user avatar+ sso_id = u.custom_fields["sso_id"]+ if sso_id.present?+ prefix = "#{AVATAR_DIR}/#{sso_id}_"+ file = get_file(prefix + "actual.jpeg")+ file ||= get_file(prefix + "profile.jpeg")++ if file.present?+ upload = UploadCreator.new(file, file.path, type: "avatar").create_for(u.id)+ u.create_user_avatar unless u.user_avatar++ if !u.user_avatar.contains_upload?(upload.id)+ u.user_avatar.update_columns(custom_upload_id: upload.id)++ if u.uploaded_avatar_id.nil? ||+ !u.user_avatar.contains_upload?(u.uploaded_avatar_id)+ u.update_columns(uploaded_avatar_id: upload.id)+ endendendend- end- end+ end,}endend@@ -226,7 +224,7 @@ class ImportScripts::Lithium < ImportScripts::Baseif attr[:user].present?fields[name] = user[attr[:user]]elsif attr[:profile].present? && profile.count > 0- result = profile.select { |p| p["param"] == "profile.#{attr[:profile]}" }+ result = profile.select { |p| p["param"] == "profile.#{attr[:profile]}" }fields[name] = result.first["nvalue"] if result.count > 0endend@@ -268,8 +266,16 @@ class ImportScripts::Lithium < ImportScripts::Baseimported_user.user_avatar.update(custom_upload_id: upload.id)imported_user.update(uploaded_avatar_id: upload.id)ensure- file.close rescue nil- file.unlind rescue nil+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlind+ rescue StandardError+ nil+ endenddef import_profile_background(old_user, imported_user)@@ -295,8 +301,16 @@ class ImportScripts::Lithium < ImportScripts::Baseimported_user.user_profile.upload_profile_background(upload)ensure- file.close rescue nil- file.unlink rescue nil+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlink+ rescue StandardError+ nil+ endenddef import_categories@@ -310,14 +324,16 @@ class ImportScripts::Lithium < ImportScripts::BaseORDER BY n.type_id DESC, n.node_id ASCSQL- categories = categories.map { |c| (c["name"] = c["c_title"] || c["b_title"] || c["display_id"]) && c }+ categories =+ categories.map { |c| (c["name"] = c["c_title"] || c["b_title"] || c["display_id"]) && c }# To prevent duplicate category names- categories = categories.map do |category|- count = categories.to_a.count { |c| c["name"].present? && c["name"] == category["name"] }- category["name"] << " (#{category["node_id"]})" if count > 1- category- end+ categories =+ categories.map do |category|+ count = categories.to_a.count { |c| c["name"].present? && c["name"] == category["name"] }+ category["name"] << " (#{category["node_id"]})" if count > 1+ category+ endparent_categories = categories.select { |c| c["parent_node_id"] <= 2 }@@ -326,9 +342,7 @@ class ImportScripts::Lithium < ImportScripts::Baseid: category["node_id"],name: category["name"],position: category["position"],- post_create_action: lambda do |record|- after_category_create(record, category)- end+ post_create_action: lambda { |record| after_category_create(record, category) },}end@@ -342,9 +356,7 @@ class ImportScripts::Lithium < ImportScripts::Basename: category["name"],position: category["position"],parent_category_id: category_id_from_imported_category_id(category["parent_node_id"]),- post_create_action: lambda do |record|- after_category_create(record, category)- end+ post_create_action: lambda { |record| after_category_create(record, category) },}endend@@ -371,7 +383,6 @@ class ImportScripts::Lithium < ImportScripts::Baseendendend-enddef staff_guardian@@ -386,8 +397,12 @@ class ImportScripts::Lithium < ImportScripts::BaseSiteSetting.max_tags_per_topic = 10SiteSetting.max_tag_length = 100- topic_count = mysql_query("SELECT COUNT(*) count FROM message2 where id = root_id").first["count"]- topic_tags = mysql_query("SELECT e.target_id, GROUP_CONCAT(l.tag_text SEPARATOR ',') tags FROM tag_events_label_message e LEFT JOIN tags_label l ON e.tag_id = l.tag_id GROUP BY e.target_id")+ topic_count =+ mysql_query("SELECT COUNT(*) count FROM message2 where id = root_id").first["count"]+ topic_tags =+ mysql_query(+ "SELECT e.target_id, GROUP_CONCAT(l.tag_text SEPARATOR ',') tags FROM tag_events_label_message e LEFT JOIN tags_label l ON e.tag_id = l.tag_id GROUP BY e.target_id",+ )batches(BATCH_SIZE) do |offset|topics = mysql_query <<-SQL@@ -405,7 +420,6 @@ class ImportScripts::Lithium < ImportScripts::Basenext if all_records_exist? :posts, topics.map { |topic| "#{topic["node_id"]} #{topic["id"]}" }create_posts(topics, total: topic_count, offset: offset) do |topic|-category_id = category_id_from_imported_category_id(topic["node_id"])deleted_at = topic["deleted"] == 1 ? topic["row_version"] : nilraw = topic["body"]@@ -420,24 +434,31 @@ class ImportScripts::Lithium < ImportScripts::Basecreated_at: unix_time(topic["post_date"]),deleted_at: deleted_at,views: topic["views"],- custom_fields: { import_unique_id: topic["unique_id"] },+ custom_fields: {+ import_unique_id: topic["unique_id"],+ },import_mode: true,- post_create_action: proc do |post|- result = topic_tags.select { |t| t["target_id"] == topic["unique_id"] }- if result.count > 0- tag_names = result.first["tags"].split(",")- DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)- end- end+ post_create_action:+ proc do |post|+ result = topic_tags.select { |t| t["target_id"] == topic["unique_id"] }+ if result.count > 0+ tag_names = result.first["tags"].split(",")+ DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)+ end+ end,}elsemessage = "Unknown"message = "Category '#{category_id}' not exist" if category_id.blank?message = "Topic 'body' is empty" if raw.blank?- PluginStoreRow.find_or_create_by(plugin_name: "topic_import_log", key: topic["unique_id"].to_s, value: message, type_name: 'String')+ PluginStoreRow.find_or_create_by(+ plugin_name: "topic_import_log",+ key: topic["unique_id"].to_s,+ value: message,+ type_name: "String",+ )nilend-endend@@ -446,9 +467,13 @@ class ImportScripts::Lithium < ImportScripts::Baseenddef import_posts-- post_count = mysql_query("SELECT COUNT(*) count FROM message2- WHERE id <> root_id").first["count"]+ post_count =+ mysql_query(+ "SELECT COUNT(*) count FROM message2+ WHERE id <> root_id",+ ).first[+ "count"+ ]puts "", "importing posts... (#{post_count})"@@ -465,11 +490,18 @@ class ImportScripts::Lithium < ImportScripts::Basebreak if posts.size < 1- next if all_records_exist? :posts, posts.map { |post| "#{post["node_id"]} #{post["root_id"]} #{post["id"]}" }+ if all_records_exist? :posts,+ posts.map { |post|+ "#{post["node_id"]} #{post["root_id"]} #{post["id"]}"+ }+ next+ endcreate_posts(posts, total: post_count, offset: offset) do |post|raw = post["raw"]- next unless topic = topic_lookup_from_imported_post_id("#{post["node_id"]} #{post["root_id"]}")+ unless topic = topic_lookup_from_imported_post_id("#{post["node_id"]} #{post["root_id"]}")+ next+ enddeleted_at = topic["deleted"] == 1 ? topic["row_version"] : nilraw = post["body"]@@ -482,17 +514,27 @@ class ImportScripts::Lithium < ImportScripts::Baseraw: raw,created_at: unix_time(post["post_date"]),deleted_at: deleted_at,- custom_fields: { import_unique_id: post["unique_id"] },- import_mode: true+ custom_fields: {+ import_unique_id: post["unique_id"],+ },+ import_mode: true,}- if parent = topic_lookup_from_imported_post_id("#{post["node_id"]} #{post["root_id"]} #{post["parent_id"]}")+ if parent =+ topic_lookup_from_imported_post_id(+ "#{post["node_id"]} #{post["root_id"]} #{post["parent_id"]}",+ )new_post[:reply_to_post_number] = parent[:post_number]endnew_postelse- PluginStoreRow.find_or_create_by(plugin_name: "post_import_log", key: post["unique_id"].to_s, value: "Post 'body' is empty", type_name: 'String')+ PluginStoreRow.find_or_create_by(+ plugin_name: "post_import_log",+ key: post["unique_id"].to_s,+ value: "Post 'body' is empty",+ type_name: "String",+ )nilendend@@ -521,37 +563,40 @@ class ImportScripts::Lithium < ImportScripts::Base"catwink" => "wink","catfrustrated" => "grumpycat","catembarrassed" => "kissing_cat",- "catlol" => "joy_cat"+ "catlol" => "joy_cat",}def import_likesputs "\nimporting likes..."- sql = "select source_id user_id, target_id post_id, row_version created_at from tag_events_score_message"+ sql =+ "select source_id user_id, target_id post_id, row_version created_at from tag_events_score_message"results = mysql_query(sql)puts "loading unique id map"existing_map = {}- PostCustomField.where(name: 'import_unique_id').pluck(:post_id, :value).each do |post_id, import_id|- existing_map[import_id] = post_id- end+ PostCustomField+ .where(name: "import_unique_id")+ .pluck(:post_id, :value)+ .each { |post_id, import_id| existing_map[import_id] = post_id }puts "loading data into temp table"- DB.exec("create temp table like_data(user_id int, post_id int, created_at timestamp without time zone)")+ DB.exec(+ "create temp table like_data(user_id int, post_id int, created_at timestamp without time zone)",+ )PostAction.transaction doresults.each do |result|-result["user_id"] = user_id_from_imported_user_id(result["user_id"].to_s)result["post_id"] = existing_map[result["post_id"].to_s]next unless result["user_id"] && result["post_id"]- DB.exec("INSERT INTO like_data VALUES (:user_id,:post_id,:created_at)",+ DB.exec(+ "INSERT INTO like_data VALUES (:user_id,:post_id,:created_at)",user_id: result["user_id"],post_id: result["post_id"],- created_at: result["created_at"]+ created_at: result["created_at"],)-endend@@ -616,31 +661,28 @@ class ImportScripts::Lithium < ImportScripts::Baseenddef import_accepted_answers-puts "\nimporting accepted answers..."- sql = "select unique_id post_id from message2 where (attributes & 0x4000 ) != 0 and deleted = 0;"+ sql =+ "select unique_id post_id from message2 where (attributes & 0x4000 ) != 0 and deleted = 0;"results = mysql_query(sql)puts "loading unique id map"existing_map = {}- PostCustomField.where(name: 'import_unique_id').pluck(:post_id, :value).each do |post_id, import_id|- existing_map[import_id] = post_id- end+ PostCustomField+ .where(name: "import_unique_id")+ .pluck(:post_id, :value)+ .each { |post_id, import_id| existing_map[import_id] = post_id }puts "loading data into temp table"DB.exec("create temp table accepted_data(post_id int primary key)")PostAction.transaction doresults.each do |result|-result["post_id"] = existing_map[result["post_id"].to_s]next unless result["post_id"]- DB.exec("INSERT INTO accepted_data VALUES (:post_id)",- post_id: result["post_id"]- )-+ DB.exec("INSERT INTO accepted_data VALUES (:post_id)", post_id: result["post_id"])endend@@ -679,7 +721,6 @@ class ImportScripts::Lithium < ImportScripts::Baseenddef import_pms-puts "", "importing pms..."puts "determining participation records"@@ -702,24 +743,20 @@ class ImportScripts::Lithium < ImportScripts::Basenote_to_subject = {}subject_to_first_note = {}- mysql_query("SELECT note_id, subject, sender_user_id FROM tblia_notes_content order by note_id").each do |row|+ mysql_query(+ "SELECT note_id, subject, sender_user_id FROM tblia_notes_content order by note_id",+ ).each do |row|user_id = user_id_from_imported_user_id(row["sender_user_id"])- ary = (users[row["note_id"]] ||= Set.new)- if user_id- ary << user_id- end- note_to_subject[row["note_id"]] = row["subject"]+ ary = (users[row["note_id"]] ||= Set.new)+ ary << user_id if user_id+ note_to_subject[row["note_id"]] = row["subject"]- if row["subject"] !~ /^Re: /- subject_to_first_note[[row["subject"], ary]] ||= row["note_id"]- end+ subject_to_first_note[[row["subject"], ary]] ||= row["note_id"] if row["subject"] !~ /^Re: /endputs "Loading user_id to username map"user_map = {}- User.pluck(:id, :username).each do |id, username|- user_map[id] = username- end+ User.pluck(:id, :username).each { |id, username| user_map[id] = username }topic_count = mysql_query("SELECT COUNT(*) count FROM tblia_notes_content").first["count"]@@ -737,8 +774,8 @@ class ImportScripts::Lithium < ImportScripts::Basenext if all_records_exist? :posts, topics.map { |topic| "pm_#{topic["note_id"]}" }create_posts(topics, total: topic_count, offset: offset) do |topic|-- user_id = user_id_from_imported_user_id(topic["sender_user_id"]) || Discourse::SYSTEM_USER_ID+ user_id =+ user_id_from_imported_user_id(topic["sender_user_id"]) || Discourse::SYSTEM_USER_IDparticipants = users[topic["note_id"]]usernames = (participants - [user_id]).map { |id| user_map[id] }@@ -763,48 +800,54 @@ class ImportScripts::Lithium < ImportScripts::Baseuser_id: user_id,raw: raw,created_at: unix_time(topic["sent_time"]),- import_mode: true+ import_mode: true,}unless topic_idmsg[:title] = @htmlentities.decode(topic["subject"]).strip[0...255]msg[:archetype] = Archetype.private_message- msg[:target_usernames] = usernames.join(',')+ msg[:target_usernames] = usernames.join(",")elsemsg[:topic_id] = topic_idendmsgelse- PluginStoreRow.find_or_create_by(plugin_name: "pm_import_log", key: topic["note_id"].to_s, value: "PM 'body' is empty", type_name: 'String')+ PluginStoreRow.find_or_create_by(+ plugin_name: "pm_import_log",+ key: topic["note_id"].to_s,+ value: "PM 'body' is empty",+ type_name: "String",+ )nilendendend-enddef close_topics-puts "\nclosing closed topics..."- sql = "select unique_id post_id from message2 where root_id = id AND (attributes & 0x0002 ) != 0;"+ sql =+ "select unique_id post_id from message2 where root_id = id AND (attributes & 0x0002 ) != 0;"results = mysql_query(sql)# loading post mapexisting_map = {}- PostCustomField.where(name: 'import_unique_id').pluck(:post_id, :value).each do |post_id, import_id|- existing_map[import_id.to_i] = post_id.to_i- end-- results.map { |r| r["post_id"] }.each_slice(500) do |ids|- mapped = ids.map { |id| existing_map[id] }.compact- DB.exec(<<~SQL, ids: mapped) if mapped.present?+ PostCustomField+ .where(name: "import_unique_id")+ .pluck(:post_id, :value)+ .each { |post_id, import_id| existing_map[import_id.to_i] = post_id.to_i }++ results+ .map { |r| r["post_id"] }+ .each_slice(500) do |ids|+ mapped = ids.map { |id| existing_map[id] }.compact+ DB.exec(<<~SQL, ids: mapped) if mapped.present?UPDATE topics SET closed = trueWHERE id IN (SELECT topic_id FROM posts where id in (:ids))SQL- end-+ endenddef create_permalinks@@ -835,7 +878,6 @@ SQLr = DB.exec sqlputs "#{r} permalinks to posts added!"-enddef find_upload(user_id, attachment_id, real_filename)@@ -846,7 +888,7 @@ SQLputs "Attachment file doesn't exist: #{filename}"return nilend- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."upload = create_upload(user_id, filename, real_filename)if upload.nil? || !upload.valid?@@ -864,48 +906,57 @@ SQLdefault_extensions = SiteSetting.authorized_extensionsdefault_max_att_size = SiteSetting.max_attachment_size_kbSiteSetting.authorized_extensions = "*"- SiteSetting.max_attachment_size_kb = 307200+ SiteSetting.max_attachment_size_kb = 307_200current = 0max = Post.count- mysql_query("create index idxUniqueId on message2(unique_id)") rescue nil- attachments = mysql_query("SELECT a.attachment_id, a.file_name, m.message_uid FROM tblia_attachment a INNER JOIN tblia_message_attachments m ON a.attachment_id = m.attachment_id")-- Post.where('id > ?', @max_start_id).find_each do |post|- begin- id = post.custom_fields["import_unique_id"]- next unless id- raw = mysql_query("select body from message2 where unique_id = '#{id}'").first['body']- unless raw- puts "Missing raw for post: #{post.id}"- next- end- new_raw = postprocess_post_raw(raw, post.user_id)- files = attachments.select { |a| a["message_uid"].to_s == id }- new_raw << html_for_attachments(post.user_id, files)- unless post.raw == new_raw- post.raw = new_raw- post.cooked = post.cook(new_raw)- cpp = CookedPostProcessor.new(post)- cpp.link_post_uploads- post.custom_fields["import_post_process"] = true- post.save+ begin+ mysql_query("create index idxUniqueId on message2(unique_id)")+ rescue StandardError+ nil+ end+ attachments =+ mysql_query(+ "SELECT a.attachment_id, a.file_name, m.message_uid FROM tblia_attachment a INNER JOIN tblia_message_attachments m ON a.attachment_id = m.attachment_id",+ )++ Post+ .where("id > ?", @max_start_id)+ .find_each do |post|+ begin+ id = post.custom_fields["import_unique_id"]+ next unless id+ raw = mysql_query("select body from message2 where unique_id = '#{id}'").first["body"]+ unless raw+ puts "Missing raw for post: #{post.id}"+ next+ end+ new_raw = postprocess_post_raw(raw, post.user_id)+ files = attachments.select { |a| a["message_uid"].to_s == id }+ new_raw << html_for_attachments(post.user_id, files)+ unless post.raw == new_raw+ post.raw = new_raw+ post.cooked = post.cook(new_raw)+ cpp = CookedPostProcessor.new(post)+ cpp.link_post_uploads+ post.custom_fields["import_post_process"] = true+ post.save+ end+ rescue PrettyText::JavaScriptError+ puts "GOT A JS error on post: #{post.id}"+ nil+ ensure+ print_status(current += 1, max)end- rescue PrettyText::JavaScriptError- puts "GOT A JS error on post: #{post.id}"- nil- ensure- print_status(current += 1, max)end- endSiteSetting.authorized_extensions = default_extensionsSiteSetting.max_attachment_size_kb = default_max_att_sizeenddef postprocess_post_raw(raw, user_id)- matches = raw.match(/<messagetemplate.*<\/messagetemplate>/m) || []+ matches = raw.match(%r{<messagetemplate.*</messagetemplate>}m) || []matches.each do |match|hash = Hash.from_xml(match)template = hash["messagetemplate"]["zone"]["item"]@@ -915,106 +966,123 @@ SQLdoc = Nokogiri::HTML5.fragment(raw)- doc.css("a,img,li-image").each do |l|- upload_name, image, linked_upload = [nil] * 3+ doc+ .css("a,img,li-image")+ .each do |l|+ upload_name, image, linked_upload = [nil] * 3- if l.name == "li-image" && l["id"]- upload_name = l["id"]- else- uri = URI.parse(l["href"] || l["src"]) rescue nil- uri.hostname = nil if uri && uri.hostname == OLD_DOMAIN-- if uri && !uri.hostname- if l["href"]- l["href"] = uri.path- # we have an internal link, lets see if we can remap it?- permalink = Permalink.find_by_url(uri.path) rescue nil+ if l.name == "li-image" && l["id"]+ upload_name = l["id"]+ else+ uri =+ begin+ URI.parse(l["href"] || l["src"])+ rescue StandardError+ nil+ end+ uri.hostname = nil if uri && uri.hostname == OLD_DOMAIN+ if uri && !uri.hostnameif l["href"]- if permalink && permalink.target_url- l["href"] = permalink.target_url- elsif l["href"] =~ /^\/gartner\/attachments\/gartner\/([^.]*).(\w*)/- linked_upload = "#{$1}.#{$2}"+ l["href"] = uri.path+ # we have an internal link, lets see if we can remap it?+ permalink =+ begin+ Permalink.find_by_url(uri.path)+ rescue StandardError+ nil+ end++ if l["href"]+ if permalink && permalink.target_url+ l["href"] = permalink.target_url+ elsif l["href"] =~ %r{^/gartner/attachments/gartner/([^.]*).(\w*)}+ linked_upload = "#{$1}.#{$2}"+ endend+ elsif l["src"]+ # we need an upload here+ upload_name = $1 if uri.path =~ %r{image-id/([^/]+)}end- elsif l["src"]-- # we need an upload here- upload_name = $1 if uri.path =~ /image-id\/([^\/]+)/endend- end- if upload_name- png = UPLOAD_DIR + "/" + upload_name + ".png"- jpg = UPLOAD_DIR + "/" + upload_name + ".jpg"- gif = UPLOAD_DIR + "/" + upload_name + ".gif"-- # check to see if we have it- if File.exist?(png)- image = png- elsif File.exist?(jpg)- image = jpg- elsif File.exist?(gif)- image = gif- end+ if upload_name+ png = UPLOAD_DIR + "/" + upload_name + ".png"+ jpg = UPLOAD_DIR + "/" + upload_name + ".jpg"+ gif = UPLOAD_DIR + "/" + upload_name + ".gif"++ # check to see if we have it+ if File.exist?(png)+ image = png+ elsif File.exist?(jpg)+ image = jpg+ elsif File.exist?(gif)+ image = gif+ end- if image- File.open(image) do |file|- upload = UploadCreator.new(file, "image." + (image.ends_with?(".png") ? "png" : "jpg")).create_for(user_id)- l.name = "img" if l.name == "li-image"- l["src"] = upload.url+ if image+ File.open(image) do |file|+ upload =+ UploadCreator.new(+ file,+ "image." + (image.ends_with?(".png") ? "png" : "jpg"),+ ).create_for(user_id)+ l.name = "img" if l.name == "li-image"+ l["src"] = upload.url+ end+ else+ puts "image was missing #{l["src"]}"end- else- puts "image was missing #{l["src"]}"- end- elsif linked_upload- segments = linked_upload.match(/\/(\d*)\/(\d)\/([^.]*).(\w*)$/)+ elsif linked_upload+ segments = linked_upload.match(%r{/(\d*)/(\d)/([^.]*).(\w*)$})- if segments.present?- lithium_post_id = segments[1]- attachment_number = segments[2]+ if segments.present?+ lithium_post_id = segments[1]+ attachment_number = segments[2]- result = mysql_query("select a.attachment_id, f.file_name from tblia_message_attachments a+ result =+ mysql_query(+ "select a.attachment_id, f.file_name from tblia_message_attachments aINNER JOIN message2 m ON a.message_uid = m.unique_idINNER JOIN tblia_attachment f ON a.attachment_id = f.attachment_id- where m.id = #{lithium_post_id} AND a.attach_num = #{attachment_number} limit 0, 1")-- result.each do |row|- upload, filename = find_upload(user_id, row["attachment_id"], row["file_name"])- if upload.present?- l["href"] = upload.url- else- puts "attachment was missing #{l["href"]}"+ where m.id = #{lithium_post_id} AND a.attach_num = #{attachment_number} limit 0, 1",+ )++ result.each do |row|+ upload, filename = find_upload(user_id, row["attachment_id"], row["file_name"])+ if upload.present?+ l["href"] = upload.url+ else+ puts "attachment was missing #{l["href"]}"+ endendendendend- end-# for user mentions- doc.css("li-user").each do |l|- uid = l["uid"]-- if uid.present?- user = UserCustomField.find_by(name: 'import_id', value: uid).try(:user)- if user.present?- username = user.username- span = l.document.create_element "span"- span.inner_html = "@#{username}"- l.replace span+ doc+ .css("li-user")+ .each do |l|+ uid = l["uid"]++ if uid.present?+ user = UserCustomField.find_by(name: "import_id", value: uid).try(:user)+ if user.present?+ username = user.username+ span = l.document.create_element "span"+ span.inner_html = "@#{username}"+ l.replace span+ endendend- endraw = ReverseMarkdown.convert(doc.to_s)raw.gsub!(/^\s* \s*$/, "")# ugly quotesraw.gsub!(/^>[\s\*]*$/, "")- raw.gsub!(/:([a-z]+):/) do |match|- ":#{SMILEY_SUBS[$1] || $1}:"- end+ raw.gsub!(/:([a-z]+):/) { |match| ":#{SMILEY_SUBS[$1] || $1}:" }# nbsp centralraw.gsub!(/([a-zA-Z0-9]) ([a-zA-Z0-9])/, "\\1 \\2")raw@@ -1037,7 +1105,6 @@ SQLdef mysql_query(sql)@client.query(sql, cache_rows: true)end-endImportScripts::Lithium.new.performdiff --git a/script/import_scripts/mbox.rb b/script/import_scripts/mbox.rbindex d712a5055d2..9756f3f04ee 100644--- a/script/import_scripts/mbox.rb+++ b/script/import_scripts/mbox.rb@@ -1,14 +1,15 @@# frozen_string_literal: trueif ARGV.length != 1 || !File.exist?(ARGV[0])- STDERR.puts '', 'Usage of mbox importer:', 'bundle exec ruby mbox.rb <path/to/settings.yml>'- STDERR.puts '', "Use the settings file from #{File.expand_path('mbox/settings.yml', File.dirname(__FILE__))} as an example."+ STDERR.puts "", "Usage of mbox importer:", "bundle exec ruby mbox.rb <path/to/settings.yml>"+ STDERR.puts "",+ "Use the settings file from #{File.expand_path("mbox/settings.yml", File.dirname(__FILE__))} as an example."exit 1endmodule ImportScriptsmodule Mbox- require_relative 'mbox/importer'+ require_relative "mbox/importer"Importer.new(ARGV[0]).performendenddiff --git a/script/import_scripts/mbox/importer.rb b/script/import_scripts/mbox/importer.rbindex b3712481697..59baba38879 100644--- a/script/import_scripts/mbox/importer.rb+++ b/script/import_scripts/mbox/importer.rb@@ -1,9 +1,9 @@# frozen_string_literal: true-require_relative '../base'-require_relative 'support/database'-require_relative 'support/indexer'-require_relative 'support/settings'+require_relative "../base"+require_relative "support/database"+require_relative "support/indexer"+require_relative "support/settings"module ImportScripts::Mboxclass Importer < ImportScripts::Base@@ -38,44 +38,44 @@ module ImportScripts::Mboxenddef index_messages- puts '', 'creating index'+ puts "", "creating index"indexer = Indexer.new(@database, @settings)indexer.executeenddef import_categories- puts '', 'creating categories'+ puts "", "creating categories"rows = @database.fetch_categoriescreate_categories(rows) do |row|{- id: row['name'],- name: row['name'],- parent_category_id: row['parent_category_id'].presence,+ id: row["name"],+ name: row["name"],+ parent_category_id: row["parent_category_id"].presence,}endenddef import_users- puts '', 'creating users'+ puts "", "creating users"total_count = @database.count_users- last_email = ''+ last_email = ""batches do |offset|rows, last_email = @database.fetch_users(last_email)break if rows.empty?- next if all_records_exist?(:users, rows.map { |row| row['email'] })+ next if all_records_exist?(:users, rows.map { |row| row["email"] })create_users(rows, total: total_count, offset: offset) do |row|{- id: row['email'],- email: row['email'],- name: row['name'],+ id: row["email"],+ email: row["email"],+ name: row["name"],trust_level: @settings.trust_level,staged: @settings.staged,active: [email protected],- created_at: to_time(row['date_of_first_message'])+ created_at: to_time(row["date_of_first_message"]),}endend@@ -86,7 +86,7 @@ module ImportScripts::Mboxenddef import_posts- puts '', 'creating topics and posts'+ puts "", "creating topics and posts"total_count = @database.count_messageslast_row_id = 0@@ -94,47 +94,45 @@ module ImportScripts::Mboxrows, last_row_id = @database.fetch_messages(last_row_id)break if rows.empty?- next if all_records_exist?(:posts, rows.map { |row| row['msg_id'] })+ next if all_records_exist?(:posts, rows.map { |row| row["msg_id"] })create_posts(rows, total: total_count, offset: offset) do |row|begin- if row['email_date'].blank?- puts "Date is missing. Skipping #{row['msg_id']}"+ if row["email_date"].blank?+ puts "Date is missing. Skipping #{row["msg_id"]}"nil- elsif row['in_reply_to'].blank?+ elsif row["in_reply_to"].blank?map_first_post(row)elsemap_reply(row)endrescue => e- puts "Failed to map post for #{row['msg_id']}", e, e.backtrace.join("\n")+ puts "Failed to map post for #{row["msg_id"]}", e, e.backtrace.join("\n")endendendenddef map_post(row)- user_id = user_id_from_imported_user_id(row['from_email']) || Discourse::SYSTEM_USER_ID+ user_id = user_id_from_imported_user_id(row["from_email"]) || Discourse::SYSTEM_USER_ID{- id: row['msg_id'],+ id: row["msg_id"],user_id: user_id,- created_at: to_time(row['email_date']),+ created_at: to_time(row["email_date"]),raw: format_raw(row, user_id),- raw_email: row['raw_message'],+ raw_email: row["raw_message"],via_email: true,- post_create_action: proc do |post|- create_incoming_email(post, row)- end+ post_create_action: proc { |post| create_incoming_email(post, row) },}enddef format_raw(row, user_id)- body = row['body'] || ''- elided = row['elided']+ body = row["body"] || ""+ elided = row["elided"]- if row['attachment_count'].positive?- receiver = Email::Receiver.new(row['raw_message'])+ if row["attachment_count"].positive?+ receiver = Email::Receiver.new(row["raw_message"])user = User.find(user_id)body = receiver.add_attachments(body, user)end@@ -147,21 +145,21 @@ module ImportScripts::Mboxenddef map_first_post(row)- subject = row['subject']+ subject = row["subject"]tags = remove_tags!(subject)mapped = map_post(row)- mapped[:category] = category_id_from_imported_category_id(row['category'])+ mapped[:category] = category_id_from_imported_category_id(row["category"])mapped[:title] = subject.strip[0...255]mapped[:tags] = tags if tags.present?mappedenddef map_reply(row)- parent = @lookup.topic_lookup_from_imported_post_id(row['in_reply_to'])+ parent = @lookup.topic_lookup_from_imported_post_id(row["in_reply_to"])if parent.blank?- puts "Parent message #{row['in_reply_to']} doesn't exist. Skipping #{row['msg_id']}: #{row['subject'][0..40]}"+ puts "Parent message #{row["in_reply_to"]} doesn't exist. Skipping #{row["msg_id"]}: #{row["subject"][0..40]}"return nilend@@ -178,9 +176,7 @@ module ImportScripts::Mboxold_length = subject.length@settings.tags.each do |tag|- if subject.sub!(tag[:regex], "") && tag[:name].present?- tag_names << tag[:name]- end+ tag_names << tag[:name] if subject.sub!(tag[:regex], "") && tag[:name].present?endremove_prefixes!(subject) if subject.length != old_length@@ -203,13 +199,13 @@ module ImportScripts::Mboxdef create_incoming_email(post, row)IncomingEmail.create(- message_id: row['msg_id'],- raw: row['raw_message'],- subject: row['subject'],- from_address: row['from_email'],+ message_id: row["msg_id"],+ raw: row["raw_message"],+ subject: row["subject"],+ from_address: row["from_email"],user_id: post.user_id,topic_id: post.topic_id,- post_id: post.id+ post_id: post.id,)enddiff --git a/script/import_scripts/mbox/support/database.rb b/script/import_scripts/mbox/support/database.rbindex 9eb0b1f30b1..0e0522d2046 100644--- a/script/import_scripts/mbox/support/database.rb+++ b/script/import_scripts/mbox/support/database.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require 'sqlite3'+require "sqlite3"module ImportScripts::Mboxclass Database@@ -23,8 +23,7 @@ module ImportScripts::Mbox@db.transactionyield self@db.commit-- rescue+ rescue StandardError@db.rollbackend@@ -60,9 +59,7 @@ module ImportScripts::MboxSQL@db.prepare(sql) do |stmt|- reply_message_ids.each do |in_reply_to|- stmt.execute(msg_id, in_reply_to)- end+ reply_message_ids.each { |in_reply_to| stmt.execute(msg_id, in_reply_to) }endend@@ -95,7 +92,7 @@ module ImportScripts::Mboxenddef sort_emails_by_date_and_reply_level- @db.execute 'DELETE FROM email_order'+ @db.execute "DELETE FROM email_order"@db.execute <<-SQLWITH RECURSIVE@@ -117,7 +114,7 @@ module ImportScripts::Mboxenddef sort_emails_by_subject- @db.execute 'DELETE FROM email_order'+ @db.execute "DELETE FROM email_order"@db.execute <<-SQLINSERT INTO email_order (msg_id)@@ -128,7 +125,7 @@ module ImportScripts::Mboxenddef fill_users_from_emails- @db.execute 'DELETE FROM user'+ @db.execute "DELETE FROM user"@db.execute <<-SQLINSERT INTO user (email, name, date_of_first_message)@@ -172,7 +169,7 @@ module ImportScripts::MboxLIMIT #{@batch_size}SQL- add_last_column_value(rows, 'email')+ add_last_column_value(rows, "email")enddef count_messages@@ -193,14 +190,14 @@ module ImportScripts::MboxLIMIT #{@batch_size}SQL- add_last_column_value(rows, 'rowid')+ add_last_column_value(rows, "rowid")endprivatedef configure_database- @db.execute 'PRAGMA journal_mode = OFF'- @db.execute 'PRAGMA locking_mode = EXCLUSIVE'+ @db.execute "PRAGMA journal_mode = OFF"+ @db.execute "PRAGMA locking_mode = EXCLUSIVE"enddef upgrade_schema_version@@ -260,10 +257,10 @@ module ImportScripts::Mbox)SQL- @db.execute 'CREATE INDEX IF NOT EXISTS email_by_from ON email (from_email)'- @db.execute 'CREATE INDEX IF NOT EXISTS email_by_subject ON email (subject)'- @db.execute 'CREATE INDEX IF NOT EXISTS email_by_in_reply_to ON email (in_reply_to)'- @db.execute 'CREATE INDEX IF NOT EXISTS email_by_date ON email (email_date)'+ @db.execute "CREATE INDEX IF NOT EXISTS email_by_from ON email (from_email)"+ @db.execute "CREATE INDEX IF NOT EXISTS email_by_subject ON email (subject)"+ @db.execute "CREATE INDEX IF NOT EXISTS email_by_in_reply_to ON email (in_reply_to)"+ @db.execute "CREATE INDEX IF NOT EXISTS email_by_date ON email (email_date)"@db.execute <<-SQLCREATE TABLE IF NOT EXISTS email_order (@@ -282,7 +279,7 @@ module ImportScripts::Mbox)SQL- @db.execute 'CREATE INDEX IF NOT EXISTS reply_by_in_reply_to ON reply (in_reply_to)'+ @db.execute "CREATE INDEX IF NOT EXISTS reply_by_in_reply_to ON reply (in_reply_to)"enddef create_table_for_usersdiff --git a/script/import_scripts/mbox/support/indexer.rb b/script/import_scripts/mbox/support/indexer.rbindex b381292c47a..b19f83f5ff1 100644--- a/script/import_scripts/mbox/support/indexer.rb+++ b/script/import_scripts/mbox/support/indexer.rb@@ -1,8 +1,8 @@# frozen_string_literal: true-require_relative 'database'-require 'json'-require 'yaml'+require_relative "database"+require "json"+require "yaml"module ImportScripts::Mboxclass Indexer@@ -15,7 +15,7 @@ module ImportScripts::Mboxenddef execute- directories = Dir.glob(File.join(@settings.data_dir, '*'))+ directories = Dir.glob(File.join(@settings.data_dir, "*"))directories.select! { |f| File.directory?(f) }directories.sort!@@ -25,7 +25,7 @@ module ImportScripts::Mboxindex_emails(directory, category[:name])end- puts '', 'indexing replies and users'+ puts "", "indexing replies and users"if @settings.group_messages_by_subject@database.sort_emails_by_subject@database.update_in_reply_to_by_email_subject@@ -39,24 +39,24 @@ module ImportScripts::Mboxprivate- METADATA_FILENAME = 'metadata.yml'- IGNORED_FILE_EXTENSIONS = ['.dbindex', '.dbnames', '.digest', '.subjects', '.yml']+ METADATA_FILENAME = "metadata.yml"+ IGNORED_FILE_EXTENSIONS = %w[.dbindex .dbnames .digest .subjects .yml]def index_category(directory)metadata_file = File.join(directory, METADATA_FILENAME)if File.exist?(metadata_file)# workaround for YML files that contain classname in file header- yaml = File.read(metadata_file).sub(/^--- !.*$/, '---')+ yaml = File.read(metadata_file).sub(/^--- !.*$/, "---")metadata = YAML.safe_load(yaml)elsemetadata = {}endcategory = {- name: metadata['name'].presence || File.basename(directory),- description: metadata['description'],- parent_category_id: metadata['parent_category_id'].presence,+ name: metadata["name"].presence || File.basename(directory),+ description: metadata["description"],+ parent_category_id: metadata["parent_category_id"].presence,}@database.insert_category(category)@@ -75,7 +75,7 @@ module ImportScripts::Mbox# Detect cases like this and attempt to get actual sender from other headers:# From: Jane Smith via ListName <[email protected]>- if receiver.mail['X-Mailman-Version'] && from_display_name =~ /\bvia \S+$/i+ if receiver.mail["X-Mailman-Version"] && from_display_name =~ /\bvia \S+$/iemail_from_from_line = opts[:from_line].scan(/From (\S+)/).flatten.firsta = Mail::Address.new(email_from_from_line)from_email = a.address@@ -88,7 +88,7 @@ module ImportScripts::Mboxendend- from_email = from_email.sub(/^(.*)=/, '') if @settings.elide_equals_in_addresses+ from_email = from_email.sub(/^(.*)=/, "") if @settings.elide_equals_in_addressesbody, elided, format = receiver.select_bodyreply_message_ids = extract_reply_message_ids(parsed_email)@@ -109,7 +109,7 @@ module ImportScripts::Mboxfilename: File.basename(filename),first_line_number: opts[:first_line_number],last_line_number: opts[:last_line_number],- index_duration: (monotonic_time - opts[:start_time]).round(4)+ index_duration: (monotonic_time - opts[:start_time]).round(4),}@database.transaction do |db|@@ -132,8 +132,8 @@ module ImportScripts::Mboxdef imported_file_checksums(category_name)rows = @database.fetch_imported_files(category_name)rows.each_with_object({}) do |row, hash|- filename = File.basename(row['filename'])- hash[filename] = row['checksum']+ filename = File.basename(row["filename"])+ hash[filename] = row["checksum"]endend@@ -171,14 +171,14 @@ module ImportScripts::Mboximported_file = {category: category_name,filename: File.basename(filename),- checksum: calc_checksum(filename)+ checksum: calc_checksum(filename),}@database.insert_imported_file(imported_file)enddef each_mail(filename)- raw_message = +''+ raw_message = +""first_line_number = 1last_line_number = 0@@ -188,7 +188,7 @@ module ImportScripts::Mboxif line.scrub =~ @split_regexif last_line_number > 0yield raw_message, first_line_number, last_line_number, from_line- raw_message = +''+ raw_message = +""first_line_number = last_line_number + 1end@@ -204,12 +204,10 @@ module ImportScripts::Mboxenddef each_line(filename)- raw_file = File.open(filename, 'r')- text_file = filename.end_with?('.gz') ? Zlib::GzipReader.new(raw_file) : raw_file+ raw_file = File.open(filename, "r")+ text_file = filename.end_with?(".gz") ? Zlib::GzipReader.new(raw_file) : raw_file- text_file.each_line do |line|- yield line- end+ text_file.each_line { |line| yield line }ensureraw_file.close if raw_fileend@@ -220,7 +218,9 @@ module ImportScripts::Mboxenddef read_mail_from_string(raw_message)- Email::Receiver.new(raw_message, convert_plaintext: true, skip_trimming: false) unless raw_message.blank?+ unless raw_message.blank?+ Email::Receiver.new(raw_message, convert_plaintext: true, skip_trimming: false)+ endenddef extract_reply_message_ids(mail)@@ -229,14 +229,13 @@ module ImportScripts::Mboxdef extract_subject(receiver, list_name)subject = receiver.subject- subject.blank? ? nil : subject.strip.gsub(/\t+/, ' ')+ subject.blank? ? nil : subject.strip.gsub(/\t+/, " ")enddef ignored_file?(path, checksums)filename = File.basename(path)- filename.start_with?('.') ||- filename == METADATA_FILENAME ||+ filename.start_with?(".") || filename == METADATA_FILENAME ||IGNORED_FILE_EXTENSIONS.include?(File.extname(filename)) ||fully_indexed?(path, filename, checksums)enddiff --git a/script/import_scripts/mbox/support/settings.rb b/script/import_scripts/mbox/support/settings.rbindex eff1511b67a..9c99a174410 100644--- a/script/import_scripts/mbox/support/settings.rb+++ b/script/import_scripts/mbox/support/settings.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require 'yaml'+require "yaml"module ImportScripts::Mboxclass Settings@@ -25,32 +25,32 @@ module ImportScripts::Mboxattr_reader :elide_equals_in_addressesdef initialize(yaml)- @data_dir = yaml['data_dir']- @split_regex = Regexp.new(yaml['split_regex']) unless yaml['split_regex'].empty?+ @data_dir = yaml["data_dir"]+ @split_regex = Regexp.new(yaml["split_regex"]) unless yaml["split_regex"].empty?@batch_size = 1000 # no need to make this actually configurable at the moment- @trust_level = yaml['default_trust_level']- @prefer_html = yaml['prefer_html']- @staged = yaml['staged']- @index_only = yaml['index_only']- @group_messages_by_subject = yaml['group_messages_by_subject']+ @trust_level = yaml["default_trust_level"]+ @prefer_html = yaml["prefer_html"]+ @staged = yaml["staged"]+ @index_only = yaml["index_only"]+ @group_messages_by_subject = yaml["group_messages_by_subject"]- if yaml['remove_subject_prefixes'].present?- prefix_regexes = yaml['remove_subject_prefixes'].map { |p| Regexp.new(p) }+ if yaml["remove_subject_prefixes"].present?+ prefix_regexes = yaml["remove_subject_prefixes"].map { |p| Regexp.new(p) }@subject_prefix_regex = /^#{Regexp.union(prefix_regexes).source}/iend- @automatically_remove_list_name_prefix = yaml['automatically_remove_list_name_prefix']- @show_trimmed_content = yaml['show_trimmed_content']- @fix_mailman_via_addresses = yaml['fix_mailman_via_addresses']- @elide_equals_in_addresses = yaml['elide_equals_in_addresses']+ @automatically_remove_list_name_prefix = yaml["automatically_remove_list_name_prefix"]+ @show_trimmed_content = yaml["show_trimmed_content"]+ @fix_mailman_via_addresses = yaml["fix_mailman_via_addresses"]+ @elide_equals_in_addresses = yaml["elide_equals_in_addresses"]@tags = []- if yaml['tags'].present?- yaml['tags'].each do |tag_name, value|+ if yaml["tags"].present?+ yaml["tags"].each do |tag_name, value|prefixes = Regexp.union(value).source@tags << {regex: /^(?:(?:\[(?:#{prefixes})\])|(?:\((?:#{prefixes})\)))\s*/i,- name: tag_name+ name: tag_name,}endenddiff --git a/script/import_scripts/modx.rb b/script/import_scripts/modx.rbindex 1221dcc4428..a24586279ff 100644--- a/script/import_scripts/modx.rb+++ b/script/import_scripts/modx.rb@@ -1,23 +1,23 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'+require "htmlentities"class ImportScripts::Modx < ImportScripts::BaseBATCH_SIZE = 1000# CHANGE THESE BEFORE RUNNING THE IMPORTER- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "modx"- DB_PW ||= ENV['DB_PW'] || "modex"- DB_USER ||= ENV['DB_USER'] || "modx"- TIMEZONE ||= ENV['TIMEZONE'] || "America/Los_Angeles"- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "modx_"- ATTACHMENT_DIR ||= ENV['ATTACHMENT_DIR'] || '/path/to/your/attachment/folder'- RANDOM_CATEGORY_COLOR ||= !ENV['RANDOM_CATEGORY_COLOR'].nil?- SUSPEND_ALL_USERS ||= !ENV['SUSPEND_ALL_USERS']+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "modx"+ DB_PW ||= ENV["DB_PW"] || "modex"+ DB_USER ||= ENV["DB_USER"] || "modx"+ TIMEZONE ||= ENV["TIMEZONE"] || "America/Los_Angeles"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "modx_"+ ATTACHMENT_DIR ||= ENV["ATTACHMENT_DIR"] || "/path/to/your/attachment/folder"+ RANDOM_CATEGORY_COLOR ||= !ENV["RANDOM_CATEGORY_COLOR"].nil?+ SUSPEND_ALL_USERS ||= !ENV["SUSPEND_ALL_USERS"]# TODO: replace modx_ with #{TABLE_PREFIX}@@ -34,14 +34,10 @@ class ImportScripts::Modx < ImportScripts::Base@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- password: DB_PW,- database: DB_NAME- )+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, password: DB_PW, database: DB_NAME)rescue Exception => e- puts '=' * 50+ puts "=" * 50puts e.messageputs <<~TEXTCannot connect in to database.@@ -83,22 +79,20 @@ class ImportScripts::Modx < ImportScripts::BaseSQLcreate_groups(groups) do |group|- {- id: group["usergroupid"],- name: @htmlentities.decode(group["title"]).strip- }+ { id: group["usergroupid"], name: @htmlentities.decode(group["title"]).strip }endenddef import_usersputs "", "importing users"- user_count = mysql_query("SELECT COUNT(id) count FROM #{TABLE_PREFIX}discuss_users").first["count"]+ user_count =+ mysql_query("SELECT COUNT(id) count FROM #{TABLE_PREFIX}discuss_users").first["count"]last_user_id = -1batches(BATCH_SIZE) do |offset|- users = mysql_query(<<-SQL+ users = mysql_query(<<-SQL).to_aSELECT id as userid, email, concat (name_first, " ", name_last) as name, username,location, website, status, last_active as last_seen_at,createdon as created_at, birthdate as date_of_birth,@@ -112,7 +106,6 @@ FROM #{TABLE_PREFIX}discuss_usersORDER BY idLIMIT #{BATCH_SIZE};SQL- ).to_abreak if users.empty?@@ -123,14 +116,14 @@ FROM #{TABLE_PREFIX}discuss_userscreate_users(users, total: user_count, offset: offset) do |user|{id: user["userid"],- name: user['name'],- username: user['username'],- email: user['email'],- website: user['website'],+ name: user["name"],+ username: user["username"],+ email: user["email"],+ website: user["website"],created_at: parse_timestamp(user["created_at"]),last_seen_at: parse_timestamp(user["last_seen_at"]),- date_of_birth: user['date_of_birth'],- password: "#{user['password']}:#{user['salt']}" # not tested+ date_of_birth: user["date_of_birth"],+ password: "#{user["password"]}:#{user["salt"]}", # not tested}endend@@ -144,13 +137,13 @@ FROM #{TABLE_PREFIX}discuss_userscategories = mysql_query("select id, name, description from modx_discuss_categories").to_acreate_categories(categories) do |category|- puts "Creating #{category['name']}"+ puts "Creating #{category["name"]}"puts category{- id: "cat#{category['id']}",+ id: "cat#{category["id"]}",name: category["name"],color: RANDOM_CATEGORY_COLOR ? (0..2).map { "%0x" % (rand * 0x80) }.join : nil,- description: category["description"]+ description: category["description"],}end@@ -159,13 +152,13 @@ FROM #{TABLE_PREFIX}discuss_usersboards = mysql_query("select id, category, name, description from modx_discuss_boards;").to_acreate_categories(boards) do |category|puts category- parent_category_id = category_id_from_imported_category_id("cat#{category['category']}")+ parent_category_id = category_id_from_imported_category_id("cat#{category["category"]}"){id: category["id"],parent_category_id: parent_category_id.to_s,name: category["name"],color: RANDOM_CATEGORY_COLOR ? (0..2).map { "%0x" % (rand * 0x80) }.join : nil,- description: category["description"]+ description: category["description"],}endend@@ -173,12 +166,15 @@ FROM #{TABLE_PREFIX}discuss_usersdef import_topics_and_postsputs "", "creating topics and posts"- total_count = mysql_query("SELECT count(id) count from #{TABLE_PREFIX}discuss_posts").first["count"]+ total_count =+ mysql_query("SELECT count(id) count from #{TABLE_PREFIX}discuss_posts").first["count"]topic_first_post_id = {}batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT id,thread topic_id,board category_id,@@ -191,27 +187,28 @@ FROM #{TABLE_PREFIX}discuss_usersORDER BY createdonLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|skip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = post_process_raw(m['raw'])- mapped[:created_at] = Time.zone.at(m['created_at'])+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = post_process_raw(m["raw"])+ mapped[:created_at] = Time.zone.at(m["created_at"])- if m['parent'] == 0- mapped[:category] = category_id_from_imported_category_id(m['category_id'])- mapped[:title] = m['title']- topic_first_post_id[m['topic_id']] = m['id']+ if m["parent"] == 0+ mapped[:category] = category_id_from_imported_category_id(m["category_id"])+ mapped[:title] = m["title"]+ topic_first_post_id[m["topic_id"]] = m["id"]else- parent = topic_lookup_from_imported_post_id(topic_first_post_id[m['topic_id']])+ parent = topic_lookup_from_imported_post_id(topic_first_post_id[m["topic_id"]])if parentmapped[:topic_id] = parent[:topic_id]else@@ -227,10 +224,11 @@ FROM #{TABLE_PREFIX}discuss_usersdef post_process_raw(raw)# [QUOTE]...[/QUOTE]- raw = raw.gsub(/\[quote.*?\](.+?)\[\/quote\]/im) { |quote|- quote = quote.gsub(/\[quote author=(.*?) .+\]/i) { "\n[quote=\"#{$1}\"]\n" }- quote = quote.gsub(/[^\n]\[\/quote\]/im) { "\n[/quote]\n" }- }+ raw =+ raw.gsub(%r{\[quote.*?\](.+?)\[/quote\]}im) do |quote|+ quote = quote.gsub(/\[quote author=(.*?) .+\]/i) { "\n[quote=\"#{$1}\"]\n" }+ quote = quote.gsub(%r{[^\n]\[/quote\]}im) { "\n[/quote]\n" }+ endrawend@@ -249,25 +247,27 @@ FROM #{TABLE_PREFIX}discuss_users# find the uploaded file information from the dbdef not_find_upload(post, attachment_id)- sql = "SELECT a.attachmentid attachment_id, a.userid user_id, a.filedataid file_id, a.filename filename,+ sql =+ "SELECT a.attachmentid attachment_id, a.userid user_id, a.filedataid file_id, a.filename filename,a.caption captionFROM #{TABLE_PREFIX}attachment aWHERE a.attachmentid = #{attachment_id}"results = mysql_query(sql)unless row = results.first- puts "Couldn't find attachment record for post.id = #{post.id}, import_id = #{post.custom_fields['import_id']}"+ puts "Couldn't find attachment record for post.id = #{post.id}, import_id = #{post.custom_fields["import_id"]}"returnend- filename = File.join(ATTACHMENT_DIR, row['user_id'].to_s.split('').join('/'), "#{row['file_id']}.attach")+ filename =+ File.join(ATTACHMENT_DIR, row["user_id"].to_s.split("").join("/"), "#{row["file_id"]}.attach")unless File.exist?(filename)puts "Attachment file doesn't exist: #{filename}"returnend- real_filename = row['filename']- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ real_filename = row["filename"]+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."upload = create_upload(post.user.id, filename, real_filename)if upload.nil? || !upload.valid?@@ -286,24 +286,24 @@ FROM #{TABLE_PREFIX}discuss_usersdef not_import_private_messagesputs "", "importing private messages..."- topic_count = mysql_query("SELECT COUNT(pmtextid) count FROM #{TABLE_PREFIX}pmtext").first["count"]+ topic_count =+ mysql_query("SELECT COUNT(pmtextid) count FROM #{TABLE_PREFIX}pmtext").first["count"]last_private_message_id = -1batches(BATCH_SIZE) do |offset|- private_messages = mysql_query(<<-SQL+ private_messages = mysql_query(<<-SQL).to_aSELECT pmtextid, fromuserid, title, message, touserarray, datelineFROM #{TABLE_PREFIX}pmtextWHERE pmtextid > #{last_private_message_id}ORDER BY pmtextidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if private_messages.empty?last_private_message_id = private_messages[-1]["pmtextid"]- private_messages.reject! { |pm| @lookup.post_already_imported?("pm-#{pm['pmtextid']}") }+ private_messages.reject! { |pm| @lookup.post_already_imported?("pm-#{pm["pmtextid"]}") }title_username_of_pm_first_post = {}@@ -311,11 +311,16 @@ FROM #{TABLE_PREFIX}discuss_usersskip = falsemapped = {}- mapped[:id] = "pm-#{m['pmtextid']}"- mapped[:user_id] = user_id_from_imported_user_id(m['fromuserid']) || Discourse::SYSTEM_USER_ID- mapped[:raw] = preprocess_post_raw(m['message']) rescue nil- mapped[:created_at] = Time.zone.at(m['dateline'])- title = @htmlentities.decode(m['title']).strip[0...255]+ mapped[:id] = "pm-#{m["pmtextid"]}"+ mapped[:user_id] = user_id_from_imported_user_id(m["fromuserid"]) ||+ Discourse::SYSTEM_USER_ID+ mapped[:raw] = begin+ preprocess_post_raw(m["message"])+ rescue StandardError+ nil+ end+ mapped[:created_at] = Time.zone.at(m["dateline"])+ title = @htmlentities.decode(m["title"]).strip[0...255]topic_id = nilnext if mapped[:raw].blank?@@ -324,9 +329,9 @@ FROM #{TABLE_PREFIX}discuss_userstarget_usernames = []target_userids = []begin- to_user_array = PHP.unserialize(m['touserarray'])- rescue- puts "#{m['pmtextid']} -- #{m['touserarray']}"+ to_user_array = PHP.unserialize(m["touserarray"])+ rescue StandardError+ puts "#{m["pmtextid"]} -- #{m["touserarray"]}"skip = trueend@@ -346,8 +351,8 @@ FROM #{TABLE_PREFIX}discuss_userstarget_usernames << username if usernameendend- rescue- puts "skipping pm-#{m['pmtextid']} `to_user_array` is not properly serialized -- #{to_user_array.inspect}"+ rescue StandardError+ puts "skipping pm-#{m["pmtextid"]} `to_user_array` is not properly serialized -- #{to_user_array.inspect}"skip = trueend@@ -355,18 +360,18 @@ FROM #{TABLE_PREFIX}discuss_usersparticipants << mapped[:user_id]beginparticipants.sort!- rescue+ rescue StandardErrorputs "one of the participant's id is nil -- #{participants.inspect}"endif title =~ /^Re:/-- parent_id = title_username_of_pm_first_post[[title[3..-1], participants]] ||- title_username_of_pm_first_post[[title[4..-1], participants]] ||- title_username_of_pm_first_post[[title[5..-1], participants]] ||- title_username_of_pm_first_post[[title[6..-1], participants]] ||- title_username_of_pm_first_post[[title[7..-1], participants]] ||- title_username_of_pm_first_post[[title[8..-1], participants]]+ parent_id =+ title_username_of_pm_first_post[[title[3..-1], participants]] ||+ title_username_of_pm_first_post[[title[4..-1], participants]] ||+ title_username_of_pm_first_post[[title[5..-1], participants]] ||+ title_username_of_pm_first_post[[title[6..-1], participants]] ||+ title_username_of_pm_first_post[[title[7..-1], participants]] ||+ title_username_of_pm_first_post[[title[8..-1], participants]]if parent_idif t = topic_lookup_from_imported_post_id("pm-#{parent_id}")@@ -374,18 +379,18 @@ FROM #{TABLE_PREFIX}discuss_usersendendelse- title_username_of_pm_first_post[[title, participants]] ||= m['pmtextid']+ title_username_of_pm_first_post[[title, participants]] ||= m["pmtextid"]endunless topic_idmapped[:title] = titlemapped[:archetype] = Archetype.private_message- mapped[:target_usernames] = target_usernames.join(',')+ mapped[:target_usernames] = target_usernames.join(",")if mapped[:target_usernames].size < 1 # pm with yourself?# skip = truemapped[:target_usernames] = "system"- puts "pm-#{m['pmtextid']} has no target (#{m['touserarray']})"+ puts "pm-#{m["pmtextid"]} has no target (#{m["touserarray"]})"endelsemapped[:topic_id] = topic_id@@ -397,22 +402,21 @@ FROM #{TABLE_PREFIX}discuss_usersenddef not_import_attachments- puts '', 'importing attachments...'+ puts "", "importing attachments..."current_count = 0- total_count = mysql_query(<<-SQL+ total_count = mysql_query(<<-SQL).first["count"]SELECT COUNT(postid) countFROM #{TABLE_PREFIX}post pJOIN #{TABLE_PREFIX}thread t ON t.threadid = p.threadidWHERE t.firstpostid <> p.postidSQL- ).first["count"]success_count = 0fail_count = 0- attachment_regex = /\[attach[^\]]*\](\d+)\[\/attach\]/i+ attachment_regex = %r{\[attach[^\]]*\](\d+)\[/attach\]}iPost.find_each do |post|current_count += 1@@ -433,7 +437,12 @@ FROM #{TABLE_PREFIX}discuss_usersendif new_raw != post.raw- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, bypass_bump: true, edit_reason: 'Import attachments from modx')+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ bypass_bump: true,+ edit_reason: "Import attachments from modx",+ )endsuccess_count += 1@@ -496,14 +505,14 @@ FROM #{TABLE_PREFIX}discuss_usersenddef not_create_permalink_file- puts '', 'Creating Permalink File...', ''+ puts "", "Creating Permalink File...", ""id_mapping = []Topic.listable_topics.find_each do |topic|pcf = topic.first_post.custom_fieldsif pcf && pcf["import_id"]- id = pcf["import_id"].split('-').last+ id = pcf["import_id"].split("-").lastid_mapping.push("XXX#{id} YYY#{topic.id}")endend@@ -517,11 +526,8 @@ FROM #{TABLE_PREFIX}discuss_users# endCSV.open(File.expand_path("../vb_map.csv", __FILE__), "w") do |csv|- id_mapping.each do |value|- csv << [value]- end+ id_mapping.each { |value| csv << [value] }end-enddef deactivate_all_users@@ -529,16 +535,23 @@ FROM #{TABLE_PREFIX}discuss_usersenddef suspend_users- puts '', "updating blocked users"+ puts "", "updating blocked users"banned = 0failed = 0- total = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}user_attributes where blocked != 0").first['count']+ total =+ mysql_query(+ "SELECT count(*) count FROM #{TABLE_PREFIX}user_attributes where blocked != 0",+ ).first[+ "count"+ ]system_user = Discourse.system_user- mysql_query("SELECT id, blockedafter, blockeduntil FROM #{TABLE_PREFIX}user_attributes").each do |b|- user = User.find_by_id(user_id_from_imported_user_id(b['id']))+ mysql_query(+ "SELECT id, blockedafter, blockeduntil FROM #{TABLE_PREFIX}user_attributes",+ ).each do |b|+ user = User.find_by_id(user_id_from_imported_user_id(b["id"]))if useruser.suspended_at = parse_timestamp(user["blockedafter"])user.suspended_till = parse_timestamp(user["blockeduntil"])@@ -550,7 +563,7 @@ FROM #{TABLE_PREFIX}discuss_usersfailed += 1endelse- puts "Not found: #{b['userid']}"+ puts "Not found: #{b["userid"]}"failed += 1end@@ -565,7 +578,6 @@ FROM #{TABLE_PREFIX}discuss_usersdef mysql_query(sql)@client.query(sql, cache_rows: true)end-endImportScripts::Modx.new.performdiff --git a/script/import_scripts/muut.rb b/script/import_scripts/muut.rbindex a242c193638..32c780f3fce 100644--- a/script/import_scripts/muut.rb+++ b/script/import_scripts/muut.rb@@ -6,7 +6,6 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Edit the constants and initialize method for your import data.class ImportScripts::Muut < ImportScripts::Base-JSON_FILE_PATH = "/path/to/json/file"CSV_FILE_PATH = "/path/to/csv/file"@@ -36,39 +35,33 @@ class ImportScripts::Muut < ImportScripts::Baseenddef repair_json(arg)- arg.gsub!(/^\(/, "") # content of file is surround by ( )+ arg.gsub!(/^\(/, "") # content of file is surround by ( )arg.gsub!(/\)$/, "")- arg.gsub!(/\]\]$/, "]") # there can be an extra ] at the end+ arg.gsub!(/\]\]$/, "]") # there can be an extra ] at the endarg.gsub!(/\}\{/, "},{") # missing commas sometimes!- arg.gsub!("}]{", "},{") # surprise square brackets- arg.gsub!("}[{", "},{") # :troll:+ arg.gsub!("}]{", "},{") # surprise square brackets+ arg.gsub!("}[{", "},{") # :troll:argenddef import_users- puts '', "Importing users"+ puts "", "Importing users"- create_users(@imported_users) do |u|- {- id: u[0],- email: u[1],- created_at: Time.now- }- end+ create_users(@imported_users) { |u| { id: u[0], email: u[1], created_at: Time.now } }enddef import_categoriesputs "", "Importing categories"- create_categories(@imported_json['categories']) do |category|+ create_categories(@imported_json["categories"]) do |category|{- id: category['path'], # muut has no id for categories, so use the path- name: category['title'],- slug: category['path']+ id: category["path"], # muut has no id for categories, so use the path+ name: category["title"],+ slug: category["path"],}endend@@ -79,23 +72,23 @@ class ImportScripts::Muut < ImportScripts::Basetopics = 0posts = 0- @imported_json['categories'].each do |category|-- @imported_json['threads'][category['path']].each do |thread|-+ @imported_json["categories"].each do |category|+ @imported_json["threads"][category["path"]].each do |thread|next if thread["seed"]["key"] == "skip-this-topic"mapped = {}mapped[:id] = "#{thread["seed"]["key"]}-#{thread["seed"]["date"]}"- if thread["seed"]["author"] && user_id_from_imported_user_id(thread["seed"]["author"]["path"]) != ""+ if thread["seed"]["author"] &&+ user_id_from_imported_user_id(thread["seed"]["author"]["path"]) != ""mapped[:user_id] = user_id_from_imported_user_id(thread["seed"]["author"]["path"]) || -1elsemapped[:user_id] = -1end# update user display name- if thread["seed"]["author"] && thread["seed"]["author"]["displayname"] != "" && mapped[:user_id] != -1+ if thread["seed"]["author"] && thread["seed"]["author"]["displayname"] != "" &&+ mapped[:user_id] != -1user = User.find_by(id: mapped[:user_id])if useruser.name = thread["seed"]["author"]["displayname"]@@ -122,18 +115,21 @@ class ImportScripts::Muut < ImportScripts::Base# create repliesif thread["replies"].present? && thread["replies"].count > 0thread["replies"].reverse_each do |post|-if post_id_from_imported_post_id(post["id"])next # already imported this postend- new_post = create_post({- id: "#{post["key"]}-#{post["date"]}",- topic_id: parent_post.topic_id,- user_id: user_id_from_imported_user_id(post["author"]["path"]) || -1,- raw: process_muut_post_body(post["body"]),- created_at: Time.zone.at(post["date"])- }, post["id"])+ new_post =+ create_post(+ {+ id: "#{post["key"]}-#{post["date"]}",+ topic_id: parent_post.topic_id,+ user_id: user_id_from_imported_user_id(post["author"]["path"]) || -1,+ raw: process_muut_post_body(post["body"]),+ created_at: Time.zone.at(post["date"]),+ },+ post["id"],+ )if new_post.is_a?(Post)posts += 1@@ -141,9 +137,7 @@ class ImportScripts::Muut < ImportScripts::Baseputs "Error creating post #{post["id"]}. Skipping."puts new_post.inspectend-end-endtopics += 1@@ -165,7 +159,7 @@ class ImportScripts::Muut < ImportScripts::Baseraw.gsub!("---", "```\n")# tab- raw.gsub!(/\\t/, ' ')+ raw.gsub!(/\\t/, " ")# double quoteraw.gsub!(/\\\"/, '"')@@ -177,9 +171,6 @@ class ImportScripts::Muut < ImportScripts::Basedef file_full_path(relpath)File.join JSON_FILES_DIR, relpath.split("?").firstend-end-if __FILE__ == $0- ImportScripts::Muut.new.perform-end+ImportScripts::Muut.new.perform if __FILE__ == $0diff --git a/script/import_scripts/mybb.rb b/script/import_scripts/mybb.rbindex 770f6df1b49..10061d63e96 100644--- a/script/import_scripts/mybb.rb+++ b/script/import_scripts/mybb.rb@@ -18,13 +18,12 @@ export BASE="" ## Call it like this:# RAILS_ENV=production ruby script/import_scripts/mybb.rbclass ImportScripts::MyBB < ImportScripts::Base-- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "mybb"- DB_PW ||= ENV['DB_PW'] || ""- DB_USER ||= ENV['DB_USER'] || "root"- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "mybb_"- UPLOADS_DIR ||= ENV['UPLOADS'] || '/data/limelightgaming/uploads'+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "mybb"+ DB_PW ||= ENV["DB_PW"] || ""+ DB_USER ||= ENV["DB_USER"] || "root"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "mybb_"+ UPLOADS_DIR ||= ENV["UPLOADS"] || "/data/limelightgaming/uploads"BATCH_SIZE = 1000BASE = ""QUIET = true@@ -33,12 +32,8 @@ class ImportScripts::MyBB < ImportScripts::Basedef initializesuper- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- password: DB_PW,- database: DB_NAME- )+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, password: DB_PW, database: DB_NAME)enddef execute@@ -52,63 +47,79 @@ class ImportScripts::MyBB < ImportScripts::Baseenddef import_users- puts '', "creating users"+ puts "", "creating users"- total_count = mysql_query("SELECT count(*) count+ total_count =+ mysql_query(+ "SELECT count(*) countFROM #{TABLE_PREFIX}users uJOIN #{TABLE_PREFIX}usergroups g ON g.gid = u.usergroup- WHERE g.title != 'Banned';").first['count']+ WHERE g.title != 'Banned';",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT uid id, email email, username, regdate, g.title `group`, avatar+ results =+ mysql_query(+ "SELECT uid id, email email, username, regdate, g.title `group`, avatarFROM #{TABLE_PREFIX}users uJOIN #{TABLE_PREFIX}usergroups g ON g.gid = u.usergroupWHERE g.title != 'Banned'ORDER BY u.uid ASCLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1next if all_records_exist? :users, results.map { |u| u["id"].to_i }create_users(results, total: total_count, offset: offset) do |user|- avatar_url = user['avatar'].match(/^http/) ? user['avatar'].gsub(/\?.*/, "") : nil- { id: user['id'],- email: user['email'],- username: user['username'],- created_at: Time.zone.at(user['regdate']),- moderator: user['group'] == 'Super Moderators',- admin: user['group'] == 'Administrators' ,+ avatar_url = user["avatar"].match(/^http/) ? user["avatar"].gsub(/\?.*/, "") : nil+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ created_at: Time.zone.at(user["regdate"]),+ moderator: user["group"] == "Super Moderators",+ admin: user["group"] == "Administrators",avatar_url: avatar_url,- post_create_action: proc do |newuser|- if !user["avatar"].blank?- avatar = user["avatar"].gsub(/\?.*/, "")- if avatar.match(/^http.*/)- UserAvatar.import_url_for_user(avatar, newuser)- else- filename = File.join(UPLOADS_DIR, avatar)- @uploader.create_avatar(newuser, filename) if File.exists?(filename)+ post_create_action:+ proc do |newuser|+ if !user["avatar"].blank?+ avatar = user["avatar"].gsub(/\?.*/, "")+ if avatar.match(/^http.*/)+ UserAvatar.import_url_for_user(avatar, newuser)+ else+ filename = File.join(UPLOADS_DIR, avatar)+ @uploader.create_avatar(newuser, filename) if File.exists?(filename)+ endend- end- end+ end,}endendenddef import_categories- results = mysql_query("+ results =+ mysql_query(+ "SELECT fid id, pid parent_id, left(name, 50) name, descriptionFROM #{TABLE_PREFIX}forumsORDER BY pid ASC, fid ASC- ")+ ",+ )create_categories(results) do |row|- h = { id: row['id'], name: CGI.unescapeHTML(row['name']), description: CGI.unescapeHTML(row['description']) }- if row['parent_id'].to_i > 0- h[:parent_category_id] = category_id_from_imported_category_id(row['parent_id'])+ h = {+ id: row["id"],+ name: CGI.unescapeHTML(row["name"]),+ description: CGI.unescapeHTML(row["description"]),+ }+ if row["parent_id"].to_i > 0+ h[:parent_category_id] = category_id_from_imported_category_id(row["parent_id"])endhend@@ -120,7 +131,9 @@ class ImportScripts::MyBB < ImportScripts::Basetotal_count = mysql_query("SELECT count(*) count from #{TABLE_PREFIX}posts").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.pid id,p.tid topic_id,t.fid category_id,@@ -132,15 +145,16 @@ class ImportScripts::MyBB < ImportScripts::BaseFROM #{TABLE_PREFIX}posts p,#{TABLE_PREFIX}threads tWHERE p.tid = t.tid- #{'AND (p.visible = 1 AND t.visible = 1)' unless IMPORT_DELETED_POSTS}+ #{"AND (p.visible = 1 AND t.visible = 1)" unless IMPORT_DELETED_POSTS}ORDER BY p.datelineLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|skip = false@@ -160,20 +174,20 @@ class ImportScripts::MyBB < ImportScripts::Base# LIMIT 1# ").first['id']- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_mybb_post(m['raw'], m['id'])- mapped[:created_at] = Time.zone.at(m['post_time'])+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_mybb_post(m["raw"], m["id"])+ mapped[:created_at] = Time.zone.at(m["post_time"])- if m['id'] == m['first_post_id']- mapped[:category] = category_id_from_imported_category_id(m['category_id'])- mapped[:title] = CGI.unescapeHTML(m['title'])+ if m["id"] == m["first_post_id"]+ mapped[:category] = category_id_from_imported_category_id(m["category_id"])+ mapped[:title] = CGI.unescapeHTML(m["title"])else- parent = topic_lookup_from_imported_post_id(m['first_post_id'])+ parent = topic_lookup_from_imported_post_id(m["first_post_id"])if parentmapped[:topic_id] = parent[:topic_id]else- puts "Parent post #{m['first_post_id']} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"+ puts "Parent post #{m["first_post_id"]} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"skip = trueendend@@ -188,17 +202,18 @@ class ImportScripts::MyBB < ImportScripts::Baseenddef suspend_users- puts '', "banned users are not implemented"+ puts "", "banned users are not implemented"end# Discourse usernames don't allow spacesdef convert_username(username, post_id)count = 0- username.gsub!(/\s+/) { |a| count += 1; '_' }- # Warn on MyBB bug that places post text in the quote line - http://community.mybb.com/thread-180526.html- if count > 5- puts "Warning: probably incorrect quote in post #{post_id}"+ username.gsub!(/\s+/) do |a|+ count += 1+ "_"end+ # Warn on MyBB bug that places post text in the quote line - http://community.mybb.com/thread-180526.html+ puts "Warning: probably incorrect quote in post #{post_id}" if count > 5usernameend@@ -209,7 +224,7 @@ class ImportScripts::MyBB < ImportScripts::Basebeginpost = Post.find(quoted_post_id_from_imported)"post:#{post.post_number}, topic:#{post.topic_id}"- rescue+ rescue StandardErrorputs "Could not find migrated post #{quoted_post_id_from_imported} quoted by original post #{post_id} as #{quoted_post_id}"""end@@ -223,23 +238,24 @@ class ImportScripts::MyBB < ImportScripts::Bases = raw.dup# convert the quote line- s.gsub!(/\[quote='([^']+)'.*?pid='(\d+).*?\]/) {- "[quote=\"#{convert_username($1, import_id)}, " + post_id_to_post_num_and_topic($2, import_id) + '"]'- }+ s.gsub!(/\[quote='([^']+)'.*?pid='(\d+).*?\]/) do+ "[quote=\"#{convert_username($1, import_id)}, " ++ post_id_to_post_num_and_topic($2, import_id) + '"]'+ end# :) is encoded as <!-- s:) --><img src="{SMILIES_PATH}/icon_e_smile.gif" alt=":)" title="Smile" /><!-- s:) -->s.gsub!(/<!-- s(\S+) -->(?:.*)<!-- s(?:\S+) -->/, '\1')# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- s.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/, '[\2](\1)')+ s.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}, '[\2](\1)')# Many phpbb bbcode tags have a hash attached to them. Examples:# [url=https://google.com:1qh1i7ky]click here[/url:1qh1i7ky]# [quote="cybereality":b0wtlzex]Some text.[/quote:b0wtlzex]- s.gsub!(/:(?:\w{8})\]/, ']')+ s.gsub!(/:(?:\w{8})\]/, "]")# Remove mybb video tags.- s.gsub!(/(^\[video=.*?\])|(\[\/video\]$)/, '')+ s.gsub!(%r{(^\[video=.*?\])|(\[/video\]$)}, "")s = CGI.unescapeHTML(s)@@ -247,16 +263,16 @@ class ImportScripts::MyBB < ImportScripts::Base# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- s.gsub!(/\[http(s)?:\/\/(www\.)?/, '[')+ s.gsub!(%r{\[http(s)?://(www\.)?}, "[")senddef create_permalinks- puts '', 'Creating redirects...', ''+ puts "", "Creating redirects...", ""SiteSetting.permalink_normalizations = '/(\\w+)-(\\d+)[-.].*/\\1-\\2.html'- puts '', 'Users...', ''+ puts "", "Users...", ""total_users = User.countstart_time = Time.nowcount = 0@@ -264,12 +280,19 @@ class ImportScripts::MyBB < ImportScripts::Baseucf = u.custom_fieldscount += 1if ucf && ucf["import_id"] && ucf["import_username"]- Permalink.create(url: "#{BASE}/user-#{ucf['import_id']}.html", external_url: "/u/#{u.username}") rescue nil+ begin+ Permalink.create(+ url: "#{BASE}/user-#{ucf["import_id"]}.html",+ external_url: "/u/#{u.username}",+ )+ rescue StandardError+ nil+ endendprint_status(count, total_users, start_time)end- puts '', 'Categories...', ''+ puts "", "Categories...", ""total_categories = Category.countstart_time = Time.nowcount = 0@@ -277,20 +300,24 @@ class ImportScripts::MyBB < ImportScripts::Baseccf = cat.custom_fieldscount += 1next unless id = ccf["import_id"]- unless QUIET- puts ("forum-#{id}.html --> /c/#{cat.id}")+ puts ("forum-#{id}.html --> /c/#{cat.id}") unless QUIET+ begin+ Permalink.create(url: "#{BASE}/forum-#{id}.html", category_id: cat.id)+ rescue StandardError+ nilend- Permalink.create(url: "#{BASE}/forum-#{id}.html", category_id: cat.id) rescue nilprint_status(count, total_categories, start_time)end- puts '', 'Topics...', ''+ puts "", "Topics...", ""total_posts = Post.countstart_time = Time.nowcount = 0- puts '', 'Posts...', ''+ puts "", "Posts...", ""batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.pid id,p.tid topic_idFROM #{TABLE_PREFIX}posts p,@@ -300,13 +327,18 @@ class ImportScripts::MyBB < ImportScripts::BaseORDER BY p.datelineLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )break if results.size < 1results.each do |post|count += 1- if topic = topic_lookup_from_imported_post_id(post['id'])- id = post['topic_id']- Permalink.create(url: "#{BASE}/thread-#{id}.html", topic_id: topic[:topic_id]) rescue nil+ if topic = topic_lookup_from_imported_post_id(post["id"])+ id = post["topic_id"]+ begin+ Permalink.create(url: "#{BASE}/thread-#{id}.html", topic_id: topic[:topic_id])+ rescue StandardError+ nil+ endunless QUIETputs ("#{BASE}/thread-#{id}.html --> http://localhost:3000/t/#{topic[:topic_id]}")enddiff --git a/script/import_scripts/mybbru.rb b/script/import_scripts/mybbru.rbindex 5857d7b55c8..cea923831bf 100755--- a/script/import_scripts/mybbru.rb+++ b/script/import_scripts/mybbru.rb@@ -9,9 +9,8 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# If your forum has non-English usernames, don't forget to enable Unicode usernames in /admin/site_settingsclass ImportScripts::MybbRu < ImportScripts::Base-- JSON_TOPICS_FILE_PATH ||= ENV['JSON_TOPICS_FILE'] || 'mybbru_export/threads.json'- JSON_USERS_FILE_PATH ||= ENV['JSON_USERS_FILE'] || 'mybbru_export/users.json'+ JSON_TOPICS_FILE_PATH ||= ENV["JSON_TOPICS_FILE"] || "mybbru_export/threads.json"+ JSON_USERS_FILE_PATH ||= ENV["JSON_USERS_FILE"] || "mybbru_export/users.json"def initializesuper@@ -35,59 +34,49 @@ class ImportScripts::MybbRu < ImportScripts::Baseenddef clean_username(name)- name.gsub(/ /, '')+ name.gsub(/ /, "")enddef import_users- puts '', "Importing users"+ puts "", "Importing users"create_users(@imported_users) do |u|- {- id: u['id'],- username: clean_username(u['name']),- email: u['email'],- created_at: Time.now- }+ { id: u["id"], username: clean_username(u["name"]), email: u["email"], created_at: Time.now }endenddef import_categoriesputs "", "importing categories..."- categories = @imported_topics.map { |t| t['category'] }.uniq+ categories = @imported_topics.map { |t| t["category"] }.uniq- create_categories(categories) do |c|- {- id: c['id'],- name: c['name']- }- end+ create_categories(categories) { |c| { id: c["id"], name: c["name"] } }enddef import_discussionsputs "", "Importing discussions"@imported_topics.each do |t|- first_post = t['posts'][0]+ first_post = t["posts"][0]- create_posts(t['posts']) do |p|+ create_posts(t["posts"]) do |p|result = {- id: p['id'],- user_id: user_id_from_imported_user_id(p['author']['id']),+ id: p["id"],+ user_id: user_id_from_imported_user_id(p["author"]["id"]),raw: fix_post_content(p["source"]),- created_at: Time.at(p['createdAt']),- cook_method: Post.cook_methods[:regular]+ created_at: Time.at(p["createdAt"]),+ cook_method: Post.cook_methods[:regular],}- if p['id'] == first_post['id']- result[:category] = category_id_from_imported_category_id(t['category']['id'])- result[:title] = t['title']+ if p["id"] == first_post["id"]+ result[:category] = category_id_from_imported_category_id(t["category"]["id"])+ result[:title] = t["title"]else- parent = topic_lookup_from_imported_post_id(first_post['id'])+ parent = topic_lookup_from_imported_post_id(first_post["id"])if parentresult[:topic_id] = parent[:topic_id]else- puts "Parent post #{first_post['id']} doesn't exist. Skipping #{p["id"]}: #{t["title"][0..40]}"+ puts "Parent post #{first_post["id"]} doesn't exist. Skipping #{p["id"]}: #{t["title"][0..40]}"breakendend@@ -100,16 +89,15 @@ class ImportScripts::MybbRu < ImportScripts::Basedef fix_post_content(text)text.gsub(/\[code\]/, "\n[code]\n")- .gsub(/\[\/code\]/, "\n[/code]\n")+ .gsub(%r{\[/code\]}, "\n[/code]\n").gsub(/\[video\]/, "")- .gsub(/\[\/video\]/, "")+ .gsub(%r{\[/video\]}, "").gsub(/\[quote.*?\]/, "\n" + '\0' + "\n")- .gsub(/\[\/quote\]/, "\n[/quote]\n")- .gsub(/\[spoiler.*?\]/, "\n" + '\0' + "\n").gsub(/\[spoiler/, '[details')- .gsub(/\[\/spoiler\]/, "\n[/details]\n")+ .gsub(%r{\[/quote\]}, "\n[/quote]\n")+ .gsub(/\[spoiler.*?\]/, "\n" + '\0' + "\n")+ .gsub(/\[spoiler/, "[details")+ .gsub(%r{\[/spoiler\]}, "\n[/details]\n")endend-if __FILE__ == $0- ImportScripts::MybbRu.new.perform-end+ImportScripts::MybbRu.new.perform if __FILE__ == $0diff --git a/script/import_scripts/mylittleforum.rb b/script/import_scripts/mylittleforum.rbindex de82d141334..5f3fce06579 100644--- a/script/import_scripts/mylittleforum.rb+++ b/script/import_scripts/mylittleforum.rb@@ -2,7 +2,7 @@require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'+require "htmlentities"# Before running this script, paste these lines into your shell,# then use arrow keys to edit the values@@ -18,45 +18,35 @@ export BASE="forum"=endclass ImportScripts::MylittleforumSQL < ImportScripts::Base-- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "mylittleforum"- DB_PW ||= ENV['DB_PW'] || ""- DB_USER ||= ENV['DB_USER'] || "root"- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "forum_"- IMPORT_AFTER ||= ENV['IMPORT_AFTER'] || "1970-01-01"- IMAGE_BASE ||= ENV['IMAGE_BASE'] || ""- BASE ||= ENV['BASE'] || "forum/"+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "mylittleforum"+ DB_PW ||= ENV["DB_PW"] || ""+ DB_USER ||= ENV["DB_USER"] || "root"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "forum_"+ IMPORT_AFTER ||= ENV["IMPORT_AFTER"] || "1970-01-01"+ IMAGE_BASE ||= ENV["IMAGE_BASE"] || ""+ BASE ||= ENV["BASE"] || "forum/"BATCH_SIZE = 1000CONVERT_HTML = true- QUIET = nil || ENV['VERBOSE'] == "TRUE"- FORCE_HOSTNAME = nil || ENV['FORCE_HOSTNAME']+ QUIET = nil || ENV["VERBOSE"] == "TRUE"+ FORCE_HOSTNAME = nil || ENV["FORCE_HOSTNAME"]QUIET = true# Site settingsSiteSetting.disable_emails = "non-staff"- if FORCE_HOSTNAME- SiteSetting.force_hostname = FORCE_HOSTNAME- end+ SiteSetting.force_hostname = FORCE_HOSTNAME if FORCE_HOSTNAMEdef initialize-- if IMPORT_AFTER > "1970-01-01"- print_warning("Importing data after #{IMPORT_AFTER}")- end+ print_warning("Importing data after #{IMPORT_AFTER}") if IMPORT_AFTER > "1970-01-01"super@htmlentities = HTMLEntities.newbegin- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- password: DB_PW,- database: DB_NAME- )+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, password: DB_PW, database: DB_NAME)rescue Exception => e- puts '=' * 50+ puts "=" * 50puts e.messageputs <<~TEXTCannot log in to database.@@ -95,12 +85,19 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Baseenddef import_users- puts '', "creating users"+ puts "", "creating users"- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}userdata WHERE last_login > '#{IMPORT_AFTER}';").first['count']+ total_count =+ mysql_query(+ "SELECT count(*) count FROM #{TABLE_PREFIX}userdata WHERE last_login > '#{IMPORT_AFTER}';",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT user_id as UserID, user_name as username,user_real_name as Name,user_email as Email,@@ -118,31 +115,33 @@ class ImportScripts::MylittleforumSQL < ImportScripts::BaseWHERE last_login > '#{IMPORT_AFTER}'order by UserID ASCLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1- next if all_records_exist? :users, results.map { |u| u['UserID'].to_i }+ next if all_records_exist? :users, results.map { |u| u["UserID"].to_i }create_users(results, total: total_count, offset: offset) do |user|- next if user['Email'].blank?- next if @lookup.user_id_from_imported_user_id(user['UserID'])+ next if user["Email"].blank?+ next if @lookup.user_id_from_imported_user_id(user["UserID"])# username = fix_username(user['username'])- { id: user['UserID'],- email: user['Email'],- username: user['username'],- name: user['Name'],- created_at: user['DateInserted'] == nil ? 0 : Time.zone.at(user['DateInserted']),- bio_raw: user['bio_raw'],- registration_ip_address: user['InsertIPAddress'],- website: user['user_hp'],- password: user['password'],- last_seen_at: user['DateLastActive'] == nil ? 0 : Time.zone.at(user['DateLastActive']),- location: user['Location'],- admin: user['user_type'] == "admin",- moderator: user['user_type'] == "mod",+ {+ id: user["UserID"],+ email: user["Email"],+ username: user["username"],+ name: user["Name"],+ created_at: user["DateInserted"] == nil ? 0 : Time.zone.at(user["DateInserted"]),+ bio_raw: user["bio_raw"],+ registration_ip_address: user["InsertIPAddress"],+ website: user["user_hp"],+ password: user["password"],+ last_seen_at: user["DateLastActive"] == nil ? 0 : Time.zone.at(user["DateLastActive"]),+ location: user["Location"],+ admin: user["user_type"] == "admin",+ moderator: user["user_type"] == "mod",}endend@@ -151,7 +150,7 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Basedef fix_username(username)olduser = username.dupusername.gsub!(/Dr\. /, "Dr") # no &- username.gsub!(/[ +!\/,*()?]/, "_") # can't have these+ username.gsub!(%r{[ +!/,*()?]}, "_") # can't have theseusername.gsub!(/&/, "_and_") # no &username.gsub!(/@/, "_at_") # no @username.gsub!(/#/, "_hash_") # no &@@ -159,28 +158,29 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Baseusername.gsub!(/[._]+/, "_") # can't have 2 special in a rowusername.gsub!(/_+/, "_") # could result in dupes, but wtf?username.gsub!(/_$/, "") # could result in dupes, but wtf?- if olduser != username- print_warning ("#{olduser} --> #{username}")- end+ print_warning ("#{olduser} --> #{username}") if olduser != usernameusernameenddef import_categoriesputs "", "importing categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT id as CategoryID,category as Name,description as DescriptionFROM #{TABLE_PREFIX}categoriesORDER BY CategoryID ASC- ").to_a+ ",+ ).to_acreate_categories(categories) do |category|{- id: category['CategoryID'],- name: CGI.unescapeHTML(category['Name']),- description: CGI.unescapeHTML(category['Description'])+ id: category["CategoryID"],+ name: CGI.unescapeHTML(category["Name"]),+ description: CGI.unescapeHTML(category["Description"]),}endend@@ -188,13 +188,19 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Basedef import_topicsputs "", "importing topics..."- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}entries+ total_count =+ mysql_query(+ "SELECT count(*) count FROM #{TABLE_PREFIX}entriesWHERE time > '#{IMPORT_AFTER}'- AND pid = 0;").first['count']+ AND pid = 0;",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- discussions = mysql_query(- "SELECT id as DiscussionID,+ discussions =+ mysql_query(+ "SELECT id as DiscussionID,category as CategoryID,subject as Name,text as Body,@@ -206,29 +212,32 @@ class ImportScripts::MylittleforumSQL < ImportScripts::BaseAND time > '#{IMPORT_AFTER}'ORDER BY time ASCLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if discussions.size < 1- next if all_records_exist? :posts, discussions.map { |t| "discussion#" + t['DiscussionID'].to_s }+ if all_records_exist? :posts, discussions.map { |t| "discussion#" + t["DiscussionID"].to_s }+ next+ endcreate_posts(discussions, total: total_count, offset: offset) do |discussion|-- raw = clean_up(discussion['Body'])+ raw = clean_up(discussion["Body"])youtube = nil- unless discussion['youtube'].blank?- youtube = clean_youtube(discussion['youtube'])+ unless discussion["youtube"].blank?+ youtube = clean_youtube(discussion["youtube"])raw += "\n#{youtube}\n"print_warning(raw)end{- id: "discussion#" + discussion['DiscussionID'].to_s,- user_id: user_id_from_imported_user_id(discussion['InsertUserID']) || Discourse::SYSTEM_USER_ID,- title: discussion['Name'].gsub('\\"', '"'),- category: category_id_from_imported_category_id(discussion['CategoryID']),+ id: "discussion#" + discussion["DiscussionID"].to_s,+ user_id:+ user_id_from_imported_user_id(discussion["InsertUserID"]) || Discourse::SYSTEM_USER_ID,+ title: discussion["Name"].gsub('\\"', '"'),+ category: category_id_from_imported_category_id(discussion["CategoryID"]),raw: raw,- created_at: Time.zone.at(discussion['DateInserted']),+ created_at: Time.zone.at(discussion["DateInserted"]),}endend@@ -237,15 +246,20 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Basedef import_postsputs "", "importing posts..."- total_count = mysql_query(- "SELECT count(*) count+ total_count =+ mysql_query(+ "SELECT count(*) countFROM #{TABLE_PREFIX}entriesWHERE pid > 0- AND time > '#{IMPORT_AFTER}';").first['count']+ AND time > '#{IMPORT_AFTER}';",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- comments = mysql_query(- "SELECT id as CommentID,+ comments =+ mysql_query(+ "SELECT id as CommentID,tid as DiscussionID,text as Body,time as DateInserted,@@ -256,26 +270,33 @@ class ImportScripts::MylittleforumSQL < ImportScripts::BaseAND time > '#{IMPORT_AFTER}'ORDER BY time ASCLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if comments.size < 1- next if all_records_exist? :posts, comments.map { |comment| "comment#" + comment['CommentID'].to_s }+ if all_records_exist? :posts,+ comments.map { |comment| "comment#" + comment["CommentID"].to_s }+ next+ endcreate_posts(comments, total: total_count, offset: offset) do |comment|- next unless t = topic_lookup_from_imported_post_id("discussion#" + comment['DiscussionID'].to_s)- next if comment['Body'].blank?- raw = clean_up(comment['Body'])+ unless t = topic_lookup_from_imported_post_id("discussion#" + comment["DiscussionID"].to_s)+ next+ end+ next if comment["Body"].blank?+ raw = clean_up(comment["Body"])youtube = nil- unless comment['youtube'].blank?- youtube = clean_youtube(comment['youtube'])+ unless comment["youtube"].blank?+ youtube = clean_youtube(comment["youtube"])raw += "\n#{youtube}\n"end{- id: "comment#" + comment['CommentID'].to_s,- user_id: user_id_from_imported_user_id(comment['InsertUserID']) || Discourse::SYSTEM_USER_ID,+ id: "comment#" + comment["CommentID"].to_s,+ user_id:+ user_id_from_imported_user_id(comment["InsertUserID"]) || Discourse::SYSTEM_USER_ID,topic_id: t[:topic_id],raw: clean_up(raw),- created_at: Time.zone.at(comment['DateInserted'])+ created_at: Time.zone.at(comment["DateInserted"]),}endend@@ -284,20 +305,20 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Basedef clean_youtube(youtube_raw)youtube_cooked = clean_up(youtube_raw.dup.to_s)# get just src from <iframe> and put on a line by itself- re = /<iframe.+?src="(\S+?)".+?<\/iframe>/mix+ re = %r{<iframe.+?src="(\S+?)".+?</iframe>}mixyoutube_cooked.gsub!(re) { "\n#{$1}\n" }- re = /<object.+?src="(\S+?)".+?<\/object>/mix+ re = %r{<object.+?src="(\S+?)".+?</object>}mixyoutube_cooked.gsub!(re) { "\n#{$1}\n" }- youtube_cooked.gsub!(/^\/\//, "https://") # make sure it has a protocol+ youtube_cooked.gsub!(%r{^//}, "https://") # make sure it has a protocolunless /http/.match(youtube_cooked) # handle case of only youtube object numberif youtube_cooked.length < 8 || /[<>=]/.match(youtube_cooked)# probably not a youtube idyoutube_cooked = ""else- youtube_cooked = 'https://www.youtube.com/watch?v=' + youtube_cooked+ youtube_cooked = "https://www.youtube.com/watch?v=" + youtube_cookedendend- print_warning("#{'-' * 40}\nBefore: #{youtube_raw}\nAfter: #{youtube_cooked}") unless QUIET+ print_warning("#{"-" * 40}\nBefore: #{youtube_raw}\nAfter: #{youtube_cooked}") unless QUIETyoutube_cookedend@@ -313,73 +334,79 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Baseraw = raw.gsub("\\'", "'")raw = raw.gsub(/\[b\]/i, "<strong>")- raw = raw.gsub(/\[\/b\]/i, "</strong>")+ raw = raw.gsub(%r{\[/b\]}i, "</strong>")raw = raw.gsub(/\[i\]/i, "<em>")- raw = raw.gsub(/\[\/i\]/i, "</em>")+ raw = raw.gsub(%r{\[/i\]}i, "</em>")raw = raw.gsub(/\[u\]/i, "<em>")- raw = raw.gsub(/\[\/u\]/i, "</em>")+ raw = raw.gsub(%r{\[/u\]}i, "</em>")- raw = raw.gsub(/\[url\](\S+)\[\/url\]/im) { "#{$1}" }- raw = raw.gsub(/\[link\](\S+)\[\/link\]/im) { "#{$1}" }+ raw = raw.gsub(%r{\[url\](\S+)\[/url\]}im) { "#{$1}" }+ raw = raw.gsub(%r{\[link\](\S+)\[/link\]}im) { "#{$1}" }# URL & LINK with text- raw = raw.gsub(/\[url=(\S+?)\](.*?)\[\/url\]/im) { "<a href=\"#{$1}\">#{$2}</a>" }- raw = raw.gsub(/\[link=(\S+?)\](.*?)\[\/link\]/im) { "<a href=\"#{$1}\">#{$2}</a>" }+ raw = raw.gsub(%r{\[url=(\S+?)\](.*?)\[/url\]}im) { "<a href=\"#{$1}\">#{$2}</a>" }+ raw = raw.gsub(%r{\[link=(\S+?)\](.*?)\[/link\]}im) { "<a href=\"#{$1}\">#{$2}</a>" }# remote images- raw = raw.gsub(/\[img\](https?:.+?)\[\/img\]/im) { "<img src=\"#{$1}\">" }- raw = raw.gsub(/\[img=(https?.+?)\](.+?)\[\/img\]/im) { "<img src=\"#{$1}\" alt=\"#{$2}\">" }+ raw = raw.gsub(%r{\[img\](https?:.+?)\[/img\]}im) { "<img src=\"#{$1}\">" }+ raw = raw.gsub(%r{\[img=(https?.+?)\](.+?)\[/img\]}im) { "<img src=\"#{$1}\" alt=\"#{$2}\">" }# local images- raw = raw.gsub(/\[img\](.+?)\[\/img\]/i) { "<img src=\"#{IMAGE_BASE}/#{$1}\">" }- raw = raw.gsub(/\[img=(.+?)\](https?.+?)\[\/img\]/im) { "<img src=\"#{IMAGE_BASE}/#{$1}\" alt=\"#{$2}\">" }+ raw = raw.gsub(%r{\[img\](.+?)\[/img\]}i) { "<img src=\"#{IMAGE_BASE}/#{$1}\">" }+ raw =+ raw.gsub(%r{\[img=(.+?)\](https?.+?)\[/img\]}im) do+ "<img src=\"#{IMAGE_BASE}/#{$1}\" alt=\"#{$2}\">"+ end# Convert image bbcode- raw.gsub!(/\[img=(\d+),(\d+)\]([^\]]*)\[\/img\]/im, '<img width="\1" height="\2" src="\3">')+ raw.gsub!(%r{\[img=(\d+),(\d+)\]([^\]]*)\[/img\]}im, '<img width="\1" height="\2" src="\3">')# [div]s are really [quote]sraw.gsub!(/\[div\]/mix, "[quote]")- raw.gsub!(/\[\/div\]/mix, "[/quote]")+ raw.gsub!(%r{\[/div\]}mix, "[/quote]")# [postedby] -> link to @user- raw.gsub(/\[postedby\](.+?)\[b\](.+?)\[\/b\]\[\/postedby\]/i) { "#{$1}@#{$2}" }+ raw.gsub(%r{\[postedby\](.+?)\[b\](.+?)\[/b\]\[/postedby\]}i) { "#{$1}@#{$2}" }# CODE (not tested)- raw = raw.gsub(/\[code\](\S+)\[\/code\]/im) { "```\n#{$1}\n```" }- raw = raw.gsub(/\[pre\](\S+)\[\/pre\]/im) { "```\n#{$1}\n```" }+ raw = raw.gsub(%r{\[code\](\S+)\[/code\]}im) { "```\n#{$1}\n```" }+ raw = raw.gsub(%r{\[pre\](\S+)\[/pre\]}im) { "```\n#{$1}\n```" }- raw = raw.gsub(/(https:\/\/youtu\S+)/i) { "\n#{$1}\n" } #youtube links on line by themselves+ raw = raw.gsub(%r{(https://youtu\S+)}i) { "\n#{$1}\n" } #youtube links on line by themselves# no center- raw = raw.gsub(/\[\/?center\]/i, "")+ raw = raw.gsub(%r{\[/?center\]}i, "")# no size- raw = raw.gsub(/\[\/?size.*?\]/i, "")+ raw = raw.gsub(%r{\[/?size.*?\]}i, "")### FROM VANILLA:# fix whitespaces- raw = raw.gsub(/(\\r)?\\n/, "\n")- .gsub("\\t", "\t")+ raw = raw.gsub(/(\\r)?\\n/, "\n").gsub("\\t", "\t")unless CONVERT_HTML# replace all chevrons with HTML entities# NOTE: must be done# - AFTER all the "code" processing# - BEFORE the "quote" processing- raw = raw.gsub(/`([^`]+)`/im) { "`" + $1.gsub("<", "\u2603") + "`" }- .gsub("<", "<")- .gsub("\u2603", "<")-- raw = raw.gsub(/`([^`]+)`/im) { "`" + $1.gsub(">", "\u2603") + "`" }- .gsub(">", ">")- .gsub("\u2603", ">")+ raw =+ raw+ .gsub(/`([^`]+)`/im) { "`" + $1.gsub("<", "\u2603") + "`" }+ .gsub("<", "<")+ .gsub("\u2603", "<")++ raw =+ raw+ .gsub(/`([^`]+)`/im) { "`" + $1.gsub(">", "\u2603") + "`" }+ .gsub(">", ">")+ .gsub("\u2603", ">")end# Remove the color tagraw.gsub!(/\[color=[#a-z0-9]+\]/i, "")- raw.gsub!(/\[\/color\]/i, "")+ raw.gsub!(%r{\[/color\]}i, "")### END VANILLA:raw@@ -395,54 +422,72 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Baseenddef create_permalinks- puts '', 'Creating redirects...', ''+ puts "", "Creating redirects...", ""- puts '', 'Users...', ''+ puts "", "Users...", ""User.find_each do |u|ucf = u.custom_fieldsif ucf && ucf["import_id"] && ucf["import_username"]- Permalink.create(url: "#{BASE}/user-id-#{ucf['import_id']}.html", external_url: "/u/#{u.username}") rescue nil- print '.'+ begin+ Permalink.create(+ url: "#{BASE}/user-id-#{ucf["import_id"]}.html",+ external_url: "/u/#{u.username}",+ )+ rescue StandardError+ nil+ end+ print "."endend- puts '', 'Posts...', ''+ puts "", "Posts...", ""Post.find_each do |post|pcf = post.custom_fieldsif pcf && pcf["import_id"]topic = post.topic- id = pcf["import_id"].split('#').last+ id = pcf["import_id"].split("#").lastif post.post_number == 1- Permalink.create(url: "#{BASE}/forum_entry-id-#{id}.html", topic_id: topic.id) rescue nil+ begin+ Permalink.create(url: "#{BASE}/forum_entry-id-#{id}.html", topic_id: topic.id)+ rescue StandardError+ nil+ endunless QUIETprint_warning("forum_entry-id-#{id}.html --> http://localhost:3000/t/#{topic.id}")endelse- Permalink.create(url: "#{BASE}/forum_entry-id-#{id}.html", post_id: post.id) rescue nil+ begin+ Permalink.create(url: "#{BASE}/forum_entry-id-#{id}.html", post_id: post.id)+ rescue StandardError+ nil+ endunless QUIET- print_warning("forum_entry-id-#{id}.html --> http://localhost:3000/t/#{topic.id}/#{post.id}")+ print_warning(+ "forum_entry-id-#{id}.html --> http://localhost:3000/t/#{topic.id}/#{post.id}",+ )endend- print '.'+ print "."endend- puts '', 'Categories...', ''+ puts "", "Categories...", ""Category.find_each do |cat|ccf = cat.custom_fieldsnext unless id = ccf["import_id"]- unless QUIET- print_warning("forum-category-#{id}.html --> /t/#{cat.id}")+ print_warning("forum-category-#{id}.html --> /t/#{cat.id}") unless QUIET+ begin+ Permalink.create(url: "#{BASE}/forum-category-#{id}.html", category_id: cat.id)+ rescue StandardError+ nilend- Permalink.create(url: "#{BASE}/forum-category-#{id}.html", category_id: cat.id) rescue nil- print '.'+ print "."endenddef print_warning(message)$stderr.puts "#{message}"end-endImportScripts::MylittleforumSQL.new.performdiff --git a/script/import_scripts/nabble.rb b/script/import_scripts/nabble.rbindex e877e9058d4..c43efe8e5c5 100644--- a/script/import_scripts/nabble.rb+++ b/script/import_scripts/nabble.rb@@ -1,8 +1,8 @@# frozen_string_literal: truerequire File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'pg'-require_relative 'base/uploader'+require "pg"+require_relative "base/uploader"=beginif you want to create mock users for posts made by anonymous participants,@@ -40,7 +40,7 @@ class ImportScripts::Nabble < ImportScripts::BaseBATCH_SIZE = 1000- DB_NAME = "nabble"+ DB_NAME = "nabble"CATEGORY_ID = 6def initialize@@ -64,14 +64,13 @@ class ImportScripts::Nabble < ImportScripts::Basetotal_count = @client.exec("SELECT COUNT(user_id) FROM user_")[0]["count"]batches(BATCH_SIZE) do |offset|- users = @client.query(<<-SQL+ users = @client.query(<<-SQL)SELECT user_id, name, email, joinedFROM user_ORDER BY joinedLIMIT #{BATCH_SIZE}OFFSET #{offset}SQL- )break if users.ntuples() < 1@@ -83,24 +82,23 @@ class ImportScripts::Nabble < ImportScripts::Baseemail: row["email"] || fake_email,created_at: Time.zone.at(@td.decode(row["joined"])),name: row["name"],- post_create_action: proc do |user|- import_avatar(user, row["user_id"])- end+ post_create_action: proc { |user| import_avatar(user, row["user_id"]) },}endendenddef import_avatar(user, org_id)- filename = 'avatar' + org_id.to_s- path = File.join('/tmp/nab', filename)- res = @client.exec("SELECT content FROM file_avatar WHERE name='avatar100.png' AND user_id = #{org_id} LIMIT 1")+ filename = "avatar" + org_id.to_s+ path = File.join("/tmp/nab", filename)+ res =+ @client.exec(+ "SELECT content FROM file_avatar WHERE name='avatar100.png' AND user_id = #{org_id} LIMIT 1",+ )return if res.ntuples() < 1- binary = res[0]['content']- File.open(path, 'wb') { |f|- f.write(PG::Connection.unescape_bytea(binary))- }+ binary = res[0]["content"]+ File.open(path, "wb") { |f| f.write(PG::Connection.unescape_bytea(binary)) }upload = @uploader.create_upload(user.id, path, filename)@@ -113,7 +111,6 @@ class ImportScripts::Nabble < ImportScripts::BaseelseRails.logger.error("Could not persist avatar for user #{user.username}")end-enddef parse_email(msg)@@ -128,11 +125,13 @@ class ImportScripts::Nabble < ImportScripts::Basedef create_forum_topicsputs "", "creating forum topics"- app_node_id = @client.exec("SELECT node_id FROM node WHERE is_app LIMIT 1")[0]['node_id']- topic_count = @client.exec("SELECT COUNT(node_id) AS count FROM node WHERE parent_id = #{app_node_id}")[0]["count"]+ app_node_id = @client.exec("SELECT node_id FROM node WHERE is_app LIMIT 1")[0]["node_id"]+ topic_count =+ @client.exec("SELECT COUNT(node_id) AS count FROM node WHERE parent_id = #{app_node_id}")[0][+ "count"+ ]batches(BATCH_SIZE) do |offset|-topics = @client.exec <<-SQLSELECT n.node_id, n.subject, n.owner_id, n.when_created, nm.message, n.msg_fmtFROM node AS n@@ -145,43 +144,43 @@ class ImportScripts::Nabble < ImportScripts::Basebreak if topics.ntuples() < 1- next if all_records_exist? :posts, topics.map { |t| t['node_id'].to_i }+ next if all_records_exist? :posts, topics.map { |t| t["node_id"].to_i }create_posts(topics, total: topic_count, offset: offset) do |t|raw = body_from(t)next unless rawraw = process_content(raw)- raw = process_attachments(raw, t['node_id'])+ raw = process_attachments(raw, t["node_id"]){- id: t['node_id'],- title: t['subject'],+ id: t["node_id"],+ title: t["subject"],user_id: user_id_from_imported_user_id(t["owner_id"]) || Discourse::SYSTEM_USER_ID,created_at: Time.zone.at(@td.decode(t["when_created"])),category: CATEGORY_ID,raw: raw,- cook_method: Post.cook_methods[:regular]+ cook_method: Post.cook_methods[:regular],}endendenddef body_from(p)- %w(m s).include?(p['msg_fmt']) ? parse_email(p['message']) : p['message']+ %w[m s].include?(p["msg_fmt"]) ? parse_email(p["message"]) : p["message"]rescue Email::Receiver::EmptyEmailError- puts "Skipped #{p['node_id']}"+ puts "Skipped #{p["node_id"]}"enddef process_content(txt)txt.gsub! /\<quote author="(.*?)"\>/, '[quote="\1"]'- txt.gsub! /\<\/quote\>/, '[/quote]'- txt.gsub!(/\<raw\>(.*?)\<\/raw\>/m) do |match|+ txt.gsub! %r{\</quote\>}, "[/quote]"+ txt.gsub!(%r{\<raw\>(.*?)\</raw\>}m) do |match|c = Regexp.last_match[1].indent(4)- "\n#{c}\n"+ "\n#{c}\n"end# lines starting with # are comments, not headings, insert a space to prevent markdown- txt.gsub! /\n#/m, ' #'+ txt.gsub! /\n#/m, " #"# in the languagetool forum, quite a lot of XML was not marked as raw# so we treat <rule...>...</rule> and <category...>...</category> as raw@@ -202,12 +201,10 @@ class ImportScripts::Nabble < ImportScripts::Basedef process_attachments(txt, postid)txt.gsub!(/<nabble_img src="(.*?)" (.*?)>/m) do |match|basename = Regexp.last_match[1]- get_attachment_upload(basename, postid) do |upload|- @uploader.embedded_image_html(upload)- end+ get_attachment_upload(basename, postid) { |upload| @uploader.embedded_image_html(upload) }end- txt.gsub!(/<nabble_a href="(.*?)">(.*?)<\/nabble_a>/m) do |match|+ txt.gsub!(%r{<nabble_a href="(.*?)">(.*?)</nabble_a>}m) do |match|basename = Regexp.last_match[1]get_attachment_upload(basename, postid) do |upload|@uploader.attachment_html(upload, basename)@@ -217,13 +214,12 @@ class ImportScripts::Nabble < ImportScripts::Baseenddef get_attachment_upload(basename, postid)- contents = @client.exec("SELECT content FROM file_node WHERE name='#{basename}' AND node_id = #{postid}")+ contents =+ @client.exec("SELECT content FROM file_node WHERE name='#{basename}' AND node_id = #{postid}")if contents.any?- binary = contents[0]['content']- fn = File.join('/tmp/nab', basename)- File.open(fn, 'wb') { |f|- f.write(PG::Connection.unescape_bytea(binary))- }+ binary = contents[0]["content"]+ fn = File.join("/tmp/nab", basename)+ File.open(fn, "wb") { |f| f.write(PG::Connection.unescape_bytea(binary)) }yield @uploader.create_upload(0, fn, basename)endend@@ -231,8 +227,11 @@ class ImportScripts::Nabble < ImportScripts::Basedef import_repliesputs "", "creating topic replies"- app_node_id = @client.exec("SELECT node_id FROM node WHERE is_app LIMIT 1")[0]['node_id']- post_count = @client.exec("SELECT COUNT(node_id) AS count FROM node WHERE parent_id != #{app_node_id}")[0]["count"]+ app_node_id = @client.exec("SELECT node_id FROM node WHERE is_app LIMIT 1")[0]["node_id"]+ post_count =+ @client.exec("SELECT COUNT(node_id) AS count FROM node WHERE parent_id != #{app_node_id}")[0][+ "count"+ ]topic_ids = {}@@ -249,11 +248,11 @@ class ImportScripts::Nabble < ImportScripts::Basebreak if posts.ntuples() < 1- next if all_records_exist? :posts, posts.map { |p| p['node_id'].to_i }+ next if all_records_exist? :posts, posts.map { |p| p["node_id"].to_i }create_posts(posts, total: post_count, offset: offset) do |p|- parent_id = p['parent_id']- id = p['node_id']+ parent_id = p["parent_id"]+ id = p["node_id"]topic_id = topic_ids[parent_id]unless topic_id@@ -268,19 +267,21 @@ class ImportScripts::Nabble < ImportScripts::Basenext unless rawraw = process_content(raw)raw = process_attachments(raw, id)- { id: id,+ {+ id: id,topic_id: topic_id,- user_id: user_id_from_imported_user_id(p['owner_id']) || Discourse::SYSTEM_USER_ID,+ user_id: user_id_from_imported_user_id(p["owner_id"]) || Discourse::SYSTEM_USER_ID,created_at: Time.zone.at(@td.decode(p["when_created"])),raw: raw,- cook_method: Post.cook_methods[:regular] }+ cook_method: Post.cook_methods[:regular],+ }endendendendclass String- def indent(count, char = ' ')+ def indent(count, char = " ")gsub(/([^\n]*)(\n|$)/) do |match|last_iteration = ($1 == "" && $2 == "")line = +""diff --git a/script/import_scripts/ning.rb b/script/import_scripts/ning.rbindex 30612ec9691..3af9b080d1b 100644--- a/script/import_scripts/ning.rb+++ b/script/import_scripts/ning.rb@@ -5,28 +5,28 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Edit the constants and initialize method for your import data.class ImportScripts::Ning < ImportScripts::Base-JSON_FILES_DIR = "/Users/techapj/Downloads/ben/ADEM"- ATTACHMENT_PREFIXES = ["discussions", "pages", "blogs", "members", "photos"]- EXTRA_AUTHORIZED_EXTENSIONS = ["bmp", "ico", "txt", "pdf", "gif", "jpg", "jpeg", "html"]+ ATTACHMENT_PREFIXES = %w[discussions pages blogs members photos]+ EXTRA_AUTHORIZED_EXTENSIONS = %w[bmp ico txt pdf gif jpg jpeg html]def initializesuper@system_user = Discourse.system_user- @users_json = load_ning_json("ning-members-local.json")+ @users_json = load_ning_json("ning-members-local.json")@discussions_json = load_ning_json("ning-discussions-local.json")# An example of a custom category from Ning:@blogs_json = load_ning_json("ning-blogs-local.json")- @photos_json = load_ning_json("ning-photos-local.json")- @pages_json = load_ning_json("ning-pages-local.json")+ @photos_json = load_ning_json("ning-photos-local.json")+ @pages_json = load_ning_json("ning-pages-local.json")- SiteSetting.max_image_size_kb = 10240- SiteSetting.max_attachment_size_kb = 10240- SiteSetting.authorized_extensions = (SiteSetting.authorized_extensions.split("|") + EXTRA_AUTHORIZED_EXTENSIONS).uniq.join("|")+ SiteSetting.max_image_size_kb = 10_240+ SiteSetting.max_attachment_size_kb = 10_240+ SiteSetting.authorized_extensions =+ (SiteSetting.authorized_extensions.split("|") + EXTRA_AUTHORIZED_EXTENSIONS).uniq.join("|")# Example of importing a custom profile field:# @interests_field = UserField.find_by_name("My interests")@@ -60,23 +60,23 @@ class ImportScripts::Ning < ImportScripts::Baseenddef repair_json(arg)- arg.gsub!(/^\(/, "") # content of file is surround by ( )+ arg.gsub!(/^\(/, "") # content of file is surround by ( )arg.gsub!(/\)$/, "")- arg.gsub!(/\]\]$/, "]") # there can be an extra ] at the end+ arg.gsub!(/\]\]$/, "]") # there can be an extra ] at the endarg.gsub!(/\}\{/, "},{") # missing commas sometimes!- arg.gsub!("}]{", "},{") # surprise square brackets- arg.gsub!("}[{", "},{") # :troll:+ arg.gsub!("}]{", "},{") # surprise square brackets+ arg.gsub!("}[{", "},{") # :troll:argenddef import_users- puts '', "Importing users"+ puts "", "Importing users"- staff_levels = ["admin", "moderator", "owner"]+ staff_levels = %w[admin moderator owner]create_users(@users_json) do |u|{@@ -88,57 +88,58 @@ class ImportScripts::Ning < ImportScripts::Baselocation: "#{u["location"]} #{u["country"]}",avatar_url: u["profilePhoto"],bio_raw: u["profileQuestions"].is_a?(Hash) ? u["profileQuestions"]["About Me"] : nil,- post_create_action: proc do |newuser|- # if u["profileQuestions"].is_a?(Hash)- # newuser.custom_fields = {"user_field_#{@interests_field.id}" => u["profileQuestions"]["My interests"]}- # end-- if staff_levels.include?(u["level"].downcase)- if u["level"].downcase == "admin" || u["level"].downcase == "owner"- newuser.admin = true- else- newuser.moderator = true+ post_create_action:+ proc do |newuser|+ # if u["profileQuestions"].is_a?(Hash)+ # newuser.custom_fields = {"user_field_#{@interests_field.id}" => u["profileQuestions"]["My interests"]}+ # end++ if staff_levels.include?(u["level"].downcase)+ if u["level"].downcase == "admin" || u["level"].downcase == "owner"+ newuser.admin = true+ else+ newuser.moderator = true+ endend- end- # states: ["active", "suspended", "left", "pending"]- if u["state"] == "active" && newuser.approved_at.nil?- newuser.approved = true- newuser.approved_by_id = @system_user.id- newuser.approved_at = newuser.created_at- end+ # states: ["active", "suspended", "left", "pending"]+ if u["state"] == "active" && newuser.approved_at.nil?+ newuser.approved = true+ newuser.approved_by_id = @system_user.id+ newuser.approved_at = newuser.created_at+ end- newuser.save-- if u["profilePhoto"] && newuser.user_avatar.try(:custom_upload_id).nil?- photo_path = file_full_path(u["profilePhoto"])- if File.exist?(photo_path)- begin- upload = create_upload(newuser.id, photo_path, File.basename(photo_path))- if upload.persisted?- newuser.import_mode = false- newuser.create_user_avatar- newuser.import_mode = true- newuser.user_avatar.update(custom_upload_id: upload.id)- newuser.update(uploaded_avatar_id: upload.id)- else- puts "Error: Upload did not persist for #{photo_path}!"+ newuser.save++ if u["profilePhoto"] && newuser.user_avatar.try(:custom_upload_id).nil?+ photo_path = file_full_path(u["profilePhoto"])+ if File.exist?(photo_path)+ begin+ upload = create_upload(newuser.id, photo_path, File.basename(photo_path))+ if upload.persisted?+ newuser.import_mode = false+ newuser.create_user_avatar+ newuser.import_mode = true+ newuser.user_avatar.update(custom_upload_id: upload.id)+ newuser.update(uploaded_avatar_id: upload.id)+ else+ puts "Error: Upload did not persist for #{photo_path}!"+ end+ rescue SystemCallError => err+ puts "Could not import avatar #{photo_path}: #{err.message}"end- rescue SystemCallError => err- puts "Could not import avatar #{photo_path}: #{err.message}"+ else+ puts "avatar file not found at #{photo_path}"end- else- puts "avatar file not found at #{photo_path}"end- end- end+ end,}endEmailToken.delete_allenddef suspend_users- puts '', "Updating suspended users"+ puts "", "Updating suspended users"count = 0suspended = 0@@ -151,7 +152,10 @@ class ImportScripts::Ning < ImportScripts::Baseuser.suspended_till = 200.years.from_nowif user.save- StaffActionLogger.new(@system_user).log_user_suspend(user, "Import data indicates account is suspended.")+ StaffActionLogger.new(@system_user).log_user_suspend(+ user,+ "Import data indicates account is suspended.",+ )suspended += 1elseputs "Failed to suspend user #{user.username}. #{user.errors.try(:full_messages).try(:inspect)}"@@ -168,13 +172,15 @@ class ImportScripts::Ning < ImportScripts::Basedef import_categoriesputs "", "Importing categories"- create_categories((["Blog", "Pages", "Photos"] + @discussions_json.map { |d| d["category"] }).uniq.compact) do |name|+ create_categories(+ (%w[Blog Pages Photos] + @discussions_json.map { |d| d["category"] }).uniq.compact,+ ) do |name|if name.downcase == "uncategorized"nilelse{id: name, # ning has no id for categories, so use the name- name: name+ name: name,}endend@@ -220,9 +226,7 @@ class ImportScripts::Ning < ImportScripts::Baseunless topic["category"].nil? || topic["category"].downcase == "uncategorized"mapped[:category] = category_id_from_imported_category_id(topic["category"])end- if topic["category"].nil? && default_category- mapped[:category] = default_category- end+ mapped[:category] = default_category if topic["category"].nil? && default_categorymapped[:title] = CGI.unescapeHTML(topic["title"])mapped[:raw] = process_ning_post_body(topic["description"])@@ -230,13 +234,9 @@ class ImportScripts::Ning < ImportScripts::Basemapped[:raw] = add_file_attachments(mapped[:raw], topic["fileAttachments"])end- if topic["photoUrl"]- mapped[:raw] = add_photo(mapped[:raw], topic["photoUrl"])- end+ mapped[:raw] = add_photo(mapped[:raw], topic["photoUrl"]) if topic["photoUrl"]- if topic["embedCode"]- mapped[:raw] = add_video(mapped[:raw], topic["embedCode"])- end+ mapped[:raw] = add_video(mapped[:raw], topic["embedCode"]) if topic["embedCode"]parent_post = create_post(mapped, mapped[:id])unless parent_post.is_a?(Post)@@ -247,23 +247,24 @@ class ImportScripts::Ning < ImportScripts::Baseif topic["comments"].present?topic["comments"].reverse.each do |post|-if post_id_from_imported_post_id(post["id"])next # already imported this postendraw = process_ning_post_body(post["description"])- if post["fileAttachments"]- raw = add_file_attachments(raw, post["fileAttachments"])- end-- new_post = create_post({- id: post["id"],- topic_id: parent_post.topic_id,- user_id: user_id_from_imported_user_id(post["contributorName"]) || -1,- raw: raw,- created_at: Time.zone.parse(post["createdDate"])- }, post["id"])+ raw = add_file_attachments(raw, post["fileAttachments"]) if post["fileAttachments"]++ new_post =+ create_post(+ {+ id: post["id"],+ topic_id: parent_post.topic_id,+ user_id: user_id_from_imported_user_id(post["contributorName"]) || -1,+ raw: raw,+ created_at: Time.zone.parse(post["createdDate"]),+ },+ post["id"],+ )if new_post.is_a?(Post)posts += 1@@ -288,11 +289,17 @@ class ImportScripts::Ning < ImportScripts::Baseenddef attachment_regex- @_attachment_regex ||= Regexp.new(%Q[<a (?:[^>]*)href="(?:#{ATTACHMENT_PREFIXES.join('|')})\/(?:[^"]+)"(?:[^>]*)><img (?:[^>]*)src="([^"]+)"(?:[^>]*)><\/a>])+ @_attachment_regex ||=+ Regexp.new(+ %Q[<a (?:[^>]*)href="(?:#{ATTACHMENT_PREFIXES.join("|")})\/(?:[^"]+)"(?:[^>]*)><img (?:[^>]*)src="([^"]+)"(?:[^>]*)><\/a>],+ )enddef youtube_iframe_regex- @_youtube_iframe_regex ||= Regexp.new(%Q[<p><iframe(?:[^>]*)src="\/\/www.youtube.com\/embed\/([^"]+)"(?:[^>]*)><\/iframe>(?:[^<]*)<\/p>])+ @_youtube_iframe_regex ||=+ Regexp.new(+ %Q[<p><iframe(?:[^>]*)src="\/\/www.youtube.com\/embed\/([^"]+)"(?:[^>]*)><\/iframe>(?:[^<]*)<\/p>],+ )enddef process_ning_post_body(arg)@@ -382,15 +389,16 @@ class ImportScripts::Ning < ImportScripts::Basedef add_video(arg, embed_code)raw = arg- youtube_regex = Regexp.new(%Q[<iframe(?:[^>]*)src="http:\/\/www.youtube.com\/embed\/([^"]+)"(?:[^>]*)><\/iframe>])+ youtube_regex =+ Regexp.new(+ %Q[<iframe(?:[^>]*)src="http:\/\/www.youtube.com\/embed\/([^"]+)"(?:[^>]*)><\/iframe>],+ )raw.gsub!(youtube_regex) do |s|matches = youtube_regex.match(s)video_id = matches[1].split("?").first- if video_id- raw += "\n\nhttps://www.youtube.com/watch?v=#{video_id}\n"- end+ raw += "\n\nhttps://www.youtube.com/watch?v=#{video_id}\n" if video_idendraw += "\n" + embed_code + "\n"@@ -398,6 +406,4 @@ class ImportScripts::Ning < ImportScripts::Baseendend-if __FILE__ == $0- ImportScripts::Ning.new.perform-end+ImportScripts::Ning.new.perform if __FILE__ == $0diff --git a/script/import_scripts/nodebb/mongo.rb b/script/import_scripts/nodebb/mongo.rbindex 134704b2b2a..696aec43936 100644--- a/script/import_scripts/nodebb/mongo.rb+++ b/script/import_scripts/nodebb/mongo.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require 'mongo'+require "mongo"module NodeBBclass Mongo@@ -43,8 +43,8 @@ module NodeBBuser["joindate"] = timestamp_to_date(user["joindate"])user["lastonline"] = timestamp_to_date(user["lastonline"])- user['banned'] = user['banned'].to_s- user['uid'] = user['uid'].to_s+ user["banned"] = user["banned"].to_s+ user["uid"] = user["uid"].to_suserend@@ -56,17 +56,17 @@ module NodeBBcategory_keys.each do |category_key|category = mongo.find(_key: "category:#{category_key}").first- category['parentCid'] = category['parentCid'].to_s- category['disabled'] = category['disabled'].to_s- category['cid'] = category['cid'].to_s+ category["parentCid"] = category["parentCid"].to_s+ category["disabled"] = category["disabled"].to_s+ category["cid"] = category["cid"].to_s- categories[category['cid']] = category+ categories[category["cid"]] = categoryendendenddef topics(offset = 0, page_size = 2000)- topic_keys = mongo.find(_key: 'topics:tid').skip(offset).limit(page_size).pluck(:value)+ topic_keys = mongo.find(_key: "topics:tid").skip(offset).limit(page_size).pluck(:value)topic_keys.map { |topic_key| topic(topic_key) }end@@ -86,11 +86,11 @@ module NodeBBenddef topic_count- mongo.find(_key: 'topics:tid').count+ mongo.find(_key: "topics:tid").countenddef posts(offset = 0, page_size = 2000)- post_keys = mongo.find(_key: 'posts:pid').skip(offset).limit(page_size).pluck(:value)+ post_keys = mongo.find(_key: "posts:pid").skip(offset).limit(page_size).pluck(:value)post_keys.map { |post_key| post(post_key) }end@@ -111,7 +111,7 @@ module NodeBBenddef post_count- mongo.find(_key: 'posts:pid').count+ mongo.find(_key: "posts:pid").countendprivatediff --git a/script/import_scripts/nodebb/nodebb.rb b/script/import_scripts/nodebb/nodebb.rbindex b29f5ee1c6c..df575f78d37 100644--- a/script/import_scripts/nodebb/nodebb.rb+++ b/script/import_scripts/nodebb/nodebb.rb@@ -1,13 +1,13 @@# frozen_string_literal: true-require_relative '../base'-require_relative './redis'-require_relative './mongo'+require_relative "../base"+require_relative "./redis"+require_relative "./mongo"class ImportScripts::NodeBB < ImportScripts::Base# CHANGE THESE BEFORE RUNNING THE IMPORTER# ATTACHMENT_DIR needs to be absolute, not relative path- ATTACHMENT_DIR = '/Users/orlando/www/orlando/NodeBB/public/uploads'+ ATTACHMENT_DIR = "/Users/orlando/www/orlando/NodeBB/public/uploads"BATCH_SIZE = 2000def initialize@@ -17,17 +17,13 @@ class ImportScripts::NodeBB < ImportScripts::Base# @client = adapter.new('mongodb://127.0.0.1:27017/nodebb')adapter = NodeBB::Redis- @client = adapter.new(- host: "localhost",- port: "6379",- db: 14- )+ @client = adapter.new(host: "localhost", port: "6379", db: 14)load_merged_postsenddef load_merged_posts- puts 'loading merged posts with topics...'+ puts "loading merged posts with topics..."# we keep here the posts that were merged# as topics@@ -35,13 +31,16 @@ class ImportScripts::NodeBB < ImportScripts::Base# { post_id: discourse_post_id }@merged_posts_map = {}- PostCustomField.where(name: 'import_merged_post_id').pluck(:post_id, :value).each do |post_id, import_id|- post = Post.find(post_id)- topic_id = post.topic_id- nodebb_post_id = post.custom_fields['import_merged_post_id']+ PostCustomField+ .where(name: "import_merged_post_id")+ .pluck(:post_id, :value)+ .each do |post_id, import_id|+ post = Post.find(post_id)+ topic_id = post.topic_id+ nodebb_post_id = post.custom_fields["import_merged_post_id"]- @merged_posts_map[nodebb_post_id] = topic_id- end+ @merged_posts_map[nodebb_post_id] = topic_id+ endenddef execute@@ -56,19 +55,14 @@ class ImportScripts::NodeBB < ImportScripts::Baseenddef import_groups- puts '', 'importing groups'+ puts "", "importing groups"groups = @client.groupstotal_count = groups.countprogress_count = 0start_time = Time.now- create_groups(groups) do |group|- {- id: group["name"],- name: group["slug"]- }- end+ create_groups(groups) { |group| { id: group["name"], name: group["slug"] } }enddef import_categories@@ -107,15 +101,18 @@ class ImportScripts::NodeBB < ImportScripts::Basename: category["name"],position: category["order"],description: category["description"],- parent_category_id: category_id_from_imported_category_id(category["parentCid"])+ parent_category_id: category_id_from_imported_category_id(category["parentCid"]),}endcategories.each do |source_category|- cid = category_id_from_imported_category_id(source_category['cid'])- Permalink.create(url: "/category/#{source_category['slug']}", category_id: cid) rescue nil+ cid = category_id_from_imported_category_id(source_category["cid"])+ begin+ Permalink.create(url: "/category/#{source_category["slug"]}", category_id: cid)+ rescue StandardError+ nil+ endend-enddef import_users@@ -158,12 +155,13 @@ class ImportScripts::NodeBB < ImportScripts::Basebio_raw: user["aboutme"],active: true,custom_fields: {- import_pass: user["password"]+ import_pass: user["password"],},- post_create_action: proc do |u|- import_profile_picture(user, u)- import_profile_background(user, u)- end+ post_create_action:+ proc do |u|+ import_profile_picture(user, u)+ import_profile_background(user, u)+ end,}endend@@ -204,7 +202,7 @@ class ImportScripts::NodeBB < ImportScripts::Baseend# write tmp file- file = Tempfile.new(filename, encoding: 'ascii-8bit')+ file = Tempfile.new(filename, encoding: "ascii-8bit")file.write string_io.readfile.rewind@@ -230,9 +228,21 @@ class ImportScripts::NodeBB < ImportScripts::Baseimported_user.user_avatar.update(custom_upload_id: upload.id)imported_user.update(uploaded_avatar_id: upload.id)ensure- string_io.close rescue nil- file.close rescue nil- file.unlind rescue nil+ begin+ string_io.close+ rescue StandardError+ nil+ end+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlind+ rescue StandardError+ nil+ endenddef import_profile_background(old_user, imported_user)@@ -264,7 +274,7 @@ class ImportScripts::NodeBB < ImportScripts::Baseend# write tmp file- file = Tempfile.new(filename, encoding: 'ascii-8bit')+ file = Tempfile.new(filename, encoding: "ascii-8bit")file.write string_io.readfile.rewind@@ -288,9 +298,21 @@ class ImportScripts::NodeBB < ImportScripts::Baseimported_user.user_profile.upload_profile_background(upload)ensure- string_io.close rescue nil- file.close rescue nil- file.unlink rescue nil+ begin+ string_io.close+ rescue StandardError+ nil+ end+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlink+ rescue StandardError+ nil+ endenddef add_users_to_groups@@ -305,7 +327,7 @@ class ImportScripts::NodeBB < ImportScripts::Basedgroup = find_group_by_import_id(group["name"])# do thing if we migrated this group already- next if dgroup.custom_fields['import_users_added']+ next if dgroup.custom_fields["import_users_added"]group_member_ids = group["member_ids"].map { |uid| user_id_from_imported_user_id(uid) }group_owner_ids = group["owner_ids"].map { |uid| user_id_from_imported_user_id(uid) }@@ -320,7 +342,7 @@ class ImportScripts::NodeBB < ImportScripts::Baseowners = User.find(group_owner_ids)owners.each { |owner| dgroup.add_owner(owner) }- dgroup.custom_fields['import_users_added'] = true+ dgroup.custom_fields["import_users_added"] = truedgroup.saveprogress_count += 1@@ -357,12 +379,13 @@ class ImportScripts::NodeBB < ImportScripts::Basecreated_at: topic["timestamp"],views: topic["viewcount"],closed: topic["locked"] == "1",- post_create_action: proc do |p|- # keep track of this to use in import_posts- p.custom_fields["import_merged_post_id"] = topic["mainPid"]- p.save- @merged_posts_map[topic["mainPid"]] = p.id- end+ post_create_action:+ proc do |p|+ # keep track of this to use in import_posts+ p.custom_fields["import_merged_post_id"] = topic["mainPid"]+ p.save+ @merged_posts_map[topic["mainPid"]] = p.id+ end,}data[:pinned_at] = data[:created_at] if topic["pinned"] == "1"@@ -372,7 +395,11 @@ class ImportScripts::NodeBB < ImportScripts::Basetopics.each do |import_topic|topic = topic_lookup_from_imported_post_id("t#{import_topic["tid"]}")- Permalink.create(url: "/topic/#{import_topic['slug']}", topic_id: topic[:topic_id]) rescue nil+ begin+ Permalink.create(url: "/topic/#{import_topic["slug"]}", topic_id: topic[:topic_id])+ rescue StandardError+ nil+ endendendend@@ -411,21 +438,23 @@ class ImportScripts::NodeBB < ImportScripts::Basetopic_id: topic[:topic_id],raw: raw,created_at: post["timestamp"],- post_create_action: proc do |p|- post["upvoted_by"].each do |upvoter_id|- user = User.new- user.id = user_id_from_imported_user_id(upvoter_id) || Discourse::SYSTEM_USER_ID- PostActionCreator.like(user, p)- end- end+ post_create_action:+ proc do |p|+ post["upvoted_by"].each do |upvoter_id|+ user = User.new+ user.id = user_id_from_imported_user_id(upvoter_id) || Discourse::SYSTEM_USER_ID+ PostActionCreator.like(user, p)+ end+ end,}- if post['toPid']+ if post["toPid"]# Look reply to topic- parent_id = topic_lookup_from_imported_post_id("t#{post['toPid']}").try(:[], :post_number)+ parent_id = topic_lookup_from_imported_post_id("t#{post["toPid"]}").try(:[], :post_number)# Look reply post if topic is missing- parent_id ||= topic_lookup_from_imported_post_id("p#{post['toPid']}").try(:[], :post_number)+ parent_id ||=+ topic_lookup_from_imported_post_id("p#{post["toPid"]}").try(:[], :post_number)if parent_iddata[:reply_to_post_number] = parent_id@@ -448,12 +477,12 @@ class ImportScripts::NodeBB < ImportScripts::BasePost.find_each do |post|begin- next if post.custom_fields['import_post_processing']+ next if post.custom_fields["import_post_processing"]new_raw = postprocess_post(post)if new_raw != post.rawpost.raw = new_raw- post.custom_fields['import_post_processing'] = true+ post.custom_fields["import_post_processing"] = truepost.saveendensure@@ -463,7 +492,7 @@ class ImportScripts::NodeBB < ImportScripts::Baseenddef import_attachments- puts '', 'importing attachments...'+ puts "", "importing attachments..."current = 0max = Post.count@@ -474,7 +503,7 @@ class ImportScripts::NodeBB < ImportScripts::Baseprint_status(current, max, start_time)new_raw = post.raw.dup- new_raw.gsub!(/\[(.*)\]\((\/assets\/uploads\/files\/.*)\)/) do+ new_raw.gsub!(%r{\[(.*)\]\((/assets/uploads/files/.*)\)}) doimage_md = Regexp.last_match[0]text, filepath = $1, $2filepath = filepath.gsub("/assets/uploads", ATTACHMENT_DIR)@@ -493,7 +522,12 @@ class ImportScripts::NodeBB < ImportScripts::Baseendif new_raw != post.raw- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, bypass_bump: true, edit_reason: 'Import attachments from NodeBB')+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ bypass_bump: true,+ edit_reason: "Import attachments from NodeBB",+ )endendend@@ -502,28 +536,30 @@ class ImportScripts::NodeBB < ImportScripts::Baseraw = post.raw# [link to post](/post/:id)- raw = raw.gsub(/\[(.*)\]\(\/post\/(\d+).*\)/) do- text, post_id = $1, $2-- if topic_lookup = topic_lookup_from_imported_post_id("p#{post_id}")- url = topic_lookup[:url]- "[#{text}](#{url})"- else- "/404"+ raw =+ raw.gsub(%r{\[(.*)\]\(/post/(\d+).*\)}) do+ text, post_id = $1, $2++ if topic_lookup = topic_lookup_from_imported_post_id("p#{post_id}")+ url = topic_lookup[:url]+ "[#{text}](#{url})"+ else+ "/404"+ endend- end# [link to topic](/topic/:id)- raw = raw.gsub(/\[(.*)\]\(\/topic\/(\d+).*\)/) do- text, topic_id = $1, $2-- if topic_lookup = topic_lookup_from_imported_post_id("t#{topic_id}")- url = topic_lookup[:url]- "[#{text}](#{url})"- else- "/404"+ raw =+ raw.gsub(%r{\[(.*)\]\(/topic/(\d+).*\)}) do+ text, topic_id = $1, $2++ if topic_lookup = topic_lookup_from_imported_post_id("t#{topic_id}")+ url = topic_lookup[:url]+ "[#{text}](#{url})"+ else+ "/404"+ endend- endrawenddiff --git a/script/import_scripts/nodebb/redis.rb b/script/import_scripts/nodebb/redis.rbindex f8877c5e15f..3d1f08a3f37 100644--- a/script/import_scripts/nodebb/redis.rb+++ b/script/import_scripts/nodebb/redis.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require 'redis'+require "redis"module NodeBBclass Redis@@ -11,7 +11,7 @@ module NodeBBenddef groups- group_keys = redis.zrange('groups:visible:createtime', 0, -1)+ group_keys = redis.zrange("groups:visible:createtime", 0, -1)group_keys.map { |group_key| group(group_key) }end@@ -26,7 +26,7 @@ module NodeBBenddef users- user_keys = redis.zrange('users:joindate', 0, -1)+ user_keys = redis.zrange("users:joindate", 0, -1)user_keys.map { |user_key| user(user_key) }end@@ -41,13 +41,13 @@ module NodeBBenddef categories- category_keys = redis.zrange('categories:cid', 0, -1)+ category_keys = redis.zrange("categories:cid", 0, -1){}.tap do |categories|category_keys.each do |category_key|category = redis.hgetall("category:#{category_key}")- categories[category['cid']] = category+ categories[category["cid"]] = categoryendendend@@ -59,7 +59,7 @@ module NodeBBfrom = offsetto = page_size + offset- topic_keys = redis.zrange('topics:tid', from, to)+ topic_keys = redis.zrange("topics:tid", from, to)topic_keys.map { |topic_key| topic(topic_key) }end@@ -75,7 +75,7 @@ module NodeBBenddef topic_count- redis.zcard('topics:tid')+ redis.zcard("topics:tid")enddef posts(offset = 0, page_size = 2000)@@ -85,7 +85,7 @@ module NodeBBfrom = offsetto = page_size + offset- post_keys = redis.zrange('posts:pid', from, to)+ post_keys = redis.zrange("posts:pid", from, to)post_keys.map { |post_key| post(post_key) }end@@ -99,7 +99,7 @@ module NodeBBenddef post_count- redis.zcard('posts:pid')+ redis.zcard("posts:pid")endprivatediff --git a/script/import_scripts/phorum.rb b/script/import_scripts/phorum.rbindex dc2639933ec..f03db50ea42 100644--- a/script/import_scripts/phorum.rb+++ b/script/import_scripts/phorum.rb@@ -5,7 +5,6 @@ require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Phorum < ImportScripts::Base-PHORUM_DB = "piwik"TABLE_PREFIX = "pw_"BATCH_SIZE = 1000@@ -13,12 +12,13 @@ class ImportScripts::Phorum < ImportScripts::Basedef initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- password: "pa$$word",- database: PHORUM_DB- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ password: "pa$$word",+ database: PHORUM_DB,+ )enddef execute@@ -29,30 +29,34 @@ class ImportScripts::Phorum < ImportScripts::Baseenddef import_users- puts '', "creating users"+ puts "", "creating users"- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}users;").first['count']+ total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}users;").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT user_id id, username, TRIM(email) AS email, username name, date_added created_at,+ results =+ mysql_query(+ "SELECT user_id id, username, TRIM(email) AS email, username name, date_added created_at,date_last_active last_seen_at, adminFROM #{TABLE_PREFIX}usersWHERE #{TABLE_PREFIX}users.active = 1LIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1create_users(results, total: total_count, offset: offset) do |user|- next if user['username'].blank?- { id: user['id'],- email: user['email'],- username: user['username'],- name: user['name'],- created_at: Time.zone.at(user['created_at']),- last_seen_at: Time.zone.at(user['last_seen_at']),- admin: user['admin'] == 1 }+ next if user["username"].blank?+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ name: user["name"],+ created_at: Time.zone.at(user["created_at"]),+ last_seen_at: Time.zone.at(user["last_seen_at"]),+ admin: user["admin"] == 1,+ }endendend@@ -60,19 +64,18 @@ class ImportScripts::Phorum < ImportScripts::Basedef import_categoriesputs "", "importing categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT forum_id id, name, description, activeFROM #{TABLE_PREFIX}forumsORDER BY forum_id ASC- ").to_a+ ",+ ).to_acreate_categories(categories) do |category|- next if category['active'] == 0- {- id: category['id'],- name: category["name"],- description: category["description"]- }+ next if category["active"] == 0+ { id: category["id"], name: category["name"], description: category["description"] }end# uncomment below lines to create permalink@@ -87,7 +90,9 @@ class ImportScripts::Phorum < ImportScripts::Basetotal_count = mysql_query("SELECT count(*) count from #{TABLE_PREFIX}messages").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT m.message_id id,m.parent_id,m.forum_id category_id,@@ -100,7 +105,8 @@ class ImportScripts::Phorum < ImportScripts::BaseORDER BY m.datestampLIMIT #{BATCH_SIZE}OFFSET #{offset};- ").to_a+ ",+ ).to_abreak if results.size < 1@@ -108,20 +114,20 @@ class ImportScripts::Phorum < ImportScripts::Baseskip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_raw_post(m['raw'], m['id'])- mapped[:created_at] = Time.zone.at(m['created_at'])+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_raw_post(m["raw"], m["id"])+ mapped[:created_at] = Time.zone.at(m["created_at"])- if m['parent_id'] == 0- mapped[:category] = category_id_from_imported_category_id(m['category_id'].to_i)- mapped[:title] = CGI.unescapeHTML(m['title'])+ if m["parent_id"] == 0+ mapped[:category] = category_id_from_imported_category_id(m["category_id"].to_i)+ mapped[:title] = CGI.unescapeHTML(m["title"])else- parent = topic_lookup_from_imported_post_id(m['parent_id'])+ parent = topic_lookup_from_imported_post_id(m["parent_id"])if parentmapped[:topic_id] = parent[:topic_id]else- puts "Parent post #{m['parent_id']} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"+ puts "Parent post #{m["parent_id"]} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"skip = trueendend@@ -137,25 +143,24 @@ class ImportScripts::Phorum < ImportScripts::Base# end# endend-enddef process_raw_post(raw, import_id)s = raw.dup# :) is encoded as <!-- s:) --><img src="{SMILIES_PATH}/icon_e_smile.gif" alt=":)" title="Smile" /><!-- s:) -->- s.gsub!(/<!-- s(\S+) --><img (?:[^>]+) \/><!-- s(?:\S+) -->/, '\1')+ s.gsub!(%r{<!-- s(\S+) --><img (?:[^>]+) /><!-- s(?:\S+) -->}, '\1')# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- s.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/, '[\2](\1)')+ s.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}, '[\2](\1)')# Many phpbb bbcode tags have a hash attached to them. Examples:# [url=https://google.com:1qh1i7ky]click here[/url:1qh1i7ky]# [quote="cybereality":b0wtlzex]Some text.[/quote:b0wtlzex]- s.gsub!(/:(?:\w{8})\]/, ']')+ s.gsub!(/:(?:\w{8})\]/, "]")# Remove mybb video tags.- s.gsub!(/(^\[video=.*?\])|(\[\/video\]$)/, '')+ s.gsub!(%r{(^\[video=.*?\])|(\[/video\]$)}, "")s = CGI.unescapeHTML(s)@@ -163,50 +168,54 @@ class ImportScripts::Phorum < ImportScripts::Base# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- s.gsub!(/\[http(s)?:\/\/(www\.)?/, '[')+ s.gsub!(%r{\[http(s)?://(www\.)?}, "[")# [QUOTE]...[/QUOTE]- s.gsub!(/\[quote\](.+?)\[\/quote\]/im) { "\n> #{$1}\n" }+ s.gsub!(%r{\[quote\](.+?)\[/quote\]}im) { "\n> #{$1}\n" }# [URL=...]...[/URL]- s.gsub!(/\[url="?(.+?)"?\](.+)\[\/url\]/i) { "[#{$2}](#{$1})" }+ s.gsub!(%r{\[url="?(.+?)"?\](.+)\[/url\]}i) { "[#{$2}](#{$1})" }# [IMG]...[/IMG]- s.gsub!(/\[\/?img\]/i, "")+ s.gsub!(%r{\[/?img\]}i, "")# convert list tags to ul and list=1 tags to ol# (basically, we're only missing list=a here...)- s.gsub!(/\[list\](.*?)\[\/list\]/m, '[ul]\1[/ul]')- s.gsub!(/\[list=1\](.*?)\[\/list\]/m, '[ol]\1[/ol]')+ s.gsub!(%r{\[list\](.*?)\[/list\]}m, '[ul]\1[/ul]')+ s.gsub!(%r{\[list=1\](.*?)\[/list\]}m, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:s.gsub!(/\[\*\](.*?)\n/, '[li]\1[/li]')# [CODE]...[/CODE]- s.gsub!(/\[\/?code\]/i, "\n```\n")+ s.gsub!(%r{\[/?code\]}i, "\n```\n")# [HIGHLIGHT]...[/HIGHLIGHT]- s.gsub!(/\[\/?highlight\]/i, "\n```\n")+ s.gsub!(%r{\[/?highlight\]}i, "\n```\n")# [YOUTUBE]<id>[/YOUTUBE]- s.gsub!(/\[youtube\](.+?)\[\/youtube\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ s.gsub!(%r{\[youtube\](.+?)\[/youtube\]}i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }# [youtube=425,350]id[/youtube]- s.gsub!(/\[youtube="?(.+?)"?\](.+)\[\/youtube\]/i) { "\nhttps://www.youtube.com/watch?v=#{$2}\n" }+ s.gsub!(%r{\[youtube="?(.+?)"?\](.+)\[/youtube\]}i) do+ "\nhttps://www.youtube.com/watch?v=#{$2}\n"+ end# [MEDIA=youtube]id[/MEDIA]- s.gsub!(/\[MEDIA=youtube\](.+?)\[\/MEDIA\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ s.gsub!(%r{\[MEDIA=youtube\](.+?)\[/MEDIA\]}i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }# [ame="youtube_link"]title[/ame]- s.gsub!(/\[ame="?(.+?)"?\](.+)\[\/ame\]/i) { "\n#{$1}\n" }+ s.gsub!(%r{\[ame="?(.+?)"?\](.+)\[/ame\]}i) { "\n#{$1}\n" }# [VIDEO=youtube;<id>]...[/VIDEO]- s.gsub!(/\[video=youtube;([^\]]+)\].*?\[\/video\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ s.gsub!(%r{\[video=youtube;([^\]]+)\].*?\[/video\]}i) do+ "\nhttps://www.youtube.com/watch?v=#{$1}\n"+ end# [USER=706]@username[/USER]- s.gsub!(/\[user="?(.+?)"?\](.+)\[\/user\]/i) { $2 }+ s.gsub!(%r{\[user="?(.+?)"?\](.+)\[/user\]}i) { $2 }# Remove the color tags.gsub!(/\[color=[#a-z0-9]+\]/i, "")- s.gsub!(/\[\/color\]/i, "")+ s.gsub!(%r{\[/color\]}i, "")s.gsub!(/\[hr\]/i, "<hr>")@@ -221,7 +230,7 @@ class ImportScripts::Phorum < ImportScripts::Baseenddef import_attachments- puts '', 'importing attachments...'+ puts "", "importing attachments..."uploads = mysql_query <<-SQLSELECT message_id, filename, FROM_BASE64(file_data) AS file_data, file_id@@ -234,26 +243,23 @@ class ImportScripts::Phorum < ImportScripts::Basetotal_count = uploads.countuploads.each do |upload|-# puts "*** processing file #{upload['file_id']}"- post_id = post_id_from_imported_post_id(upload['message_id'])+ post_id = post_id_from_imported_post_id(upload["message_id"])if post_id.nil?- puts "Post #{upload['message_id']} for attachment #{upload['file_id']} not found"+ puts "Post #{upload["message_id"]} for attachment #{upload["file_id"]} not found"nextendpost = Post.find(post_id)- real_filename = upload['filename']- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ real_filename = upload["filename"]+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."- tmpfile = 'attach_' + upload['file_id'].to_s- filename = File.join('/tmp/', tmpfile)- File.open(filename, 'wb') { |f|- f.write(upload['file_data'])- }+ tmpfile = "attach_" + upload["file_id"].to_s+ filename = File.join("/tmp/", tmpfile)+ File.open(filename, "wb") { |f| f.write(upload["file_data"]) }upl_obj = create_upload(post.user.id, filename, real_filename)@@ -265,16 +271,16 @@ class ImportScripts::Phorum < ImportScripts::Basepost.raw += "\n\n#{html}\n\n"post.save!if PostUpload.where(post: post, upload: upl_obj).exists?- puts "skipping creating uploaded for previously uploaded file #{upload['file_id']}"+ puts "skipping creating uploaded for previously uploaded file #{upload["file_id"]}"elsePostUpload.create!(post: post, upload: upl_obj)end# PostUpload.create!(post: post, upload: upl_obj) unless PostUpload.where(post: post, upload: upl_obj).exists?else- puts "Skipping attachment #{upload['file_id']}"+ puts "Skipping attachment #{upload["file_id"]}"endelse- puts "Failed to upload attachment #{upload['file_id']}"+ puts "Failed to upload attachment #{upload["file_id"]}"exitend@@ -282,7 +288,6 @@ class ImportScripts::Phorum < ImportScripts::Baseprint_status(current_count, total_count)endend-endImportScripts::Phorum.new.performdiff --git a/script/import_scripts/phpbb3.rb b/script/import_scripts/phpbb3.rbindex fb1807f911e..2c5ae75e449 100644--- a/script/import_scripts/phpbb3.rb+++ b/script/import_scripts/phpbb3.rb@@ -4,32 +4,34 @@# Documentation: https://meta.discourse.org/t/importing-from-phpbb3/30810if ARGV.length != 1 || !File.exist?(ARGV[0])- STDERR.puts '', 'Usage of phpBB3 importer:', 'bundle exec ruby phpbb3.rb <path/to/settings.yml>'- STDERR.puts '', "Use the settings file from #{File.expand_path('phpbb3/settings.yml', File.dirname(__FILE__))} as an example."- STDERR.puts '', 'Still having problems? Take a look at https://meta.discourse.org/t/importing-from-phpbb3/30810'+ STDERR.puts "", "Usage of phpBB3 importer:", "bundle exec ruby phpbb3.rb <path/to/settings.yml>"+ STDERR.puts "",+ "Use the settings file from #{File.expand_path("phpbb3/settings.yml", File.dirname(__FILE__))} as an example."+ STDERR.puts "",+ "Still having problems? Take a look at https://meta.discourse.org/t/importing-from-phpbb3/30810"exit 1endmodule ImportScriptsmodule PhpBB3- require_relative 'phpbb3/support/settings'- require_relative 'phpbb3/database/database'+ require_relative "phpbb3/support/settings"+ require_relative "phpbb3/database/database"@settings = Settings.load(ARGV[0])# We need to load the gem files for ruby-bbcode-to-md and the database adapter# (e.g. mysql2) before bundler gets initialized by the base importer.# Otherwise we get an error since those gems are not always in the Gemfile.- require 'ruby-bbcode-to-md' if @settings.use_bbcode_to_md+ require "ruby-bbcode-to-md" if @settings.use_bbcode_to_mdbegin@database = Database.create(@settings.database)rescue UnsupportedVersionError => error- STDERR.puts '', error.message+ STDERR.puts "", error.messageexit 1end- require_relative 'phpbb3/importer'+ require_relative "phpbb3/importer"Importer.new(@settings, @database).performendenddiff --git a/script/import_scripts/phpbb3/database/database.rb b/script/import_scripts/phpbb3/database/database.rbindex 240003edae9..c31b6bb6204 100644--- a/script/import_scripts/phpbb3/database/database.rb+++ b/script/import_scripts/phpbb3/database/database.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"module ImportScripts::PhpBB3class Database@@ -19,11 +19,11 @@ module ImportScripts::PhpBB3def create_databaseversion = get_phpbb_version- if version.start_with?('3.0')- require_relative 'database_3_0'+ if version.start_with?("3.0")+ require_relative "database_3_0"Database_3_0.new(@database_client, @database_settings)- elsif version.start_with?('3.1') || version.start_with?('3.2') || version.start_with?('3.3')- require_relative 'database_3_1'+ elsif version.start_with?("3.1") || version.start_with?("3.2") || version.start_with?("3.3")+ require_relative "database_3_1"Database_3_1.new(@database_client, @database_settings)elseraise UnsupportedVersionError, <<~TEXT@@ -42,7 +42,7 @@ module ImportScripts::PhpBB3username: @database_settings.username,password: @database_settings.password,database: @database_settings.schema,- reconnect: true+ reconnect: true,)enddiff --git a/script/import_scripts/phpbb3/database/database_3_0.rb b/script/import_scripts/phpbb3/database/database_3_0.rbindex 49f042a6e75..f45b38824a5 100644--- a/script/import_scripts/phpbb3/database/database_3_0.rb+++ b/script/import_scripts/phpbb3/database/database_3_0.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require_relative 'database_base'-require_relative '../support/constants'+require_relative "database_base"+require_relative "../support/constants"module ImportScripts::PhpBB3class Database_3_0 < DatabaseBasediff --git a/script/import_scripts/phpbb3/database/database_3_1.rb b/script/import_scripts/phpbb3/database/database_3_1.rbindex ee666bbbc01..3255e484b1a 100644--- a/script/import_scripts/phpbb3/database/database_3_1.rb+++ b/script/import_scripts/phpbb3/database/database_3_1.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require_relative 'database_3_0'-require_relative '../support/constants'+require_relative "database_3_0"+require_relative "../support/constants"module ImportScripts::PhpBB3class Database_3_1 < Database_3_0@@ -32,14 +32,15 @@ module ImportScripts::PhpBB3privatedef profile_fields_query(profile_fields)- @profile_fields_query ||= begin- if profile_fields.present?- columns = profile_fields.map { |field| "pf_#{field[:phpbb_field_name]}" }- ", #{columns.join(', ')}"- else- ""+ @profile_fields_query ||=+ begin+ if profile_fields.present?+ columns = profile_fields.map { |field| "pf_#{field[:phpbb_field_name]}" }+ ", #{columns.join(", ")}"+ else+ ""+ endend- endendendenddiff --git a/script/import_scripts/phpbb3/database/database_base.rb b/script/import_scripts/phpbb3/database/database_base.rbindex a51bcde3a5d..4419d4e78cb 100644--- a/script/import_scripts/phpbb3/database/database_base.rb+++ b/script/import_scripts/phpbb3/database/database_base.rb@@ -39,9 +39,7 @@ module ImportScripts::PhpBB3def find_last_row(rows)last_index = rows.size - 1- rows.each_with_index do |row, index|- return row if index == last_index- end+ rows.each_with_index { |row, index| return row if index == last_index }nilenddiff --git a/script/import_scripts/phpbb3/importer.rb b/script/import_scripts/phpbb3/importer.rbindex b8b84e29e69..a4f64f82c46 100644--- a/script/import_scripts/phpbb3/importer.rb+++ b/script/import_scripts/phpbb3/importer.rb@@ -1,9 +1,9 @@# frozen_string_literal: true-require_relative '../base'-require_relative 'support/settings'-require_relative 'database/database'-require_relative 'importers/importer_factory'+require_relative "../base"+require_relative "support/settings"+require_relative "database/database"+require_relative "importers/importer_factory"module ImportScripts::PhpBB3class Importer < ImportScripts::Base@@ -25,7 +25,7 @@ module ImportScripts::PhpBB3protecteddef execute- puts '', "importing from phpBB #{@php_config[:phpbb_version]}"+ puts "", "importing from phpBB #{@php_config[:phpbb_version]}"SiteSetting.tagging_enabled = true if @settings.tag_mappings.present?@@ -55,8 +55,14 @@ module ImportScripts::PhpBB3settings[:max_attachment_size_kb] = [max_file_size_kb, SiteSetting.max_attachment_size_kb].max# temporarily disable validation since we want to import all existing images and attachments- SiteSetting.type_supervisor.load_setting(:max_image_size_kb, max: settings[:max_image_size_kb])- SiteSetting.type_supervisor.load_setting(:max_attachment_size_kb, max: settings[:max_attachment_size_kb])+ SiteSetting.type_supervisor.load_setting(+ :max_image_size_kb,+ max: settings[:max_image_size_kb],+ )+ SiteSetting.type_supervisor.load_setting(+ :max_attachment_size_kb,+ max: settings[:max_attachment_size_kb],+ )settingsend@@ -66,7 +72,7 @@ module ImportScripts::PhpBB3enddef import_users- puts '', 'creating users'+ puts "", "creating users"total_count = @database.count_usersimporter = @importers.user_importerlast_user_id = 0@@ -88,10 +94,10 @@ module ImportScripts::PhpBB3enddef import_anonymous_users- puts '', 'creating anonymous users'+ puts "", "creating anonymous users"total_count = @database.count_anonymous_usersimporter = @importers.user_importer- last_username = ''+ last_username = ""batches do |offset|rows, last_username = @database.fetch_anonymous_users(last_username)@@ -109,26 +115,34 @@ module ImportScripts::PhpBB3enddef import_groups- puts '', 'creating groups'+ puts "", "creating groups"rows = @database.fetch_groupscreate_groups(rows) do |row|beginnext if row[:group_type] == 3- group_name = if @settings.site_name.present?- "#{@settings.site_name}_#{row[:group_name]}"- else- row[:group_name]- end[0..19].gsub(/[^a-zA-Z0-9\-_. ]/, '_')-- bio_raw = @importers.text_processor.process_raw_text(row[:group_desc]) rescue row[:group_desc]+ group_name =+ if @settings.site_name.present?+ "#{@settings.site_name}_#{row[:group_name]}"+ else+ row[:group_name]+ end[+ 0..19+ ].gsub(/[^a-zA-Z0-9\-_. ]/, "_")++ bio_raw =+ begin+ @importers.text_processor.process_raw_text(row[:group_desc])+ rescue StandardError+ row[:group_desc]+ end{id: @settings.prefix(row[:group_id]),name: group_name,full_name: row[:group_name],- bio_raw: bio_raw+ bio_raw: bio_raw,}rescue => elog_error("Failed to map group with ID #{row[:group_id]}", e)@@ -137,7 +151,7 @@ module ImportScripts::PhpBB3enddef import_user_groups- puts '', 'creating user groups'+ puts "", "creating user groups"rows = @database.fetch_group_usersrows.each do |row|@@ -147,7 +161,11 @@ module ImportScripts::PhpBB3user_id = @lookup.user_id_from_imported_user_id(@settings.prefix(row[:user_id]))begin- GroupUser.find_or_create_by(user_id: user_id, group_id: group_id, owner: row[:group_leader])+ GroupUser.find_or_create_by(+ user_id: user_id,+ group_id: group_id,+ owner: row[:group_leader],+ )rescue => elog_error("Failed to add user #{row[:user_id]} to group #{row[:group_id]}", e)end@@ -155,7 +173,7 @@ module ImportScripts::PhpBB3enddef import_new_categories- puts '', 'creating new categories'+ puts "", "creating new categories"create_categories(@settings.new_categories) do |row|next if row == "SKIP"@@ -163,13 +181,14 @@ module ImportScripts::PhpBB3{id: @settings.prefix(row[:forum_id]),name: row[:name],- parent_category_id: @lookup.category_id_from_imported_category_id(@settings.prefix(row[:parent_id]))+ parent_category_id:+ @lookup.category_id_from_imported_category_id(@settings.prefix(row[:parent_id])),}endenddef import_categories- puts '', 'creating categories'+ puts "", "creating categories"rows = @database.fetch_categoriesimporter = @importers.category_importer@@ -181,7 +200,7 @@ module ImportScripts::PhpBB3enddef import_posts- puts '', 'creating topics and posts'+ puts "", "creating topics and posts"total_count = @database.count_postsimporter = @importers.post_importerlast_post_id = 0@@ -202,7 +221,7 @@ module ImportScripts::PhpBB3enddef import_private_messages- puts '', 'creating private messages'+ puts "", "creating private messages"total_count = @database.count_messagesimporter = @importers.message_importerlast_msg_id = 0@@ -223,7 +242,7 @@ module ImportScripts::PhpBB3enddef import_bookmarks- puts '', 'creating bookmarks'+ puts "", "creating bookmarks"total_count = @database.count_bookmarksimporter = @importers.bookmark_importerlast_user_id = last_topic_id = 0@@ -243,7 +262,7 @@ module ImportScripts::PhpBB3enddef import_likes- puts '', 'importing likes'+ puts "", "importing likes"total_count = @database.count_likeslast_post_id = last_user_id = 0@@ -255,7 +274,7 @@ module ImportScripts::PhpBB3{post_id: @settings.prefix(row[:post_id]),user_id: @settings.prefix(row[:user_id]),- created_at: Time.zone.at(row[:thanks_time])+ created_at: Time.zone.at(row[:thanks_time]),}endenddiff --git a/script/import_scripts/phpbb3/importers/avatar_importer.rb b/script/import_scripts/phpbb3/importers/avatar_importer.rbindex bb72572c0ba..4e6e3b13bb1 100644--- a/script/import_scripts/phpbb3/importers/avatar_importer.rb+++ b/script/import_scripts/phpbb3/importers/avatar_importer.rb@@ -49,12 +49,12 @@ module ImportScripts::PhpBB3def get_avatar_path(avatar_type, filename)case avatar_type- when Constants::AVATAR_TYPE_UPLOADED, Constants::AVATAR_TYPE_STRING_UPLOADED then- filename.gsub!(/_[0-9]+\./, '.') # we need 1337.jpg, not 1337_2983745.jpg- get_uploaded_path(filename)- when Constants::AVATAR_TYPE_GALLERY, Constants::AVATAR_TYPE_STRING_GALLERY then+ when Constants::AVATAR_TYPE_UPLOADED, Constants::AVATAR_TYPE_STRING_UPLOADED+ filename.gsub!(/_[0-9]+\./, ".") # we need 1337.jpg, not 1337_2983745.jpg+ get_uploaded_path(filename)+ when Constants::AVATAR_TYPE_GALLERY, Constants::AVATAR_TYPE_STRING_GALLERYget_gallery_path(filename)- when Constants::AVATAR_TYPE_REMOTE, Constants::AVATAR_TYPE_STRING_REMOTE then+ when Constants::AVATAR_TYPE_REMOTE, Constants::AVATAR_TYPE_STRING_REMOTEdownload_avatar(filename)elseputs "Invalid avatar type #{avatar_type}. Skipping..."@@ -67,12 +67,13 @@ module ImportScripts::PhpBB3max_image_size_kb = SiteSetting.max_image_size_kb.kilobytesbegin- avatar_file = FileHelper.download(- url,- max_file_size: max_image_size_kb,- tmp_file_name: 'discourse-avatar',- follow_redirect: true- )+ avatar_file =+ FileHelper.download(+ url,+ max_file_size: max_image_size_kb,+ tmp_file_name: "discourse-avatar",+ follow_redirect: true,+ )rescue StandardError => errwarn "Error downloading avatar: #{err.message}. Skipping..."return nil@@ -100,11 +101,11 @@ module ImportScripts::PhpBB3def is_allowed_avatar_type?(avatar_type)case avatar_type- when Constants::AVATAR_TYPE_UPLOADED, Constants::AVATAR_TYPE_STRING_UPLOADED then+ when Constants::AVATAR_TYPE_UPLOADED, Constants::AVATAR_TYPE_STRING_UPLOADED@settings.import_uploaded_avatars- when Constants::AVATAR_TYPE_REMOTE, Constants::AVATAR_TYPE_STRING_REMOTE then+ when Constants::AVATAR_TYPE_REMOTE, Constants::AVATAR_TYPE_STRING_REMOTE@settings.import_remote_avatars- when Constants::AVATAR_TYPE_GALLERY, Constants::AVATAR_TYPE_STRING_GALLERY then+ when Constants::AVATAR_TYPE_GALLERY, Constants::AVATAR_TYPE_STRING_GALLERY@settings.import_gallery_avatarselsefalsediff --git a/script/import_scripts/phpbb3/importers/bookmark_importer.rb b/script/import_scripts/phpbb3/importers/bookmark_importer.rbindex 784e6c74768..6dd2a793d8f 100644--- a/script/import_scripts/phpbb3/importers/bookmark_importer.rb+++ b/script/import_scripts/phpbb3/importers/bookmark_importer.rb@@ -9,7 +9,7 @@ module ImportScripts::PhpBB3def map_bookmark(row){user_id: @settings.prefix(row[:user_id]),- post_id: @settings.prefix(row[:topic_first_post_id])+ post_id: @settings.prefix(row[:topic_first_post_id]),}endenddiff --git a/script/import_scripts/phpbb3/importers/category_importer.rb b/script/import_scripts/phpbb3/importers/category_importer.rbindex 6e5725b97e5..e0b95bc79b6 100644--- a/script/import_scripts/phpbb3/importers/category_importer.rb+++ b/script/import_scripts/phpbb3/importers/category_importer.rb@@ -23,11 +23,13 @@ module ImportScripts::PhpBB3{id: @settings.prefix(row[:forum_id]),name: CGI.unescapeHTML(row[:forum_name]),- parent_category_id: @lookup.category_id_from_imported_category_id(@settings.prefix(row[:parent_id])),- post_create_action: proc do |category|- update_category_description(category, row)- @permalink_importer.create_for_category(category, row[:forum_id]) # skip @settings.prefix because ID is used in permalink generation- end+ parent_category_id:+ @lookup.category_id_from_imported_category_id(@settings.prefix(row[:parent_id])),+ post_create_action:+ proc do |category|+ update_category_description(category, row)+ @permalink_importer.create_for_category(category, row[:forum_id]) # skip @settings.prefix because ID is used in permalink generation+ end,}end@@ -51,7 +53,16 @@ module ImportScripts::PhpBB3endif row[:forum_desc].present?- changes = { raw: (@text_processor.process_raw_text(row[:forum_desc]) rescue row[:forum_desc]) }+ changes = {+ raw:+ (+ begin+ @text_processor.process_raw_text(row[:forum_desc])+ rescue StandardError+ row[:forum_desc]+ end+ ),+ }opts = { revised_at: post.created_at, bypass_bump: true }post.revise(Discourse.system_user, changes, opts)enddiff --git a/script/import_scripts/phpbb3/importers/importer_factory.rb b/script/import_scripts/phpbb3/importers/importer_factory.rbindex b02cb92ff0d..d7a3fe9c9fc 100644--- a/script/import_scripts/phpbb3/importers/importer_factory.rb+++ b/script/import_scripts/phpbb3/importers/importer_factory.rb@@ -1,16 +1,16 @@# frozen_string_literal: true-require_relative 'attachment_importer'-require_relative 'avatar_importer'-require_relative 'bookmark_importer'-require_relative 'category_importer'-require_relative 'message_importer'-require_relative 'poll_importer'-require_relative 'post_importer'-require_relative 'permalink_importer'-require_relative 'user_importer'-require_relative '../support/smiley_processor'-require_relative '../support/text_processor'+require_relative "attachment_importer"+require_relative "avatar_importer"+require_relative "bookmark_importer"+require_relative "category_importer"+require_relative "message_importer"+require_relative "poll_importer"+require_relative "post_importer"+require_relative "permalink_importer"+require_relative "user_importer"+require_relative "../support/smiley_processor"+require_relative "../support/text_processor"module ImportScripts::PhpBB3class ImporterFactory@@ -36,7 +36,14 @@ module ImportScripts::PhpBB3enddef post_importer- PostImporter.new(@lookup, text_processor, attachment_importer, poll_importer, permalink_importer, @settings)+ PostImporter.new(+ @lookup,+ text_processor,+ attachment_importer,+ poll_importer,+ permalink_importer,+ @settings,+ )enddef message_importer@@ -64,7 +71,8 @@ module ImportScripts::PhpBB3enddef text_processor- @text_processor ||= TextProcessor.new(@lookup, @database, smiley_processor, @settings, @phpbb_config)+ @text_processor ||=+ TextProcessor.new(@lookup, @database, smiley_processor, @settings, @phpbb_config)enddef smiley_processordiff --git a/script/import_scripts/phpbb3/importers/message_importer.rb b/script/import_scripts/phpbb3/importers/message_importer.rbindex 65c5874bdae..c71795b3280 100644--- a/script/import_scripts/phpbb3/importers/message_importer.rb+++ b/script/import_scripts/phpbb3/importers/message_importer.rb@@ -20,14 +20,16 @@ module ImportScripts::PhpBB3enddef map_message(row)- user_id = @lookup.user_id_from_imported_user_id(@settings.prefix(row[:author_id])) || Discourse.system_user.id+ user_id =+ @lookup.user_id_from_imported_user_id(@settings.prefix(row[:author_id])) ||+ Discourse.system_user.idattachments = import_attachments(row, user_id)mapped = {id: get_import_id(row[:msg_id]),user_id: user_id,created_at: Time.zone.at(row[:message_time]),- raw: @text_processor.process_private_msg(row[:message_text], attachments)+ raw: @text_processor.process_private_msg(row[:message_text], attachments),}root_user_ids = sorted_user_ids(row[:root_author_id], row[:root_to_address])@@ -43,7 +45,7 @@ module ImportScripts::PhpBB3protected- RE_PREFIX = 're: '+ RE_PREFIX = "re: "def import_attachments(row, user_id)if @settings.import_attachments && row[:attachment_count] > 0@@ -55,7 +57,7 @@ module ImportScripts::PhpBB3mapped[:title] = get_topic_title(row)mapped[:archetype] = Archetype.private_messagemapped[:target_usernames] = get_recipient_usernames(row)- mapped[:custom_fields] = { import_user_ids: current_user_ids.join(',') }+ mapped[:custom_fields] = { import_user_ids: current_user_ids.join(",") }if mapped[:target_usernames].empty?puts "Private message without recipients. Skipping #{row[:msg_id]}: #{row[:message_subject][0..40]}"@@ -75,9 +77,9 @@ module ImportScripts::PhpBB3# to_address looks like this: "u_91:u_1234:g_200"# If there is a "u_" prefix, the prefix is discarded and the rest is a user_id- user_ids = to_address.split(':')+ user_ids = to_address.split(":")user_ids.uniq!- user_ids.map! { |u| u[2..-1].to_i if u[0..1] == 'u_' }.compact+ user_ids.map! { |u| u[2..-1].to_i if u[0..1] == "u_" }.compactenddef get_recipient_group_ids(to_address)@@ -85,16 +87,19 @@ module ImportScripts::PhpBB3# to_address looks like this: "u_91:u_1234:g_200"# If there is a "g_" prefix, the prefix is discarded and the rest is a group_id- group_ids = to_address.split(':')+ group_ids = to_address.split(":")group_ids.uniq!- group_ids.map! { |g| g[2..-1].to_i if g[0..1] == 'g_' }.compact+ group_ids.map! { |g| g[2..-1].to_i if g[0..1] == "g_" }.compactenddef get_recipient_usernames(row)import_user_ids = get_recipient_user_ids(row[:to_address])- usernames = import_user_ids.map do |import_user_id|- @lookup.find_user_by_import_id(@settings.prefix(import_user_id)).try(:username)- end.compact+ usernames =+ import_user_ids+ .map do |import_user_id|+ @lookup.find_user_by_import_id(@settings.prefix(import_user_id)).try(:username)+ end+ .compactimport_group_ids = get_recipient_group_ids(row[:to_address])import_group_ids.each do |import_group_id|@@ -142,13 +147,19 @@ module ImportScripts::PhpBB3topic_titles = [topic_title]topic_titles << topic_title[RE_PREFIX.length..-1] if topic_title.start_with?(RE_PREFIX)- Post.select(:topic_id)+ Post+ .select(:topic_id).joins(:topic).joins(:_custom_fields)- .where(["LOWER(topics.title) IN (:titles) AND post_custom_fields.name = 'import_user_ids' AND post_custom_fields.value = :user_ids",- { titles: topic_titles, user_ids: current_user_ids.join(',') }])- .order('topics.created_at DESC')- .first.try(:topic_id)+ .where(+ [+ "LOWER(topics.title) IN (:titles) AND post_custom_fields.name = 'import_user_ids' AND post_custom_fields.value = :user_ids",+ { titles: topic_titles, user_ids: current_user_ids.join(",") },+ ],+ )+ .order("topics.created_at DESC")+ .first+ .try(:topic_id)endendenddiff --git a/script/import_scripts/phpbb3/importers/permalink_importer.rb b/script/import_scripts/phpbb3/importers/permalink_importer.rbindex 051604ba87e..5dcd9ffe60f 100644--- a/script/import_scripts/phpbb3/importers/permalink_importer.rb+++ b/script/import_scripts/phpbb3/importers/permalink_importer.rb@@ -13,13 +13,15 @@ module ImportScripts::PhpBB3def change_site_settingsnormalizations = SiteSetting.permalink_normalizations- normalizations = normalizations.blank? ? [] : normalizations.split('|')+ normalizations = normalizations.blank? ? [] : normalizations.split("|")- add_normalization(normalizations, CATEGORY_LINK_NORMALIZATION) if @settings.create_category_links+ if @settings.create_category_links+ add_normalization(normalizations, CATEGORY_LINK_NORMALIZATION)+ endadd_normalization(normalizations, POST_LINK_NORMALIZATION) if @settings.create_post_linksadd_normalization(normalizations, TOPIC_LINK_NORMALIZATION) if @settings.create_topic_links- SiteSetting.permalink_normalizations = normalizations.join('|')+ SiteSetting.permalink_normalizations = normalizations.join("|")enddef create_for_category(category, import_id)@@ -50,8 +52,8 @@ module ImportScripts::PhpBB3def add_normalization(normalizations, normalization)if @settings.normalization_prefix.present?- prefix = @settings.normalization_prefix[%r|^/?(.*?)/?$|, 1]- normalization = "/#{prefix.gsub('/', '\/')}\\#{normalization}"+ prefix = @settings.normalization_prefix[%r{^/?(.*?)/?$}, 1]+ normalization = "/#{prefix.gsub("/", '\/')}\\#{normalization}"endnormalizations << normalization unless normalizations.include?(normalization)diff --git a/script/import_scripts/phpbb3/importers/poll_importer.rb b/script/import_scripts/phpbb3/importers/poll_importer.rbindex 785fbb60b27..df4696201c3 100644--- a/script/import_scripts/phpbb3/importers/poll_importer.rb+++ b/script/import_scripts/phpbb3/importers/poll_importer.rb@@ -49,7 +49,12 @@ module ImportScripts::PhpBB3enddef get_option_text(row)- text = @text_processor.process_raw_text(row[:poll_option_text]) rescue row[:poll_option_text]+ text =+ begin+ @text_processor.process_raw_text(row[:poll_option_text])+ rescue StandardError+ row[:poll_option_text]+ endtext.squish!text.gsub!(/^(\d+)\./, '\1\.')text@@ -57,7 +62,12 @@ module ImportScripts::PhpBB3# @param poll_data [ImportScripts::PhpBB3::PollData]def get_poll_text(poll_data)- title = @text_processor.process_raw_text(poll_data.title) rescue poll_data.title+ title =+ begin+ @text_processor.process_raw_text(poll_data.title)+ rescue StandardError+ poll_data.title+ endtext = +"#{title}\n\n"arguments = ["results=always"]@@ -69,11 +79,9 @@ module ImportScripts::PhpBB3arguments << "type=regular"end- text << "[poll #{arguments.join(' ')}]"+ text << "[poll #{arguments.join(" ")}]"- poll_data.options.each do |option|- text << "\n* #{option[:text]}"- end+ poll_data.options.each { |option| text << "\n* #{option[:text]}" }text << "\n[/poll]"end@@ -104,9 +112,7 @@ module ImportScripts::PhpBB3poll.poll_options.each_with_index do |option, index|imported_option = poll_data.options[index]- imported_option[:ids].each do |imported_id|- option_ids[imported_id] = option.id- end+ imported_option[:ids].each { |imported_id| option_ids[imported_id] = option.id }endoption_idsdiff --git a/script/import_scripts/phpbb3/importers/post_importer.rb b/script/import_scripts/phpbb3/importers/post_importer.rbindex 8f41e9ed669..4f66560e349 100644--- a/script/import_scripts/phpbb3/importers/post_importer.rb+++ b/script/import_scripts/phpbb3/importers/post_importer.rb@@ -8,7 +8,14 @@ module ImportScripts::PhpBB3# @param poll_importer [ImportScripts::PhpBB3::PollImporter]# @param permalink_importer [ImportScripts::PhpBB3::PermalinkImporter]# @param settings [ImportScripts::PhpBB3::Settings]- def initialize(lookup, text_processor, attachment_importer, poll_importer, permalink_importer, settings)+ def initialize(+ lookup,+ text_processor,+ attachment_importer,+ poll_importer,+ permalink_importer,+ settings+ )@lookup = lookup@text_processor = text_processor@attachment_importer = attachment_importer@@ -24,7 +31,8 @@ module ImportScripts::PhpBB3def map_post(row)return if @settings.category_mappings.dig(row[:forum_id].to_s, :skip)- imported_user_id = @settings.prefix(row[:post_username].blank? ? row[:poster_id] : row[:post_username])+ imported_user_id =+ @settings.prefix(row[:post_username].blank? ? row[:poster_id] : row[:post_username])user_id = @lookup.user_id_from_imported_user_id(imported_user_id) || -1is_first_post = row[:post_id] == row[:topic_first_post_id]@@ -35,7 +43,7 @@ module ImportScripts::PhpBB3user_id: user_id,created_at: Time.zone.at(row[:post_time]),raw: @text_processor.process_post(row[:post_text], attachments),- import_topic_id: @settings.prefix(row[:topic_id])+ import_topic_id: @settings.prefix(row[:topic_id]),}if is_first_post@@ -58,7 +66,9 @@ module ImportScripts::PhpBB3mapped[:category] = if category_mapping = @settings.category_mappings[row[:forum_id].to_s]category_mapping[:discourse_category_id] ||- @lookup.category_id_from_imported_category_id(@settings.prefix(category_mapping[:target_category_id]))+ @lookup.category_id_from_imported_category_id(+ @settings.prefix(category_mapping[:target_category_id]),+ )else@lookup.category_id_from_imported_category_id(@settings.prefix(row[:forum_id]))end@@ -81,7 +91,8 @@ module ImportScripts::PhpBB3enddef map_other_post(row, mapped)- parent = @lookup.topic_lookup_from_imported_post_id(@settings.prefix(row[:topic_first_post_id]))+ parent =+ @lookup.topic_lookup_from_imported_post_id(@settings.prefix(row[:topic_first_post_id]))if parent.blank?puts "Parent post #{@settings.prefix(row[:topic_first_post_id])} doesn't exist. Skipping #{@settings.prefix(row[:post_id])}: #{row[:topic_title][0..40]}"diff --git a/script/import_scripts/phpbb3/importers/user_importer.rb b/script/import_scripts/phpbb3/importers/user_importer.rbindex 3fa61d6e17e..6f32223232c 100644--- a/script/import_scripts/phpbb3/importers/user_importer.rb+++ b/script/import_scripts/phpbb3/importers/user_importer.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require_relative '../support/constants'+require_relative "../support/constants"module ImportScripts::PhpBB3class UserImporter@@ -29,8 +29,22 @@ module ImportScripts::PhpBB3password: @settings.import_passwords ? row[:user_password] : nil,name: @settings.username_as_name ? row[:username] : row[:name].presence,created_at: Time.zone.at(row[:user_regdate]),- last_seen_at: row[:user_lastvisit] == 0 ? Time.zone.at(row[:user_regdate]) : Time.zone.at(row[:user_lastvisit]),- registration_ip_address: (IPAddr.new(row[:user_ip]) rescue nil),+ last_seen_at:+ (+ if row[:user_lastvisit] == 0+ Time.zone.at(row[:user_regdate])+ else+ Time.zone.at(row[:user_lastvisit])+ end+ ),+ registration_ip_address:+ (+ begin+ IPAddr.new(row[:user_ip])+ rescue StandardError+ nil+ end+ ),active: is_active_user,trust_level: trust_level,manual_locked_trust_level: manual_locked_trust_level,@@ -43,10 +57,11 @@ module ImportScripts::PhpBB3location: row[:user_from],date_of_birth: parse_birthdate(row),custom_fields: custom_fields(row),- post_create_action: proc do |user|- suspend_user(user, row)- @avatar_importer.import_avatar(user, row) if row[:user_avatar_type].present?- end+ post_create_action:+ proc do |user|+ suspend_user(user, row)+ @avatar_importer.import_avatar(user, row) if row[:user_avatar_type].present?+ end,}end@@ -61,18 +76,19 @@ module ImportScripts::PhpBB3id: @settings.prefix(username),email: "anonymous_#{SecureRandom.hex}@no-email.invalid",username: username,- name: @settings.username_as_name ? username : '',+ name: @settings.username_as_name ? username : "",created_at: Time.zone.at(row[:first_post_time]),active: true,trust_level: TrustLevel[0],approved: true,approved_by_id: Discourse.system_user.id,approved_at: Time.now,- post_create_action: proc do |user|- row[:user_inactive_reason] = Constants::INACTIVE_MANUAL- row[:ban_reason] = 'Anonymous user from phpBB3' # TODO i18n- suspend_user(user, row, true)- end+ post_create_action:+ proc do |user|+ row[:user_inactive_reason] = Constants::INACTIVE_MANUAL+ row[:ban_reason] = "Anonymous user from phpBB3" # TODO i18n+ suspend_user(user, row, true)+ end,}end@@ -80,25 +96,32 @@ module ImportScripts::PhpBB3def parse_birthdate(row)return nil if row[:user_birthday].blank?- birthdate = Date.strptime(row[:user_birthday].delete(' '), '%d-%m-%Y') rescue nil+ birthdate =+ begin+ Date.strptime(row[:user_birthday].delete(" "), "%d-%m-%Y")+ rescue StandardError+ nil+ endbirthdate && birthdate.year > 0 ? birthdate : nilenddef user_fields- @user_fields ||= begin- Hash[UserField.all.map { |field| [field.name, field] }]- end+ @user_fields ||=+ begin+ Hash[UserField.all.map { |field| [field.name, field] }]+ endenddef field_mappings- @field_mappings ||= begin- @settings.custom_fields.map do |field|- {- phpbb_field_name: "pf_#{field[:phpbb_field_name]}".to_sym,- discourse_user_field: user_fields[field[:discourse_field_name]]- }+ @field_mappings ||=+ begin+ @settings.custom_fields.map do |field|+ {+ phpbb_field_name: "pf_#{field[:phpbb_field_name]}".to_sym,+ discourse_user_field: user_fields[field[:discourse_field_name]],+ }+ endend- endenddef custom_fields(row)@@ -114,7 +137,8 @@ module ImportScripts::PhpBB3when "confirm"value = value == 1 ? true : nilwhen "dropdown"- value = user_field.user_field_options.find { |option| option.value == value } ? value : nil+ value =+ user_field.user_field_options.find { |option| option.value == value } ? value : nilendcustom_fields["user_field_#{user_field.id}"] = value if value.present?@@ -128,7 +152,8 @@ module ImportScripts::PhpBB3if row[:user_inactive_reason] == Constants::INACTIVE_MANUALuser.suspended_at = Time.nowuser.suspended_till = 200.years.from_now- ban_reason = row[:ban_reason].blank? ? 'Account deactivated by administrator' : row[:ban_reason] # TODO i18n+ ban_reason =+ row[:ban_reason].blank? ? "Account deactivated by administrator" : row[:ban_reason] # TODO i18nelsif row[:ban_start].present?user.suspended_at = Time.zone.at(row[:ban_start])user.suspended_till = row[:ban_end] > 0 ? Time.zone.at(row[:ban_end]) : 200.years.from_now@@ -148,7 +173,9 @@ module ImportScripts::PhpBB3if user.saveStaffActionLogger.new(Discourse.system_user).log_user_suspend(user, ban_reason)else- Rails.logger.error("Failed to suspend user #{user.username}. #{user.errors.try(:full_messages).try(:inspect)}")+ Rails.logger.error(+ "Failed to suspend user #{user.username}. #{user.errors.try(:full_messages).try(:inspect)}",+ )endendenddiff --git a/script/import_scripts/phpbb3/support/bbcode/markdown_node.rb b/script/import_scripts/phpbb3/support/bbcode/markdown_node.rbindex 5a42a1bf408..c5e5048a9f1 100644--- a/script/import_scripts/phpbb3/support/bbcode/markdown_node.rb+++ b/script/import_scripts/phpbb3/support/bbcode/markdown_node.rb@@ -1,7 +1,9 @@# frozen_string_literal: true-module ImportScripts; end-module ImportScripts::PhpBB3; end+module ImportScripts+end+module ImportScripts::PhpBB3+endmodule ImportScripts::PhpBB3::BBCodeLINEBREAK_AUTO = :autodiff --git a/script/import_scripts/phpbb3/support/bbcode/xml_to_markdown.rb b/script/import_scripts/phpbb3/support/bbcode/xml_to_markdown.rbindex 7041c5923f7..004601d2471 100644--- a/script/import_scripts/phpbb3/support/bbcode/xml_to_markdown.rb+++ b/script/import_scripts/phpbb3/support/bbcode/xml_to_markdown.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require 'nokogiri'-require_relative 'markdown_node'+require "nokogiri"+require_relative "markdown_node"module ImportScripts::PhpBB3::BBCodeclass XmlToMarkdown@@ -14,7 +14,7 @@ module ImportScripts::PhpBB3::BBCode@allow_inline_code = opts.fetch(:allow_inline_code, false)@traditional_linebreaks = opts.fetch(:traditional_linebreaks, false)- @doc = Nokogiri::XML(xml)+ @doc = Nokogiri.XML(xml)@list_stack = []end@@ -28,9 +28,9 @@ module ImportScripts::PhpBB3::BBCodeprivate- IGNORED_ELEMENTS = ["s", "e", "i"]- ELEMENTS_WITHOUT_LEADING_WHITESPACES = ["LIST", "LI"]- ELEMENTS_WITH_HARD_LINEBREAKS = ["B", "I", "U"]+ IGNORED_ELEMENTS = %w[s e i]+ ELEMENTS_WITHOUT_LEADING_WHITESPACES = %w[LIST LI]+ ELEMENTS_WITH_HARD_LINEBREAKS = %w[B I U]EXPLICIT_LINEBREAK_THRESHOLD = 2def preprocess_xml@@ -65,9 +65,7 @@ module ImportScripts::PhpBB3::BBCodexml_node.children.each { |xml_child| visit(xml_child, md_node || md_parent) }after_hook = "after_#{xml_node.name}"- if respond_to?(after_hook, include_all: true)- send(after_hook, xml_node, md_node)- end+ send(after_hook, xml_node, md_node) if respond_to?(after_hook, include_all: true)enddef create_node(xml_node, md_parent)@@ -84,19 +82,15 @@ module ImportScripts::PhpBB3::BBCodeenddef visit_B(xml_node, md_node)- if xml_node.parent&.name != 'B'- md_node.enclosed_with = "**"- end+ md_node.enclosed_with = "**" if xml_node.parent&.name != "B"enddef visit_I(xml_node, md_node)- if xml_node.parent&.name != 'I'- md_node.enclosed_with = "_"- end+ md_node.enclosed_with = "_" if xml_node.parent&.name != "I"enddef visit_U(xml_node, md_node)- if xml_node.parent&.name != 'U'+ if xml_node.parent&.name != "U"md_node.prefix = "[u]"md_node.postfix = "[/u]"end@@ -122,10 +116,7 @@ module ImportScripts::PhpBB3::BBCodemd_node.prefix_linebreaks = md_node.postfix_linebreaks = @list_stack.size == 0 ? 2 : 1md_node.prefix_linebreak_type = LINEBREAK_HTML if @list_stack.size == 0- @list_stack << {- unordered: xml_node.attribute('type').nil?,- item_count: 0- }+ @list_stack << { unordered: xml_node.attribute("type").nil?, item_count: 0 }enddef after_LIST(xml_node, md_node)@@ -138,21 +129,21 @@ module ImportScripts::PhpBB3::BBCodelist[:item_count] += 1- indentation = ' ' * 2 * depth- symbol = list[:unordered] ? '*' : "#{list[:item_count]}."+ indentation = " " * 2 * depth+ symbol = list[:unordered] ? "*" : "#{list[:item_count]}."md_node.prefix = "#{indentation}#{symbol} "md_node.postfix_linebreaks = 1enddef visit_IMG(xml_node, md_node)- md_node.text = +"})"+ md_node.text = +"})"md_node.prefix_linebreaks = md_node.postfix_linebreaks = 2md_node.skip_childrenenddef visit_URL(xml_node, md_node)- original_url = xml_node.attribute('url').to_s+ original_url = xml_node.attribute("url").to_surl = CGI.unescapeHTML(original_url)url = @url_replacement.call(url) if @url_replacement@@ -173,7 +164,8 @@ module ImportScripts::PhpBB3::BBCodedef visit_br(xml_node, md_node)md_node.postfix_linebreaks += 1- if md_node.postfix_linebreaks > 1 && ELEMENTS_WITH_HARD_LINEBREAKS.include?(xml_node.parent&.name)+ if md_node.postfix_linebreaks > 1 &&+ ELEMENTS_WITH_HARD_LINEBREAKS.include?(xml_node.parent&.name)md_node.postfix_linebreak_type = LINEBREAK_HARDendend@@ -194,7 +186,8 @@ module ImportScripts::PhpBB3::BBCodedef visit_QUOTE(xml_node, md_node)if post = quoted_post(xml_node)- md_node.prefix = %Q{[quote="#{post[:username]}, post:#{post[:post_number]}, topic:#{post[:topic_id]}"]\n}+ md_node.prefix =+ %Q{[quote="#{post[:username]}, post:#{post[:post_number]}, topic:#{post[:topic_id]}"]\n}md_node.postfix = "\n[/quote]"elsif username = quoted_username(xml_node)md_node.prefix = %Q{[quote="#{username}"]\n}@@ -242,11 +235,11 @@ module ImportScripts::PhpBB3::BBCodereturn if size.nil?if size.between?(1, 99)- md_node.prefix = '<small>'- md_node.postfix = '</small>'+ md_node.prefix = "<small>"+ md_node.postfix = "</small>"elsif size.between?(101, 200)- md_node.prefix = '<big>'- md_node.postfix = '</big>'+ md_node.prefix = "<big>"+ md_node.postfix = "</big>"endend@@ -267,7 +260,8 @@ module ImportScripts::PhpBB3::BBCodeparent_prefix = prefix_from_parent(md_parent)- if parent_prefix && md_node.xml_node_name != "br" && (md_parent.prefix_children || !markdown.empty?)+ if parent_prefix && md_node.xml_node_name != "br" &&+ (md_parent.prefix_children || !markdown.empty?)prefix = "#{parent_prefix}#{prefix}"end@@ -275,11 +269,21 @@ module ImportScripts::PhpBB3::BBCodetext, prefix, postfix = hoist_whitespaces!(markdown, text, prefix, postfix)end- add_linebreaks!(markdown, md_node.prefix_linebreaks, md_node.prefix_linebreak_type, parent_prefix)+ add_linebreaks!(+ markdown,+ md_node.prefix_linebreaks,+ md_node.prefix_linebreak_type,+ parent_prefix,+ )markdown << prefixmarkdown << textmarkdown << postfix- add_linebreaks!(markdown, md_node.postfix_linebreaks, md_node.postfix_linebreak_type, parent_prefix)+ add_linebreaks!(+ markdown,+ md_node.postfix_linebreaks,+ md_node.postfix_linebreak_type,+ parent_prefix,+ )endmarkdown@@ -296,9 +300,7 @@ module ImportScripts::PhpBB3::BBCodeendunless postfix.empty?- if ends_with_whitespace?(text)- postfix = "#{postfix}#{text[-1]}"- end+ postfix = "#{postfix}#{text[-1]}" if ends_with_whitespace?(text)text = text.rstripend@@ -319,16 +321,24 @@ module ImportScripts::PhpBB3::BBCodeif linebreak_type == LINEBREAK_HTMLmax_linebreak_count = [existing_linebreak_count, required_linebreak_count - 1].max + 1- required_linebreak_count = max_linebreak_count if max_linebreak_count > EXPLICIT_LINEBREAK_THRESHOLD+ required_linebreak_count = max_linebreak_count if max_linebreak_count >+ EXPLICIT_LINEBREAK_THRESHOLDendreturn if existing_linebreak_count >= required_linebreak_countrstrip!(markdown)- alternative_linebreak_start_index = required_linebreak_count > EXPLICIT_LINEBREAK_THRESHOLD ? 1 : 2+ alternative_linebreak_start_index =+ required_linebreak_count > EXPLICIT_LINEBREAK_THRESHOLD ? 1 : 2required_linebreak_count.times do |index|- linebreak = linebreak(linebreak_type, index, alternative_linebreak_start_index, required_linebreak_count)+ linebreak =+ linebreak(+ linebreak_type,+ index,+ alternative_linebreak_start_index,+ required_linebreak_count,+ )markdown << (linebreak == "\n" ? prefix.rstrip : prefix) if prefix && index > 0markdown << linebreak@@ -336,18 +346,25 @@ module ImportScripts::PhpBB3::BBCodeenddef rstrip!(markdown)- markdown.gsub!(/\s*(?:\\?\n|<br>\n)*\z/, '')+ markdown.gsub!(/\s*(?:\\?\n|<br>\n)*\z/, "")end- def linebreak(linebreak_type, linebreak_index, alternative_linebreak_start_index, required_linebreak_count)+ def linebreak(+ linebreak_type,+ linebreak_index,+ alternative_linebreak_start_index,+ required_linebreak_count+ )use_alternative_linebreak = linebreak_index >= alternative_linebreak_start_indexis_last_linebreak = linebreak_index + 1 == required_linebreak_count- return "<br>\n" if linebreak_type == LINEBREAK_HTML &&- use_alternative_linebreak && is_last_linebreak+ if linebreak_type == LINEBREAK_HTML && use_alternative_linebreak && is_last_linebreak+ return "<br>\n"+ end- return "\\\n" if linebreak_type == LINEBREAK_HARD ||- @traditional_linebreaks || use_alternative_linebreak+ if linebreak_type == LINEBREAK_HARD || @traditional_linebreaks || use_alternative_linebreak+ return "\\\n"+ end"\n"enddiff --git a/script/import_scripts/phpbb3/support/constants.rb b/script/import_scripts/phpbb3/support/constants.rbindex af8d62dc439..c832cfee8f8 100644--- a/script/import_scripts/phpbb3/support/constants.rb+++ b/script/import_scripts/phpbb3/support/constants.rb@@ -8,8 +8,8 @@ module ImportScripts::PhpBB3INACTIVE_MANUAL = 3 # Account deactivated by administratorINACTIVE_REMIND = 4 # Forced user account reactivation- GROUP_ADMINISTRATORS = 'ADMINISTRATORS'- GROUP_MODERATORS = 'GLOBAL_MODERATORS'+ GROUP_ADMINISTRATORS = "ADMINISTRATORS"+ GROUP_MODERATORS = "GLOBAL_MODERATORS"# https://wiki.phpbb.com/Table.phpbb_usersUSER_TYPE_NORMAL = 0@@ -21,9 +21,9 @@ module ImportScripts::PhpBB3AVATAR_TYPE_REMOTE = 2AVATAR_TYPE_GALLERY = 3- AVATAR_TYPE_STRING_UPLOADED = 'avatar.driver.upload'- AVATAR_TYPE_STRING_REMOTE = 'avatar.driver.remote'- AVATAR_TYPE_STRING_GALLERY = 'avatar.driver.local'+ AVATAR_TYPE_STRING_UPLOADED = "avatar.driver.upload"+ AVATAR_TYPE_STRING_REMOTE = "avatar.driver.remote"+ AVATAR_TYPE_STRING_GALLERY = "avatar.driver.local"FORUM_TYPE_CATEGORY = 0FORUM_TYPE_POST = 1diff --git a/script/import_scripts/phpbb3/support/settings.rb b/script/import_scripts/phpbb3/support/settings.rbindex b259821ab3c..e308e322cf5 100644--- a/script/import_scripts/phpbb3/support/settings.rb+++ b/script/import_scripts/phpbb3/support/settings.rb@@ -1,13 +1,13 @@# frozen_string_literal: true-require 'csv'-require 'yaml'-require_relative '../../base'+require "csv"+require "yaml"+require_relative "../../base"module ImportScripts::PhpBB3class Settingsdef self.load(filename)- yaml = YAML::load_file(filename)+ yaml = YAML.load_file(filename)Settings.new(yaml.deep_stringify_keys.with_indifferent_access)end@@ -44,40 +44,41 @@ module ImportScripts::PhpBB3attr_reader :databasedef initialize(yaml)- import_settings = yaml['import']+ import_settings = yaml["import"]- @site_name = import_settings['site_name']+ @site_name = import_settings["site_name"]- @new_categories = import_settings['new_categories']- @category_mappings = import_settings.fetch('category_mappings', []).to_h { |m| [m[:source_category_id].to_s, m] }- @tag_mappings = import_settings['tag_mappings']- @rank_mapping = import_settings['rank_mapping']+ @new_categories = import_settings["new_categories"]+ @category_mappings =+ import_settings.fetch("category_mappings", []).to_h { |m| [m[:source_category_id].to_s, m] }+ @tag_mappings = import_settings["tag_mappings"]+ @rank_mapping = import_settings["rank_mapping"]- @import_anonymous_users = import_settings['anonymous_users']- @import_attachments = import_settings['attachments']- @import_private_messages = import_settings['private_messages']- @import_polls = import_settings['polls']- @import_bookmarks = import_settings['bookmarks']- @import_passwords = import_settings['passwords']- @import_likes = import_settings['likes']+ @import_anonymous_users = import_settings["anonymous_users"]+ @import_attachments = import_settings["attachments"]+ @import_private_messages = import_settings["private_messages"]+ @import_polls = import_settings["polls"]+ @import_bookmarks = import_settings["bookmarks"]+ @import_passwords = import_settings["passwords"]+ @import_likes = import_settings["likes"]- avatar_settings = import_settings['avatars']- @import_uploaded_avatars = avatar_settings['uploaded']- @import_remote_avatars = avatar_settings['remote']- @import_gallery_avatars = avatar_settings['gallery']+ avatar_settings = import_settings["avatars"]+ @import_uploaded_avatars = avatar_settings["uploaded"]+ @import_remote_avatars = avatar_settings["remote"]+ @import_gallery_avatars = avatar_settings["gallery"]- @use_bbcode_to_md = import_settings['use_bbcode_to_md']+ @use_bbcode_to_md = import_settings["use_bbcode_to_md"]- @original_site_prefix = import_settings['site_prefix']['original']- @new_site_prefix = import_settings['site_prefix']['new']- @base_dir = import_settings['phpbb_base_dir']- @permalinks = PermalinkSettings.new(import_settings['permalinks'])+ @original_site_prefix = import_settings["site_prefix"]["original"]+ @new_site_prefix = import_settings["site_prefix"]["new"]+ @base_dir = import_settings["phpbb_base_dir"]+ @permalinks = PermalinkSettings.new(import_settings["permalinks"])- @username_as_name = import_settings['username_as_name']- @emojis = import_settings.fetch('emojis', [])- @custom_fields = import_settings.fetch('custom_fields', [])+ @username_as_name = import_settings["username_as_name"]+ @emojis = import_settings.fetch("emojis", [])+ @custom_fields = import_settings.fetch("custom_fields", [])- @database = DatabaseSettings.new(yaml['database'])+ @database = DatabaseSettings.new(yaml["database"])enddef prefix(val)@@ -87,7 +88,7 @@ module ImportScripts::PhpBB3def trust_level_for_posts(rank, trust_level: 0)if @rank_mapping.present?@rank_mapping.each do |key, value|- trust_level = [trust_level, key.gsub('trust_level_', '').to_i].max if rank >= value+ trust_level = [trust_level, key.gsub("trust_level_", "").to_i].max if rank >= valueendend@@ -106,14 +107,14 @@ module ImportScripts::PhpBB3attr_reader :batch_sizedef initialize(yaml)- @type = yaml['type']- @host = yaml['host']- @port = yaml['port']- @username = yaml['username']- @password = yaml['password']- @schema = yaml['schema']- @table_prefix = yaml['table_prefix']- @batch_size = yaml['batch_size']+ @type = yaml["type"]+ @host = yaml["host"]+ @port = yaml["port"]+ @username = yaml["username"]+ @password = yaml["password"]+ @schema = yaml["schema"]+ @table_prefix = yaml["table_prefix"]+ @batch_size = yaml["batch_size"]endend@@ -124,10 +125,10 @@ module ImportScripts::PhpBB3attr_reader :normalization_prefixdef initialize(yaml)- @create_category_links = yaml['categories']- @create_topic_links = yaml['topics']- @create_post_links = yaml['posts']- @normalization_prefix = yaml['prefix']+ @create_category_links = yaml["categories"]+ @create_topic_links = yaml["topics"]+ @create_post_links = yaml["posts"]+ @normalization_prefix = yaml["prefix"]endendenddiff --git a/script/import_scripts/phpbb3/support/smiley_processor.rb b/script/import_scripts/phpbb3/support/smiley_processor.rbindex 618f99ddd22..4a861fc4c10 100644--- a/script/import_scripts/phpbb3/support/smiley_processor.rb+++ b/script/import_scripts/phpbb3/support/smiley_processor.rb@@ -18,15 +18,16 @@ module ImportScripts::PhpBB3def replace_smilies(text)# :) is encoded as <!-- s:) --><img src="{SMILIES_PATH}/icon_e_smile.gif" alt=":)" title="Smile" /><!-- s:) -->- text.gsub!(/<!-- s(\S+) --><img src="\{SMILIES_PATH\}\/.+?" alt=".*?" title=".*?" \/><!-- s?\S+ -->/) do- emoji($1)- end+ text.gsub!(+ /<!-- s(\S+) --><img src="\{SMILIES_PATH\}\/.+?" alt=".*?" title=".*?" \/><!-- s?\S+ -->/,+ ) { emoji($1) }enddef emoji(smiley_code)@smiley_map.fetch(smiley_code) dosmiley = @database.get_smiley(smiley_code)- emoji = upload_smiley(smiley_code, smiley[:smiley_url], smiley_code, smiley[:emotion]) if smiley+ emoji =+ upload_smiley(smiley_code, smiley[:smiley_url], smiley_code, smiley[:emotion]) if smileyemoji || smiley_as_text(smiley_code)endend@@ -35,37 +36,34 @@ module ImportScripts::PhpBB3def add_default_smilies{- [':D', ':-D', ':grin:'] => ':smiley:',- [':)', ':-)', ':smile:'] => ':slight_smile:',- [';)', ';-)', ':wink:'] => ':wink:',- [':(', ':-(', ':sad:'] => ':frowning:',- [':o', ':-o', ':eek:'] => ':astonished:',- [':shock:'] => ':open_mouth:',- [':?', ':-?', ':???:'] => ':confused:',- ['8)', '8-)', ':cool:'] => ':sunglasses:',- [':lol:'] => ':laughing:',- [':x', ':-x', ':mad:'] => ':angry:',- [':P', ':-P', ':razz:'] => ':stuck_out_tongue:',- [':oops:'] => ':blush:',- [':cry:'] => ':cry:',- [':evil:'] => ':imp:',- [':twisted:'] => ':smiling_imp:',- [':roll:'] => ':unamused:',- [':!:'] => ':exclamation:',- [':?:'] => ':question:',- [':idea:'] => ':bulb:',- [':arrow:'] => ':arrow_right:',- [':|', ':-|'] => ':neutral_face:',- [':geek:'] => ':nerd:'- }.each do |smilies, emoji|- smilies.each { |smiley| @smiley_map[smiley] = emoji }- end+ %w[:D :-D :grin:] => ":smiley:",+ %w[:) :-) :smile:] => ":slight_smile:",+ %w[;) ;-) :wink:] => ":wink:",+ %w[:( :-( :sad:] => ":frowning:",+ %w[:o :-o :eek:] => ":astonished:",+ [":shock:"] => ":open_mouth:",+ %w[:? :-? :???:] => ":confused:",+ %w[8) 8-) :cool:] => ":sunglasses:",+ [":lol:"] => ":laughing:",+ %w[:x :-x :mad:] => ":angry:",+ %w[:P :-P :razz:] => ":stuck_out_tongue:",+ [":oops:"] => ":blush:",+ [":cry:"] => ":cry:",+ [":evil:"] => ":imp:",+ [":twisted:"] => ":smiling_imp:",+ [":roll:"] => ":unamused:",+ [":!:"] => ":exclamation:",+ [":?:"] => ":question:",+ [":idea:"] => ":bulb:",+ [":arrow:"] => ":arrow_right:",+ %w[:| :-|] => ":neutral_face:",+ [":geek:"] => ":nerd:",+ }.each { |smilies, emoji| smilies.each { |smiley| @smiley_map[smiley] = emoji } }enddef add_configured_smilies(emojis)emojis.each do |emoji, smilies|- Array.wrap(smilies)- .each { |smiley| @smiley_map[smiley] = ":#{emoji}:" }+ Array.wrap(smilies).each { |smiley| @smiley_map[smiley] = ":#{emoji}:" }endenddiff --git a/script/import_scripts/phpbb3/support/text_processor.rb b/script/import_scripts/phpbb3/support/text_processor.rbindex 62547b4f156..fb788bf5370 100644--- a/script/import_scripts/phpbb3/support/text_processor.rb+++ b/script/import_scripts/phpbb3/support/text_processor.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require_relative 'bbcode/xml_to_markdown'+require_relative "bbcode/xml_to_markdown"module ImportScripts::PhpBB3class TextProcessor@@ -14,7 +14,9 @@ module ImportScripts::PhpBB3@database = database@smiley_processor = smiley_processor@he = HTMLEntities.new- @use_xml_to_markdown = phpbb_config[:phpbb_version].start_with?('3.2') || phpbb_config[:phpbb_version].start_with?('3.3')+ @use_xml_to_markdown =+ phpbb_config[:phpbb_version].start_with?("3.2") ||+ phpbb_config[:phpbb_version].start_with?("3.3")@settings = settings@new_site_prefix = settings.new_site_prefix@@ -25,24 +27,27 @@ module ImportScripts::PhpBB3if @use_xml_to_markdownunreferenced_attachments = attachments&.dup- converter = BBCode::XmlToMarkdown.new(- raw,- username_from_user_id: lambda { |user_id| @lookup.find_username_by_import_id(user_id) },- smilie_to_emoji: lambda { |smilie| @smiley_processor.emoji(smilie).dup },- quoted_post_from_post_id: lambda { |post_id| @lookup.topic_lookup_from_imported_post_id(post_id) },- upload_md_from_file: (lambda do |filename, index|- unreferenced_attachments[index] = nil- attachments.fetch(index, filename).dup- end if attachments),- url_replacement: nil,- allow_inline_code: false- )+ converter =+ BBCode::XmlToMarkdown.new(+ raw,+ username_from_user_id: lambda { |user_id| @lookup.find_username_by_import_id(user_id) },+ smilie_to_emoji: lambda { |smilie| @smiley_processor.emoji(smilie).dup },+ quoted_post_from_post_id:+ lambda { |post_id| @lookup.topic_lookup_from_imported_post_id(post_id) },+ upload_md_from_file:+ (+ lambda do |filename, index|+ unreferenced_attachments[index] = nil+ attachments.fetch(index, filename).dup+ end if attachments+ ),+ url_replacement: nil,+ allow_inline_code: false,+ )text = converter.convert- text.gsub!(@short_internal_link_regexp) do |link|- replace_internal_link(link, $1, $2)- end+ text.gsub!(@short_internal_link_regexp) { |link| replace_internal_link(link, $1, $2) }add_unreferenced_attachments(text, unreferenced_attachments)else@@ -50,9 +55,7 @@ module ImportScripts::PhpBB3text = CGI.unescapeHTML(text)clean_bbcodes(text)- if @settings.use_bbcode_to_md- text = bbcode_to_md(text)- end+ text = bbcode_to_md(text) if @settings.use_bbcode_to_mdprocess_smilies(text)process_links(text)process_lists(text)@@ -65,11 +68,19 @@ module ImportScripts::PhpBB3enddef process_post(raw, attachments)- process_raw_text(raw, attachments) rescue raw+ begin+ process_raw_text(raw, attachments)+ rescue StandardError+ raw+ endenddef process_private_msg(raw, attachments)- process_raw_text(raw, attachments) rescue raw+ begin+ process_raw_text(raw, attachments)+ rescue StandardError+ raw+ endendprotected@@ -78,10 +89,10 @@ module ImportScripts::PhpBB3# Many phpbb bbcode tags have a hash attached to them. Examples:# [url=https://google.com:1qh1i7ky]click here[/url:1qh1i7ky]# [quote="cybereality":b0wtlzex]Some text.[/quote:b0wtlzex]- text.gsub!(/:(?:\w{5,8})\]/, ']')+ text.gsub!(/:(?:\w{5,8})\]/, "]")# remove color tags- text.gsub!(/\[\/?color(=#?[a-z0-9]*)?\]/i, "")+ text.gsub!(%r{\[/?color(=#?[a-z0-9]*)?\]}i, "")enddef bbcode_to_md(text)@@ -101,23 +112,19 @@ module ImportScripts::PhpBB3# Internal forum links can have this forms:# for topics: <!-- l --><a class="postlink-local" href="https://example.com/forums/viewtopic.php?f=26&t=3412">viewtopic.php?f=26&t=3412</a><!-- l --># for posts: <!-- l --><a class="postlink-local" href="https://example.com/forums/viewtopic.php?p=1732#p1732">viewtopic.php?p=1732#p1732</a><!-- l -->- text.gsub!(@long_internal_link_regexp) do |link|- replace_internal_link(link, $1, $2)- end+ text.gsub!(@long_internal_link_regexp) { |link| replace_internal_link(link, $1, $2) }# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- text.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/i, '[\2](\1)')+ text.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}i, '[\2](\1)')# Replace internal forum links that aren't in the <!-- l --> format- text.gsub!(@short_internal_link_regexp) do |link|- replace_internal_link(link, $1, $2)- end+ text.gsub!(@short_internal_link_regexp) { |link| replace_internal_link(link, $1, $2) }# phpBB shortens link text like this, which breaks our markdown processing:# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- text.gsub!(/\[http(s)?:\/\/(www\.)?/i, '[')+ text.gsub!(%r{\[http(s)?://(www\.)?}i, "[")enddef replace_internal_link(link, import_topic_id, import_post_id)@@ -144,19 +151,20 @@ module ImportScripts::PhpBB3# convert list tags to ul and list=1 tags to ol# list=a is not supported, so handle it like list=1# list=9 and list=x have the same result as list=1 and list=a- text.gsub!(/\[list\](.*?)\[\/list:u\]/mi) do- $1.gsub(/\[\*\](.*?)\[\/\*:m\]\n*/mi) { "* #{$1}\n" }+ text.gsub!(%r{\[list\](.*?)\[/list:u\]}mi) do+ $1.gsub(%r{\[\*\](.*?)\[/\*:m\]\n*}mi) { "* #{$1}\n" }end- text.gsub!(/\[list=.*?\](.*?)\[\/list:o\]/mi) do- $1.gsub(/\[\*\](.*?)\[\/\*:m\]\n*/mi) { "1. #{$1}\n" }+ text.gsub!(%r{\[list=.*?\](.*?)\[/list:o\]}mi) do+ $1.gsub(%r{\[\*\](.*?)\[/\*:m\]\n*}mi) { "1. #{$1}\n" }endend# This replaces existing [attachment] BBCodes with the corresponding HTML tags for Discourse.# All attachments that haven't been referenced in the text are appended to the end of the text.def process_attachments(text, attachments)- attachment_regexp = /\[attachment=([\d])+\]<!-- [\w]+ -->([^<]+)<!-- [\w]+ -->\[\/attachment\]?/i+ attachment_regexp =+ %r{\[attachment=([\d])+\]<!-- [\w]+ -->([^<]+)<!-- [\w]+ -->\[/attachment\]?}iunreferenced_attachments = attachments.duptext.gsub!(attachment_regexp) do@@ -178,29 +186,34 @@ module ImportScripts::PhpBB3enddef create_internal_link_regexps(original_site_prefix)- host = original_site_prefix.gsub('.', '\.')- link_regex = "http(?:s)?://#{host}/viewtopic\\.php\\?(?:\\S*)(?:t=(\\d+)|p=(\\d+)(?:#p\\d+)?)(?:[^\\s\\)\\]]*)"-- @long_internal_link_regexp = Regexp.new(%Q|<!-- l --><a(?:.+)href="#{link_regex}"(?:.*)</a><!-- l -->|, Regexp::IGNORECASE)+ host = original_site_prefix.gsub(".", '\.')+ link_regex =+ "http(?:s)?://#{host}/viewtopic\\.php\\?(?:\\S*)(?:t=(\\d+)|p=(\\d+)(?:#p\\d+)?)(?:[^\\s\\)\\]]*)"++ @long_internal_link_regexp =+ Regexp.new(+ %Q|<!-- l --><a(?:.+)href="#{link_regex}"(?:.*)</a><!-- l -->|,+ Regexp::IGNORECASE,+ )@short_internal_link_regexp = Regexp.new(link_regex, Regexp::IGNORECASE)enddef process_code(text)- text.gsub!(/<span class="syntax.*?>(.*?)<\/span>/) { "#{$1}" }- text.gsub!(/\[code(=[a-z]*)?\](.*?)\[\/code\]/i) { "[code]\n#{@he.decode($2)}\n[/code]" }- text.gsub!(/<br \/>/, "\n")+ text.gsub!(%r{<span class="syntax.*?>(.*?)</span>}) { "#{$1}" }+ text.gsub!(%r{\[code(=[a-z]*)?\](.*?)\[/code\]}i) { "[code]\n#{@he.decode($2)}\n[/code]" }+ text.gsub!(%r{<br />}, "\n")textenddef fix_markdown(text)- text.gsub!(/(\n*\[\/?quote.*?\]\n*)/mi) { |q| "\n#{q.strip}\n" }+ text.gsub!(%r{(\n*\[/?quote.*?\]\n*)}mi) { |q| "\n#{q.strip}\n" }text.gsub!(/^!\[[^\]]*\]\([^\]]*\)$/i) { |img| "\n#{img.strip}\n" } # space out images single on linetextenddef process_videos(text)# [YOUTUBE]<id>[/YOUTUBE]- text.gsub(/\[youtube\](.+?)\[\/youtube\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ text.gsub(%r{\[youtube\](.+?)\[/youtube\]}i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }textendenddiff --git a/script/import_scripts/punbb.rb b/script/import_scripts/punbb.rbindex 64cce9bbcf4..b73e4f71281 100644--- a/script/import_scripts/punbb.rb+++ b/script/import_scripts/punbb.rb@@ -7,19 +7,19 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/punbb.rbclass ImportScripts::PunBB < ImportScripts::Base-PUNBB_DB = "punbb_db"BATCH_SIZE = 1000def initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- password: "pa$$word",- database: PUNBB_DB- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ password: "pa$$word",+ database: PUNBB_DB,+ )enddef execute@@ -30,36 +30,41 @@ class ImportScripts::PunBB < ImportScripts::Baseenddef import_users- puts '', "creating users"+ puts "", "creating users"- total_count = mysql_query("SELECT count(*) count FROM users;").first['count']+ total_count = mysql_query("SELECT count(*) count FROM users;").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT id, username, realname name, url website, email email, registered created_at,+ results =+ mysql_query(+ "SELECT id, username, realname name, url website, email email, registered created_at,registration_ip registration_ip_address, last_visit last_visit_time, last_email_sent last_emailed_at,last_email_sent last_emailed_at, location, group_idFROM usersLIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1next if all_records_exist? :users, results.map { |u| u["id"].to_i }create_users(results, total: total_count, offset: offset) do |user|- { id: user['id'],- email: user['email'],- username: user['username'],- name: user['name'],- created_at: Time.zone.at(user['created_at']),- website: user['website'],- registration_ip_address: user['registration_ip_address'],- last_seen_at: Time.zone.at(user['last_visit_time']),- last_emailed_at: user['last_emailed_at'] == nil ? 0 : Time.zone.at(user['last_emailed_at']),- location: user['location'],- moderator: user['group_id'] == 4,- admin: user['group_id'] == 1 }+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ name: user["name"],+ created_at: Time.zone.at(user["created_at"]),+ website: user["website"],+ registration_ip_address: user["registration_ip_address"],+ last_seen_at: Time.zone.at(user["last_visit_time"]),+ last_emailed_at:+ user["last_emailed_at"] == nil ? 0 : Time.zone.at(user["last_emailed_at"]),+ location: user["location"],+ moderator: user["group_id"] == 4,+ admin: user["group_id"] == 1,+ }endendend@@ -67,33 +72,34 @@ class ImportScripts::PunBB < ImportScripts::Basedef import_categoriesputs "", "importing top level categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT id, cat_name name, disp_position positionFROM categoriesORDER BY id ASC- ").to_a+ ",+ ).to_a- create_categories(categories) do |category|- {- id: category["id"],- name: category["name"]- }- end+ create_categories(categories) { |category| { id: category["id"], name: category["name"] } }puts "", "importing children categories..."- children_categories = mysql_query("+ children_categories =+ mysql_query(+ "SELECT id, forum_name name, forum_desc description, disp_position position, cat_id parent_category_idFROM forumsORDER BY id- ").to_a+ ",+ ).to_acreate_categories(children_categories) do |category|{- id: "child##{category['id']}",+ id: "child##{category["id"]}",name: category["name"],description: category["description"],- parent_category_id: category_id_from_imported_category_id(category["parent_category_id"])+ parent_category_id: category_id_from_imported_category_id(category["parent_category_id"]),}endend@@ -104,7 +110,9 @@ class ImportScripts::PunBB < ImportScripts::Basetotal_count = mysql_query("SELECT count(*) count from posts").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.id id,t.id topic_id,t.forum_id category_id,@@ -119,29 +127,30 @@ class ImportScripts::PunBB < ImportScripts::BaseORDER BY p.postedLIMIT #{BATCH_SIZE}OFFSET #{offset};- ").to_a+ ",+ ).to_abreak if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|skip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_punbb_post(m['raw'], m['id'])- mapped[:created_at] = Time.zone.at(m['created_at'])+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_punbb_post(m["raw"], m["id"])+ mapped[:created_at] = Time.zone.at(m["created_at"])- if m['id'] == m['first_post_id']- mapped[:category] = category_id_from_imported_category_id("child##{m['category_id']}")- mapped[:title] = CGI.unescapeHTML(m['title'])+ if m["id"] == m["first_post_id"]+ mapped[:category] = category_id_from_imported_category_id("child##{m["category_id"]}")+ mapped[:title] = CGI.unescapeHTML(m["title"])else- parent = topic_lookup_from_imported_post_id(m['first_post_id'])+ parent = topic_lookup_from_imported_post_id(m["first_post_id"])if parentmapped[:topic_id] = parent[:topic_id]else- puts "Parent post #{m['first_post_id']} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"+ puts "Parent post #{m["first_post_id"]} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"skip = trueendend@@ -152,16 +161,16 @@ class ImportScripts::PunBB < ImportScripts::Baseenddef suspend_users- puts '', "updating banned users"+ puts "", "updating banned users"banned = 0failed = 0- total = mysql_query("SELECT count(*) count FROM bans").first['count']+ total = mysql_query("SELECT count(*) count FROM bans").first["count"]system_user = Discourse.system_usermysql_query("SELECT username, email FROM bans").each do |b|- user = User.find_by_email(b['email'])+ user = User.find_by_email(b["email"])if useruser.suspended_at = Time.nowuser.suspended_till = 200.years.from_now@@ -174,7 +183,7 @@ class ImportScripts::PunBB < ImportScripts::Basefailed += 1endelse- puts "Not found: #{b['email']}"+ puts "Not found: #{b["email"]}"failed += 1end@@ -189,15 +198,15 @@ class ImportScripts::PunBB < ImportScripts::Bases.gsub!(/<!-- s(\S+) -->(?:.*)<!-- s(?:\S+) -->/, '\1')# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- s.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/, '[\2](\1)')+ s.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}, '[\2](\1)')# Many phpbb bbcode tags have a hash attached to them. Examples:# [url=https://google.com:1qh1i7ky]click here[/url:1qh1i7ky]# [quote="cybereality":b0wtlzex]Some text.[/quote:b0wtlzex]- s.gsub!(/:(?:\w{8})\]/, ']')+ s.gsub!(/:(?:\w{8})\]/, "]")# Remove mybb video tags.- s.gsub!(/(^\[video=.*?\])|(\[\/video\]$)/, '')+ s.gsub!(%r{(^\[video=.*?\])|(\[/video\]$)}, "")s = CGI.unescapeHTML(s)@@ -205,7 +214,7 @@ class ImportScripts::PunBB < ImportScripts::Base# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- s.gsub!(/\[http(s)?:\/\/(www\.)?/, '[')+ s.gsub!(%r{\[http(s)?://(www\.)?}, "[")senddiff --git a/script/import_scripts/quandora/export.rb b/script/import_scripts/quandora/export.rbindex e1f87b7ec32..fbbe146ca6c 100644--- a/script/import_scripts/quandora/export.rb+++ b/script/import_scripts/quandora/export.rb@@ -1,25 +1,25 @@# frozen_string_literal: true-require 'yaml'-require_relative 'quandora_api'+require "yaml"+require_relative "quandora_api"def load_config(file)- config = YAML::load_file(File.join(__dir__, file))- @domain = config['domain']- @username = config['username']- @password = config['password']+ config = YAML.load_file(File.join(__dir__, file))+ @domain = config["domain"]+ @username = config["username"]+ @password = config["password"]enddef exportapi = QuandoraApi.new @domain, @username, @passwordbases = api.list_basesbases.each do |base|- question_list = api.list_questions base['objectId'], 1000+ question_list = api.list_questions base["objectId"], 1000question_list.each do |q|- question_id = q['uid']+ question_id = q["uid"]question = api.get_question question_id- File.open("output/#{question_id}.json", 'w') do |f|- puts question['title']+ File.open("output/#{question_id}.json", "w") do |f|+ puts question["title"]f.write question.to_jsonf.closeenddiff --git a/script/import_scripts/quandora/import.rb b/script/import_scripts/quandora/import.rbindex 7df8be302c4..a3dc5dfe290 100644--- a/script/import_scripts/quandora/import.rb+++ b/script/import_scripts/quandora/import.rb@@ -1,10 +1,9 @@# frozen_string_literal: true-require_relative './quandora_question.rb'+require_relative "./quandora_question.rb"require File.expand_path(File.dirname(__FILE__) + "/../base.rb")class ImportScripts::Quandora < ImportScripts::Base-JSON_FILES_DIR = "output"def initialize@@ -12,8 +11,8 @@ class ImportScripts::Quandora < ImportScripts::Base@system_user = Discourse.system_user@questions = []Dir.foreach(JSON_FILES_DIR) do |filename|- next if filename == ('.') || filename == ('..')- question = File.read JSON_FILES_DIR + '/' + filename+ next if filename == (".") || filename == ("..")+ question = File.read JSON_FILES_DIR + "/" + filename@questions << questionendend@@ -33,9 +32,7 @@ class ImportScripts::Quandora < ImportScripts::Baseq = QuandoraQuestion.new questionimport_users q.userscreated_topic = import_topic q.topic- if created_topic- import_posts q.replies, created_topic.topic_id- end+ import_posts q.replies, created_topic.topic_id if created_topictopics += 1print_status topics, totalend@@ -43,9 +40,7 @@ class ImportScripts::Quandora < ImportScripts::Baseenddef import_users(users)- users.each do |user|- create_user user, user[:id]- end+ users.each { |user| create_user user, user[:id] }enddef import_topic(topic)@@ -54,7 +49,7 @@ class ImportScripts::Quandora < ImportScripts::Basepost = Post.find(post_id) # already imported this topicelsetopic[:user_id] = user_id_from_imported_user_id(topic[:author_id]) || -1- topic[:category] = 'quandora-import'+ topic[:category] = "quandora-import"post = create_post(topic, topic[:id])@@ -68,9 +63,7 @@ class ImportScripts::Quandora < ImportScripts::Baseenddef import_posts(posts, topic_id)- posts.each do |post|- import_post post, topic_id- end+ posts.each { |post| import_post post, topic_id }enddef import_post(post, topic_id)@@ -91,6 +84,4 @@ class ImportScripts::Quandora < ImportScripts::Baseendend-if __FILE__ == $0- ImportScripts::Quandora.new.perform-end+ImportScripts::Quandora.new.perform if __FILE__ == $0diff --git a/script/import_scripts/quandora/quandora_api.rb b/script/import_scripts/quandora/quandora_api.rbindex 747473bb793..9a743087720 100644--- a/script/import_scripts/quandora/quandora_api.rb+++ b/script/import_scripts/quandora/quandora_api.rb@@ -1,10 +1,9 @@# frozen_string_literal: true-require 'base64'-require 'json'+require "base64"+require "json"class QuandoraApi-attr_accessor :domain, :username, :passworddef initialize(domain, username, password)@@ -38,18 +37,18 @@ class QuandoraApidef list_basesresponse = request list_bases_url- response['data']+ response["data"]enddef list_questions(kb_id, limit = nil)url = list_questions_url(kb_id, limit)response = request url- response['data']['result']+ response["data"]["result"]enddef get_question(question_id)url = "#{base_url @domain}/q/#{question_id}"response = request url- response['data']+ response["data"]endenddiff --git a/script/import_scripts/quandora/quandora_question.rb b/script/import_scripts/quandora/quandora_question.rbindex abbaaeeda6a..767dad16fc9 100644--- a/script/import_scripts/quandora/quandora_question.rb+++ b/script/import_scripts/quandora/quandora_question.rb@@ -1,28 +1,27 @@# frozen_string_literal: true-require 'json'-require 'cgi'-require 'time'+require "json"+require "cgi"+require "time"class QuandoraQuestion-def initialize(question_json)@question = JSON.parse question_jsonenddef topictopic = {}- topic[:id] = @question['uid']- topic[:author_id] = @question['author']['uid']- topic[:title] = unescape @question['title']- topic[:raw] = unescape @question['content']- topic[:created_at] = Time.parse @question['created']+ topic[:id] = @question["uid"]+ topic[:author_id] = @question["author"]["uid"]+ topic[:title] = unescape @question["title"]+ topic[:raw] = unescape @question["content"]+ topic[:created_at] = Time.parse @question["created"]topicenddef usersusers = {}- user = user_from_author @question['author']+ user = user_from_author @question["author"]users[user[:id]] = userreplies.each do |reply|user = user_from_author reply[:author]@@ -32,12 +31,12 @@ class QuandoraQuestionenddef user_from_author(author)- email = author['email']- email = "#{author['uid']}@noemail.com" unless email+ email = author["email"]+ email = "#{author["uid"]}@noemail.com" unless emailuser = {}- user[:id] = author['uid']- user[:name] = "#{author['firstName']} #{author['lastName']}"+ user[:id] = author["uid"]+ user[:name] = "#{author["firstName"]} #{author["lastName"]}"user[:email] = emailuser[:staged] = trueuser@@ -45,26 +44,20 @@ class QuandoraQuestiondef repliesposts = []- answers = @question['answersList']- comments = @question['comments']- comments.each_with_index do |comment, i|- posts << post_from_comment(comment, i, @question)- end+ answers = @question["answersList"]+ comments = @question["comments"]+ comments.each_with_index { |comment, i| posts << post_from_comment(comment, i, @question) }answers.each do |answer|posts << post_from_answer(answer)- comments = answer['comments']- comments.each_with_index do |comment, i|- posts << post_from_comment(comment, i, answer)- end+ comments = answer["comments"]+ comments.each_with_index { |comment, i| posts << post_from_comment(comment, i, answer) }endorder_replies postsenddef order_replies(posts)posts = posts.sort_by { |p| p[:created_at] }- posts.each_with_index do |p, i|- p[:post_number] = i + 2- end+ posts.each_with_index { |p, i| p[:post_number] = i + 2 }posts.each do |p|parent = posts.select { |pp| pp[:id] == p[:parent_id] }p[:reply_to_post_number] = parent[0][:post_number] if parent.size > 0@@ -74,35 +67,35 @@ class QuandoraQuestiondef post_from_answer(answer)post = {}- post[:id] = answer['uid']- post[:parent_id] = @question['uid']- post[:author] = answer['author']- post[:author_id] = answer['author']['uid']- post[:raw] = unescape answer['content']- post[:created_at] = Time.parse answer['created']+ post[:id] = answer["uid"]+ post[:parent_id] = @question["uid"]+ post[:author] = answer["author"]+ post[:author_id] = answer["author"]["uid"]+ post[:raw] = unescape answer["content"]+ post[:created_at] = Time.parse answer["created"]postenddef post_from_comment(comment, index, parent)- if comment['created']- created_at = Time.parse comment['created']+ if comment["created"]+ created_at = Time.parse comment["created"]else- created_at = Time.parse parent['created']+ created_at = Time.parse parent["created"]end- parent_id = parent['uid']- parent_id = "#{parent['uid']}-#{index - 1}" if index > 0+ parent_id = parent["uid"]+ parent_id = "#{parent["uid"]}-#{index - 1}" if index > 0post = {}- id = "#{parent['uid']}-#{index}"+ id = "#{parent["uid"]}-#{index}"post[:id] = idpost[:parent_id] = parent_id- post[:author] = comment['author']- post[:author_id] = comment['author']['uid']- post[:raw] = unescape comment['text']+ post[:author] = comment["author"]+ post[:author_id] = comment["author"]["uid"]+ post[:raw] = unescape comment["text"]post[:created_at] = created_atpostend- private+ privatedef unescape(html)return nil unless htmldiff --git a/script/import_scripts/quandora/test/test_data.rb b/script/import_scripts/quandora/test/test_data.rbindex 3166d6c44da..172e753e31d 100644--- a/script/import_scripts/quandora/test/test_data.rb+++ b/script/import_scripts/quandora/test/test_data.rb@@ -1,5 +1,6 @@- # frozen_string_literal: true- BASES = '{+# frozen_string_literal: true+BASES =+ '{"type" : "kbase","data" : [ {"objectId" : "90b1ccf3-35aa-4d6f-848e-e7c122d92c58",@@ -9,7 +10,8 @@} ]}'- QUESTIONS = '{+QUESTIONS =+ '{"type": "question-search-result","data": {"totalSize": 445,@@ -50,7 +52,8 @@}}'- QUESTION = '{+QUESTION =+ '{"type" : "question","data" : {"uid" : "de20ed0a-5fe5-48a5-9c14-d854f9af99f1",diff --git a/script/import_scripts/quandora/test/test_quandora_api.rb b/script/import_scripts/quandora/test/test_quandora_api.rbindex 784ba4fb855..a167ca9ad7a 100644--- a/script/import_scripts/quandora/test/test_quandora_api.rb+++ b/script/import_scripts/quandora/test/test_quandora_api.rb@@ -1,21 +1,20 @@# frozen_string_literal: true-require 'minitest/autorun'-require 'yaml'-require_relative '../quandora_api.rb'-require_relative './test_data.rb'+require "minitest/autorun"+require "yaml"+require_relative "../quandora_api.rb"+require_relative "./test_data.rb"class TestQuandoraApi < Minitest::Test-DEBUG = falsedef initialize(args)- config = YAML::load_file(File.join(__dir__, 'config.yml'))- @domain = config['domain']- @username = config['username']- @password = config['password']- @kb_id = config['kb_id']- @question_id = config['question_id']+ config = YAML.load_file(File.join(__dir__, "config.yml"))+ @domain = config["domain"]+ @username = config["username"]+ @password = config["password"]+ @kb_id = config["kb_id"]+ @question_id = config["question_id"]super argsend@@ -30,19 +29,19 @@ class TestQuandoraApi < Minitest::Testenddef test_base_url- assert_equal 'https://mydomain.quandora.com/m/json', @quandora.base_url('mydomain')+ assert_equal "https://mydomain.quandora.com/m/json", @quandora.base_url("mydomain")enddef test_auth_header- user = 'Aladdin'- password = 'open sesame'+ user = "Aladdin"+ password = "open sesame"auth_header = @quandora.auth_header user, password- assert_equal 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==', auth_header[:Authorization]+ assert_equal "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", auth_header[:Authorization]enddef test_list_bases_element_has_expected_structureelement = @quandora.list_bases[0]- expected = JSON.parse(BASES)['data'][0]+ expected = JSON.parse(BASES)["data"][0]debug elementcheck_keys expected, elementend@@ -50,24 +49,24 @@ class TestQuandoraApi < Minitest::Testdef test_list_questions_has_expected_structureresponse = @quandora.list_questions @kb_id, 1debug response- check_keys JSON.parse(QUESTIONS)['data']['result'][0], response[0]+ check_keys JSON.parse(QUESTIONS)["data"]["result"][0], response[0]enddef test_get_question_has_expected_structurequestion = @quandora.get_question @question_id- expected = JSON.parse(QUESTION)['data']+ expected = JSON.parse(QUESTION)["data"]check_keys expected, question- expected_comment = expected['comments'][0]- actual_comment = question['comments'][0]+ expected_comment = expected["comments"][0]+ actual_comment = question["comments"][0]check_keys expected_comment, actual_comment- expected_answer = expected['answersList'][1]- actual_answer = question['answersList'][0]+ expected_answer = expected["answersList"][1]+ actual_answer = question["answersList"][0]check_keys expected_answer, actual_answer- expected_answer_comment = expected_answer['comments'][0]- actual_answer_comment = actual_answer['comments'][0]+ expected_answer_comment = expected_answer["comments"][0]+ actual_answer_comment = actual_answer["comments"][0]check_keys expected_answer_comment, actual_answer_commentend@@ -75,18 +74,16 @@ class TestQuandoraApi < Minitest::Testdef check_keys(expected, actual)msg = "### caller[0]:\nKey not found in actual keys: #{actual.keys}\n"- expected.keys.each do |k|- assert (actual.keys.include? k), "#{k}"- end+ expected.keys.each { |k| assert (actual.keys.include? k), "#{k}" }enddef debug(message, show = false)if show || DEBUG- puts '### ' + caller[0]- puts ''+ puts "### " + caller[0]+ puts ""puts message- puts ''- puts ''+ puts ""+ puts ""endendenddiff --git a/script/import_scripts/quandora/test/test_quandora_question.rb b/script/import_scripts/quandora/test/test_quandora_question.rbindex 28b5dd9885c..6044951c5b8 100644--- a/script/import_scripts/quandora/test/test_quandora_question.rb+++ b/script/import_scripts/quandora/test/test_quandora_question.rb@@ -1,47 +1,46 @@# frozen_string_literal: true-require 'minitest/autorun'-require 'cgi'-require 'time'-require_relative '../quandora_question.rb'-require_relative './test_data.rb'+require "minitest/autorun"+require "cgi"+require "time"+require_relative "../quandora_question.rb"+require_relative "./test_data.rb"class TestQuandoraQuestion < Minitest::Test-def setup- @data = JSON.parse(QUESTION)['data']+ @data = JSON.parse(QUESTION)["data"]@question = QuandoraQuestion.new @data.to_jsonenddef test_topictopic = @question.topic- assert_equal @data['uid'], topic[:id]- assert_equal @data['author']['uid'], topic[:author_id]- assert_equal unescape(@data['title']), topic[:title]- assert_equal unescape(@data['content']), topic[:raw]- assert_equal Time.parse(@data['created']), topic[:created_at]+ assert_equal @data["uid"], topic[:id]+ assert_equal @data["author"]["uid"], topic[:author_id]+ assert_equal unescape(@data["title"]), topic[:title]+ assert_equal unescape(@data["content"]), topic[:raw]+ assert_equal Time.parse(@data["created"]), topic[:created_at]enddef test_user_from_authorauthor = {}- author['uid'] = 'uid'- author['firstName'] = 'Joe'- author['lastName'] = 'Schmoe'- author['email'] = '[email protected]'+ author["uid"] = "uid"+ author["firstName"] = "Joe"+ author["lastName"] = "Schmoe"+ author["email"] = "[email protected]"user = @question.user_from_author author- assert_equal 'uid', user[:id]- assert_equal 'Joe Schmoe', user[:name]- assert_equal '[email protected]', user[:email]+ assert_equal "uid", user[:id]+ assert_equal "Joe Schmoe", user[:name]+ assert_equal "[email protected]", user[:email]assert_equal true, user[:staged]enddef test_user_from_author_with_no_emailauthor = {}- author['uid'] = 'foo'+ author["uid"] = "foo"user = @question.user_from_author author- assert_equal '[email protected]', user[:email]+ assert_equal "[email protected]", user[:email]enddef test_replies@@ -57,77 +56,77 @@ class TestQuandoraQuestion < Minitest::Testassert_equal nil, replies[2][:reply_to_post_number]assert_equal 4, replies[3][:reply_to_post_number]assert_equal 3, replies[4][:reply_to_post_number]- assert_equal '2013-01-07 04:59:56 UTC', replies[0][:created_at].to_s- assert_equal '2013-01-08 16:49:32 UTC', replies[1][:created_at].to_s- assert_equal '2016-01-20 15:38:55 UTC', replies[2][:created_at].to_s- assert_equal '2016-01-21 15:38:55 UTC', replies[3][:created_at].to_s- assert_equal '2016-01-22 15:38:55 UTC', replies[4][:created_at].to_s+ assert_equal "2013-01-07 04:59:56 UTC", replies[0][:created_at].to_s+ assert_equal "2013-01-08 16:49:32 UTC", replies[1][:created_at].to_s+ assert_equal "2016-01-20 15:38:55 UTC", replies[2][:created_at].to_s+ assert_equal "2016-01-21 15:38:55 UTC", replies[3][:created_at].to_s+ assert_equal "2016-01-22 15:38:55 UTC", replies[4][:created_at].to_senddef test_post_from_answeranswer = {}- answer['uid'] = 'uid'- answer['content'] = 'content'- answer['created'] = '2013-01-06T18:24:54.62Z'- answer['author'] = { 'uid' => 'auid' }+ answer["uid"] = "uid"+ answer["content"] = "content"+ answer["created"] = "2013-01-06T18:24:54.62Z"+ answer["author"] = { "uid" => "auid" }post = @question.post_from_answer answer- assert_equal 'uid', post[:id]+ assert_equal "uid", post[:id]assert_equal @question.topic[:id], post[:parent_id]- assert_equal answer['author'], post[:author]- assert_equal 'auid', post[:author_id]- assert_equal 'content', post[:raw]- assert_equal Time.parse('2013-01-06T18:24:54.62Z'), post[:created_at]+ assert_equal answer["author"], post[:author]+ assert_equal "auid", post[:author_id]+ assert_equal "content", post[:raw]+ assert_equal Time.parse("2013-01-06T18:24:54.62Z"), post[:created_at]enddef test_post_from_commentcomment = {}- comment['text'] = 'text'- comment['created'] = '2013-01-06T18:24:54.62Z'- comment['author'] = { 'uid' => 'auid' }- parent = { 'uid' => 'parent-uid' }+ comment["text"] = "text"+ comment["created"] = "2013-01-06T18:24:54.62Z"+ comment["author"] = { "uid" => "auid" }+ parent = { "uid" => "parent-uid" }post = @question.post_from_comment comment, 0, parent- assert_equal 'parent-uid-0', post[:id]- assert_equal 'parent-uid', post[:parent_id]- assert_equal comment['author'], post[:author]- assert_equal 'auid', post[:author_id]- assert_equal 'text', post[:raw]- assert_equal Time.parse('2013-01-06T18:24:54.62Z'), post[:created_at]+ assert_equal "parent-uid-0", post[:id]+ assert_equal "parent-uid", post[:parent_id]+ assert_equal comment["author"], post[:author]+ assert_equal "auid", post[:author_id]+ assert_equal "text", post[:raw]+ assert_equal Time.parse("2013-01-06T18:24:54.62Z"), post[:created_at]enddef test_post_from_comment_uses_parent_created_if_necessarycomment = {}- comment['author'] = { 'uid' => 'auid' }- parent = { 'created' => '2013-01-06T18:24:54.62Z' }+ comment["author"] = { "uid" => "auid" }+ parent = { "created" => "2013-01-06T18:24:54.62Z" }post = @question.post_from_comment comment, 0, parent- assert_equal Time.parse('2013-01-06T18:24:54.62Z'), post[:created_at]+ assert_equal Time.parse("2013-01-06T18:24:54.62Z"), post[:created_at]enddef test_post_from_comment_uses_previous_comment_as_parentcomment = {}- comment['author'] = { 'uid' => 'auid' }- parent = { 'uid' => 'parent-uid', 'created' => '2013-01-06T18:24:54.62Z' }+ comment["author"] = { "uid" => "auid" }+ parent = { "uid" => "parent-uid", "created" => "2013-01-06T18:24:54.62Z" }post = @question.post_from_comment comment, 1, parent- assert_equal 'parent-uid-1', post[:id]- assert_equal 'parent-uid-0', post[:parent_id]- assert_equal Time.parse('2013-01-06T18:24:54.62Z'), post[:created_at]+ assert_equal "parent-uid-1", post[:id]+ assert_equal "parent-uid-0", post[:parent_id]+ assert_equal Time.parse("2013-01-06T18:24:54.62Z"), post[:created_at]enddef test_usersusers = @question.usersassert_equal 5, users.size- assert_equal 'Ida Inquisitive', users[0][:name]- assert_equal 'Harry Helpful', users[1][:name]- assert_equal 'Sam Smarty-Pants', users[2][:name]- assert_equal 'Greta Greatful', users[3][:name]- assert_equal 'Eddy Excited', users[4][:name]+ assert_equal "Ida Inquisitive", users[0][:name]+ assert_equal "Harry Helpful", users[1][:name]+ assert_equal "Sam Smarty-Pants", users[2][:name]+ assert_equal "Greta Greatful", users[3][:name]+ assert_equal "Eddy Excited", users[4][:name]endprivatediff --git a/script/import_scripts/question2answer.rb b/script/import_scripts/question2answer.rbindex acd5b70bebf..3820b8050bd 100644--- a/script/import_scripts/question2answer.rb+++ b/script/import_scripts/question2answer.rb@@ -1,21 +1,21 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'-require 'php_serialize' # https://github.com/jqr/php-serialize+require "htmlentities"+require "php_serialize" # https://github.com/jqr/php-serializeclass ImportScripts::Question2Answer < ImportScripts::BaseBATCH_SIZE = 1000# CHANGE THESE BEFORE RUNNING THE IMPORTER- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "qa_db"- DB_PW ||= ENV['DB_PW'] || ""- DB_USER ||= ENV['DB_USER'] || "root"- TIMEZONE ||= ENV['TIMEZONE'] || "America/Los_Angeles"- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "qa_"+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "qa_db"+ DB_PW ||= ENV["DB_PW"] || ""+ DB_USER ||= ENV["DB_USER"] || "root"+ TIMEZONE ||= ENV["TIMEZONE"] || "America/Los_Angeles"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "qa_"def initializesuper@@ -26,12 +26,8 @@ class ImportScripts::Question2Answer < ImportScripts::Base@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- password: DB_PW,- database: DB_NAME- )+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, password: DB_PW, database: DB_NAME)enddef execute@@ -51,11 +47,16 @@ class ImportScripts::Question2Answer < ImportScripts::Base# only import users that have posted or voted on Q2A# if you want to import all users, just leave out the WHERE and everything after it (and remove line 95 as well)- user_count = mysql_query("SELECT COUNT(userid) count FROM #{TABLE_PREFIX}users u WHERE EXISTS (SELECT 1 FROM #{TABLE_PREFIX}posts p WHERE p.userid=u.userid) or EXISTS (SELECT 1 FROM #{TABLE_PREFIX}uservotes uv WHERE u.userid=uv.userid)").first["count"]+ user_count =+ mysql_query(+ "SELECT COUNT(userid) count FROM #{TABLE_PREFIX}users u WHERE EXISTS (SELECT 1 FROM #{TABLE_PREFIX}posts p WHERE p.userid=u.userid) or EXISTS (SELECT 1 FROM #{TABLE_PREFIX}uservotes uv WHERE u.userid=uv.userid)",+ ).first[+ "count"+ ]last_user_id = -1batches(BATCH_SIZE) do |offset|- users = mysql_query(<<-SQL+ users = mysql_query(<<-SQL).to_aSELECT u.userid AS id, u.email, u.handle AS username, u.created AS created_at, u.loggedin AS last_sign_in_at, u.avatarblobidFROM #{TABLE_PREFIX}users uWHERE u.userid > #{last_user_id}@@ -63,7 +64,6 @@ class ImportScripts::Question2Answer < ImportScripts::BaseORDER BY u.useridLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?last_user_id = users[-1]["id"]@@ -73,18 +73,17 @@ class ImportScripts::Question2Answer < ImportScripts::Baseemail = user["email"].presenceusername = @htmlentities.decode(user["email"]).strip.split("@").first- avatar_url = "https://your_image_bucket/#{user['cdn_slug']}" if user['cdn_slug']+ avatar_url = "https://your_image_bucket/#{user["cdn_slug"]}" if user["cdn_slug"]{id: user["id"],- name: "#{user['username']}",- username: "#{user['username']}",- password: user['password'],+ name: "#{user["username"]}",+ username: "#{user["username"]}",+ password: user["password"],email: email,created_at: user["created_at"],last_seen_at: user["last_sign_in_at"],- post_create_action: proc do |u|- @old_username_to_new_usernames[user["username"]] = u.username- end+ post_create_action:+ proc { |u| @old_username_to_new_usernames[user["username"]] = u.username },}endend@@ -93,7 +92,10 @@ class ImportScripts::Question2Answer < ImportScripts::Basedef import_categoriesputs "", "importing top level categories..."- categories = mysql_query("SELECT categoryid, parentid, title, position FROM #{TABLE_PREFIX}categories ORDER BY categoryid").to_a+ categories =+ mysql_query(+ "SELECT categoryid, parentid, title, position FROM #{TABLE_PREFIX}categories ORDER BY categoryid",+ ).to_atop_level_categories = categories.select { |c| c["parentid"].nil? }@@ -101,7 +103,7 @@ class ImportScripts::Question2Answer < ImportScripts::Base{id: category["categoryid"],name: @htmlentities.decode(category["title"]).strip,- position: category["position"]+ position: category["position"],}end@@ -122,7 +124,7 @@ class ImportScripts::Question2Answer < ImportScripts::Baseid: category["categoryid"],name: @htmlentities.decode(category["title"]).strip,position: category["position"],- parent_category_id: category_id_from_imported_category_id(category["parentid"])+ parent_category_id: category_id_from_imported_category_id(category["parentid"]),}endend@@ -130,12 +132,15 @@ class ImportScripts::Question2Answer < ImportScripts::Basedef import_topicsputs "", "importing topics..."- topic_count = mysql_query("SELECT COUNT(postid) count FROM #{TABLE_PREFIX}posts WHERE type = 'Q'").first["count"]+ topic_count =+ mysql_query("SELECT COUNT(postid) count FROM #{TABLE_PREFIX}posts WHERE type = 'Q'").first[+ "count"+ ]last_topic_id = -1batches(BATCH_SIZE) do |offset|- topics = mysql_query(<<-SQL+ topics = mysql_query(<<-SQL).to_aSELECT p.postid, p.type, p.categoryid, p.closedbyid, p.userid postuserid, p.views, p.created, p.title, p.content rawFROM #{TABLE_PREFIX}posts pWHERE type = 'Q'@@ -143,7 +148,6 @@ class ImportScripts::Question2Answer < ImportScripts::BaseORDER BY p.postidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if topics.empty?@@ -179,20 +183,19 @@ class ImportScripts::Question2Answer < ImportScripts::Baseif topic.present?title_slugified = slugify(thread["title"], false, 50) if thread["title"].present?url_slug = "qa/#{thread["postid"]}/#{title_slugified}" if thread["title"].present?- Permalink.create(url: url_slug, topic_id: topic[:topic_id].to_i) if url_slug.present? && topic[:topic_id].present?+ if url_slug.present? && topic[:topic_id].present?+ Permalink.create(url: url_slug, topic_id: topic[:topic_id].to_i)+ endendend-endenddef slugify(title, ascii_only, max_length)- words = title.downcase.gsub(/[^a-zA-Z0-9\s]/, '').split(" ")+ words = title.downcase.gsub(/[^a-zA-Z0-9\s]/, "").split(" ")word_lengths = {}- words.each_with_index do |word, idx|- word_lengths[idx] = word.length- end+ words.each_with_index { |word, idx| word_lengths[idx] = word.length }remaining = max_lengthif word_lengths.inject(0) { |sum, (_, v)| sum + v } > remaining@@ -211,17 +214,16 @@ class ImportScripts::Question2Answer < ImportScripts::Basedef import_postsputs "", "importing posts..."- post_count = mysql_query(<<-SQL+ post_count = mysql_query(<<-SQL).first["count"]SELECT COUNT(postid) countFROM #{TABLE_PREFIX}posts pWHERE p.parentid IS NOT NULLSQL- ).first["count"]last_post_id = -1batches(BATCH_SIZE) do |offset|- posts = mysql_query(<<-SQL+ posts = mysql_query(<<-SQL).to_aSELECT p.postid, p.type, p.parentid, p.categoryid, p.closedbyid, p.userid, p.views, p.created, p.title, p.content,parent.type AS parenttype, parent.parentid AS qidFROM #{TABLE_PREFIX}posts p@@ -233,7 +235,6 @@ class ImportScripts::Question2Answer < ImportScripts::BaseORDER BY p.postidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if posts.empty?last_post_id = posts[-1]["postid"]@@ -250,11 +251,11 @@ class ImportScripts::Question2Answer < ImportScripts::Base# this works as long as comments can not have a comment as parent# it's always Q-A Q-C or A-C- if post['type'] == 'A' # for answers the question/topic is always the parent+ if post["type"] == "A" # for answers the question/topic is always the parenttopic = topic_lookup_from_imported_post_id("thread-#{post["parentid"]}")next if topic.nil?else- if post['parenttype'] == 'Q' # for comments to questions, the question/topic is the parent as well+ if post["parenttype"] == "Q" # for comments to questions, the question/topic is the parent as welltopic = topic_lookup_from_imported_post_id("thread-#{post["parentid"]}")next if topic.nil?else # for comments to answers, the question/topic is the parent of the parent@@ -284,7 +285,7 @@ class ImportScripts::Question2Answer < ImportScripts::Baseans = mysql_query("select postid, selchildid from qa_posts where selchildid is not null").to_aans.each do |answer|begin- post = Post.find_by(id: post_id_from_imported_post_id("#{answer['selchildid']}"))+ post = Post.find_by(id: post_id_from_imported_post_id("#{answer["selchildid"]}"))post.custom_fields["is_accepted_answer"] = "true"post.savetopic = Topic.find(post.topic_id)@@ -293,20 +294,18 @@ class ImportScripts::Question2Answer < ImportScripts::Baserescue => eputs "error acting on post #{e}"end-endenddef import_likesputs "", "importing likes..."- likes = mysql_query(<<-SQL+ likes = mysql_query(<<-SQL).to_aSELECT postid, useridFROM #{TABLE_PREFIX}uservotes uWHERE u.vote=1SQL- ).to_alikes.each do |like|- post = Post.find_by(id: post_id_from_imported_post_id("thread-#{like['postid']}"))+ post = Post.find_by(id: post_id_from_imported_post_id("thread-#{like["postid"]}"))user = User.find_by(id: user_id_from_imported_user_id(like["userid"]))beginPostActionCreator.like(user, post) if user && post@@ -340,10 +339,10 @@ class ImportScripts::Question2Answer < ImportScripts::Basedef preprocess_post_raw(raw)return "" if raw.blank?- raw.gsub!(/<a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a>/i, '[\2](\1)')- raw.gsub!(/<p>(.+?)<\/p>/im) { "#{$1}\n\n" }- raw.gsub!('<br />', "\n")- raw.gsub!(/<strong>(.*?)<\/strong>/im, '[b]\1[/b]')+ raw.gsub!(%r{<a(?:.+)href="(\S+)"(?:.*)>(.+)</a>}i, '[\2](\1)')+ raw.gsub!(%r{<p>(.+?)</p>}im) { "#{$1}\n\n" }+ raw.gsub!("<br />", "\n")+ raw.gsub!(%r{<strong>(.*?)</strong>}im, '[b]\1[/b]')# decode HTML entitiesraw = @htmlentities.decode(raw)@@ -355,22 +354,22 @@ class ImportScripts::Question2Answer < ImportScripts::Base# [HTML]...[/HTML]raw.gsub!(/\[html\]/i, "\n```html\n")- raw.gsub!(/\[\/html\]/i, "\n```\n")+ raw.gsub!(%r{\[/html\]}i, "\n```\n")# [PHP]...[/PHP]raw.gsub!(/\[php\]/i, "\n```php\n")- raw.gsub!(/\[\/php\]/i, "\n```\n")+ raw.gsub!(%r{\[/php\]}i, "\n```\n")# [HIGHLIGHT="..."]raw.gsub!(/\[highlight="?(\w+)"?\]/i) { "\n```#{$1.downcase}\n" }# [CODE]...[/CODE]# [HIGHLIGHT]...[/HIGHLIGHT]- raw.gsub!(/\[\/?code\]/i, "\n```\n")- raw.gsub!(/\[\/?highlight\]/i, "\n```\n")+ raw.gsub!(%r{\[/?code\]}i, "\n```\n")+ raw.gsub!(%r{\[/?highlight\]}i, "\n```\n")# [SAMP]...[/SAMP]- raw.gsub!(/\[\/?samp\]/i, "`")+ raw.gsub!(%r{\[/?samp\]}i, "`")# replace all chevrons with HTML entities# NOTE: must be done@@ -385,16 +384,16 @@ class ImportScripts::Question2Answer < ImportScripts::Baseraw.gsub!("\u2603", ">")# [URL=...]...[/URL]- raw.gsub!(/\[url="?([^"]+?)"?\](.*?)\[\/url\]/im) { "[#{$2.strip}](#{$1})" }- raw.gsub!(/\[url="?(.+?)"?\](.+)\[\/url\]/im) { "[#{$2.strip}](#{$1})" }+ raw.gsub!(%r{\[url="?([^"]+?)"?\](.*?)\[/url\]}im) { "[#{$2.strip}](#{$1})" }+ raw.gsub!(%r{\[url="?(.+?)"?\](.+)\[/url\]}im) { "[#{$2.strip}](#{$1})" }# [URL]...[/URL]# [MP3]...[/MP3]- raw.gsub!(/\[\/?url\]/i, "")- raw.gsub!(/\[\/?mp3\]/i, "")+ raw.gsub!(%r{\[/?url\]}i, "")+ raw.gsub!(%r{\[/?mp3\]}i, "")# [MENTION]<username>[/MENTION]- raw.gsub!(/\[mention\](.+?)\[\/mention\]/i) do+ raw.gsub!(%r{\[mention\](.+?)\[/mention\]}i) doold_username = $1if @old_username_to_new_usernames.has_key?(old_username)old_username = @old_username_to_new_usernames[old_username]@@ -403,31 +402,31 @@ class ImportScripts::Question2Answer < ImportScripts::Baseend# [FONT=blah] and [COLOR=blah]- raw.gsub!(/\[FONT=.*?\](.*?)\[\/FONT\]/im, '\1')- raw.gsub!(/\[COLOR=.*?\](.*?)\[\/COLOR\]/im, '\1')- raw.gsub!(/\[COLOR=#.*?\](.*?)\[\/COLOR\]/im, '\1')+ raw.gsub!(%r{\[FONT=.*?\](.*?)\[/FONT\]}im, '\1')+ raw.gsub!(%r{\[COLOR=.*?\](.*?)\[/COLOR\]}im, '\1')+ raw.gsub!(%r{\[COLOR=#.*?\](.*?)\[/COLOR\]}im, '\1')- raw.gsub!(/\[SIZE=.*?\](.*?)\[\/SIZE\]/im, '\1')- raw.gsub!(/\[h=.*?\](.*?)\[\/h\]/im, '\1')+ raw.gsub!(%r{\[SIZE=.*?\](.*?)\[/SIZE\]}im, '\1')+ raw.gsub!(%r{\[h=.*?\](.*?)\[/h\]}im, '\1')# [CENTER]...[/CENTER]- raw.gsub!(/\[CENTER\](.*?)\[\/CENTER\]/im, '\1')+ raw.gsub!(%r{\[CENTER\](.*?)\[/CENTER\]}im, '\1')# [INDENT]...[/INDENT]- raw.gsub!(/\[INDENT\](.*?)\[\/INDENT\]/im, '\1')- raw.gsub!(/\[TABLE\](.*?)\[\/TABLE\]/im, '\1')- raw.gsub!(/\[TR\](.*?)\[\/TR\]/im, '\1')- raw.gsub!(/\[TD\](.*?)\[\/TD\]/im, '\1')- raw.gsub!(/\[TD="?.*?"?\](.*?)\[\/TD\]/im, '\1')+ raw.gsub!(%r{\[INDENT\](.*?)\[/INDENT\]}im, '\1')+ raw.gsub!(%r{\[TABLE\](.*?)\[/TABLE\]}im, '\1')+ raw.gsub!(%r{\[TR\](.*?)\[/TR\]}im, '\1')+ raw.gsub!(%r{\[TD\](.*?)\[/TD\]}im, '\1')+ raw.gsub!(%r{\[TD="?.*?"?\](.*?)\[/TD\]}im, '\1')# [QUOTE]...[/QUOTE]- raw.gsub!(/\[quote\](.+?)\[\/quote\]/im) { |quote|- quote.gsub!(/\[quote\](.+?)\[\/quote\]/im) { "\n#{$1}\n" }+ raw.gsub!(%r{\[quote\](.+?)\[/quote\]}im) do |quote|+ quote.gsub!(%r{\[quote\](.+?)\[/quote\]}im) { "\n#{$1}\n" }quote.gsub!(/\n(.+?)/) { "\n> #{$1}" }- }+ end# [QUOTE=<username>]...[/QUOTE]- raw.gsub!(/\[quote=([^;\]]+)\](.+?)\[\/quote\]/im) do+ raw.gsub!(%r{\[quote=([^;\]]+)\](.+?)\[/quote\]}im) doold_username, quote = $1, $2if @old_username_to_new_usernames.has_key?(old_username)old_username = @old_username_to_new_usernames[old_username]@@ -436,31 +435,33 @@ class ImportScripts::Question2Answer < ImportScripts::Baseend# [YOUTUBE]<id>[/YOUTUBE]- raw.gsub!(/\[youtube\](.+?)\[\/youtube\]/i) { "\n//youtu.be/#{$1}\n" }+ raw.gsub!(%r{\[youtube\](.+?)\[/youtube\]}i) { "\n//youtu.be/#{$1}\n" }# [VIDEO=youtube;<id>]...[/VIDEO]- raw.gsub!(/\[video=youtube;([^\]]+)\].*?\[\/video\]/i) { "\n//youtu.be/#{$1}\n" }+ raw.gsub!(%r{\[video=youtube;([^\]]+)\].*?\[/video\]}i) { "\n//youtu.be/#{$1}\n" }# More Additions ....# [spoiler=Some hidden stuff]SPOILER HERE!![/spoiler]- raw.gsub!(/\[spoiler="?(.+?)"?\](.+?)\[\/spoiler\]/im) { "\n#{$1}\n[spoiler]#{$2}[/spoiler]\n" }+ raw.gsub!(%r{\[spoiler="?(.+?)"?\](.+?)\[/spoiler\]}im) do+ "\n#{$1}\n[spoiler]#{$2}[/spoiler]\n"+ end# [IMG][IMG]http://i63.tinypic.com/akga3r.jpg[/IMG][/IMG]- raw.gsub!(/\[IMG\]\[IMG\](.+?)\[\/IMG\]\[\/IMG\]/i) { "[IMG]#{$1}[/IMG]" }+ raw.gsub!(%r{\[IMG\]\[IMG\](.+?)\[/IMG\]\[/IMG\]}i) { "[IMG]#{$1}[/IMG]" }# convert list tags to ul and list=1 tags to ol# (basically, we're only missing list=a here...)# (https://meta.discourse.org/t/phpbb-3-importer-old/17397)- raw.gsub!(/\[list\](.*?)\[\/list\]/im, '[ul]\1[/ul]')- raw.gsub!(/\[list=1\](.*?)\[\/list\]/im, '[ol]\1[/ol]')- raw.gsub!(/\[list\](.*?)\[\/list:u\]/im, '[ul]\1[/ul]')- raw.gsub!(/\[list=1\](.*?)\[\/list:o\]/im, '[ol]\1[/ol]')+ raw.gsub!(%r{\[list\](.*?)\[/list\]}im, '[ul]\1[/ul]')+ raw.gsub!(%r{\[list=1\](.*?)\[/list\]}im, '[ol]\1[/ol]')+ raw.gsub!(%r{\[list\](.*?)\[/list:u\]}im, '[ul]\1[/ul]')+ raw.gsub!(%r{\[list=1\](.*?)\[/list:o\]}im, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:- raw.gsub!(/\[\*\]\n/, '')- raw.gsub!(/\[\*\](.*?)\[\/\*:m\]/, '[li]\1[/li]')+ raw.gsub!(/\[\*\]\n/, "")+ raw.gsub!(%r{\[\*\](.*?)\[/\*:m\]}, '[li]\1[/li]')raw.gsub!(/\[\*\](.*?)\n/, '[li]\1[/li]')- raw.gsub!(/\[\*=1\]/, '')+ raw.gsub!(/\[\*=1\]/, "")raw.strip!raw@@ -468,7 +469,7 @@ class ImportScripts::Question2Answer < ImportScripts::Basedef postprocess_post_raw(raw)# [QUOTE=<username>;<post_id>]...[/QUOTE]- raw.gsub!(/\[quote=([^;]+);(\d+)\](.+?)\[\/quote\]/im) do+ raw.gsub!(%r{\[quote=([^;]+);(\d+)\](.+?)\[/quote\]}im) doold_username, post_id, quote = $1, $2, $3if @old_username_to_new_usernames.has_key?(old_username)@@ -477,7 +478,7 @@ class ImportScripts::Question2Answer < ImportScripts::Baseif topic_lookup = topic_lookup_from_imported_post_id(post_id)post_number = topic_lookup[:post_number]- topic_id = topic_lookup[:topic_id]+ topic_id = topic_lookup[:topic_id]"\n[quote=\"#{old_username},post:#{post_number},topic:#{topic_id}\"]\n#{quote}\n[/quote]\n"else"\n[quote=\"#{old_username}\"]\n#{quote}\n[/quote]\n"@@ -485,11 +486,11 @@ class ImportScripts::Question2Answer < ImportScripts::Baseend# remove attachments- raw.gsub!(/\[attach[^\]]*\]\d+\[\/attach\]/i, "")+ raw.gsub!(%r{\[attach[^\]]*\]\d+\[/attach\]}i, "")# [THREAD]<thread_id>[/THREAD]# ==> http://my.discourse.org/t/slug/<topic_id>- raw.gsub!(/\[thread\](\d+)\[\/thread\]/i) do+ raw.gsub!(%r{\[thread\](\d+)\[/thread\]}i) dothread_id = $1if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")topic_lookup[:url]@@ -500,7 +501,7 @@ class ImportScripts::Question2Answer < ImportScripts::Base# [THREAD=<thread_id>]...[/THREAD]# ==> [...](http://my.discourse.org/t/slug/<topic_id>)- raw.gsub!(/\[thread=(\d+)\](.+?)\[\/thread\]/i) do+ raw.gsub!(%r{\[thread=(\d+)\](.+?)\[/thread\]}i) dothread_id, link = $1, $2if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")url = topic_lookup[:url]@@ -512,7 +513,7 @@ class ImportScripts::Question2Answer < ImportScripts::Base# [POST]<post_id>[/POST]# ==> http://my.discourse.org/t/slug/<topic_id>/<post_number>- raw.gsub!(/\[post\](\d+)\[\/post\]/i) do+ raw.gsub!(%r{\[post\](\d+)\[/post\]}i) dopost_id = $1if topic_lookup = topic_lookup_from_imported_post_id(post_id)topic_lookup[:url]@@ -523,7 +524,7 @@ class ImportScripts::Question2Answer < ImportScripts::Base# [POST=<post_id>]...[/POST]# ==> [...](http://my.discourse.org/t/<topic_slug>/<topic_id>/<post_number>)- raw.gsub!(/\[post=(\d+)\](.+?)\[\/post\]/i) do+ raw.gsub!(%r{\[post=(\d+)\](.+?)\[/post\]}i) dopost_id, link = $1, $2if topic_lookup = topic_lookup_from_imported_post_id(post_id)url = topic_lookup[:url]@@ -537,7 +538,7 @@ class ImportScripts::Question2Answer < ImportScripts::Baseenddef create_permalinks- puts '', 'Creating permalinks...'+ puts "", "Creating permalinks..."# topicsTopic.find_each do |topic|@@ -546,7 +547,11 @@ class ImportScripts::Question2Answer < ImportScripts::Baseif tcf && tcf["import_id"]question_id = tcf["import_id"][/thread-(\d)/, 0]url = "#{question_id}"- Permalink.create(url: url, topic_id: topic.id) rescue nil+ begin+ Permalink.create(url: url, topic_id: topic.id)+ rescue StandardError+ nil+ endendend@@ -555,11 +560,21 @@ class ImportScripts::Question2Answer < ImportScripts::Baseccf = category.custom_fieldsif ccf && ccf["import_id"]- url = category.parent_category ? "#{category.parent_category.slug}/#{category.slug}" : category.slug- Permalink.create(url: url, category_id: category.id) rescue nil+ url =+ (+ if category.parent_category+ "#{category.parent_category.slug}/#{category.slug}"+ else+ category.slug+ end+ )+ begin+ Permalink.create(url: url, category_id: category.id)+ rescue StandardError+ nil+ endendend-enddef parse_timestamp(timestamp)@@ -569,7 +584,6 @@ class ImportScripts::Question2Answer < ImportScripts::Basedef mysql_query(sql)@client.query(sql, cache_rows: true)end-endImportScripts::Question2Answer.new.performdiff --git a/script/import_scripts/sfn.rb b/script/import_scripts/sfn.rbindex e9270813d72..e10c9c1b0aa 100644--- a/script/import_scripts/sfn.rb+++ b/script/import_scripts/sfn.rb@@ -8,7 +8,6 @@ require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Sfn < ImportScripts::Base-BATCH_SIZE = 100_000MIN_CREATED_AT = "2003-11-01"@@ -96,22 +95,27 @@ class ImportScripts::Sfn < ImportScripts::Baseusername: email.split("@")[0],bio_raw: bio,created_at: user["created_at"],- post_create_action: proc do |newuser|- next if user["avatar"].blank?-- avatar = Tempfile.new("sfn-avatar")- avatar.write(user["avatar"].encode("ASCII-8BIT").force_encoding("UTF-8"))- avatar.rewind-- upload = UploadCreator.new(avatar, "avatar.jpg").create_for(newuser.id)- if upload.persisted?- newuser.create_user_avatar- newuser.user_avatar.update(custom_upload_id: upload.id)- newuser.update(uploaded_avatar_id: upload.id)- end-- avatar.try(:close!) rescue nil- end+ post_create_action:+ proc do |newuser|+ next if user["avatar"].blank?++ avatar = Tempfile.new("sfn-avatar")+ avatar.write(user["avatar"].encode("ASCII-8BIT").force_encoding("UTF-8"))+ avatar.rewind++ upload = UploadCreator.new(avatar, "avatar.jpg").create_for(newuser.id)+ if upload.persisted?+ newuser.create_user_avatar+ newuser.user_avatar.update(custom_upload_id: upload.id)+ newuser.update(uploaded_avatar_id: upload.id)+ end++ begin+ avatar.try(:close!)+ rescue StandardError+ nil+ end+ end,}endend@@ -198,9 +202,7 @@ class ImportScripts::Sfn < ImportScripts::Basedef import_categoriesputs "", "importing categories..."- create_categories(NEW_CATEGORIES) do |category|- { id: category, name: category }- end+ create_categories(NEW_CATEGORIES) { |category| { id: category, name: category } }enddef import_topics@@ -234,7 +236,7 @@ class ImportScripts::Sfn < ImportScripts::BaseSQLbreak if topics.size < 1- next if all_records_exist? :posts, topics.map { |t| t['id'].to_i }+ next if all_records_exist? :posts, topics.map { |t| t["id"].to_i }create_posts(topics, total: topic_count, offset: offset) do |topic|next unless category_id = CATEGORY_MAPPING[topic["category_id"]]@@ -286,7 +288,7 @@ class ImportScripts::Sfn < ImportScripts::Basebreak if posts.size < 1- next if all_records_exist? :posts, posts.map { |p| p['id'].to_i }+ next if all_records_exist? :posts, posts.map { |p| p["id"].to_i }create_posts(posts, total: posts_count, offset: offset) do |post|next unless parent = topic_lookup_from_imported_post_id(post["topic_id"])@@ -307,7 +309,7 @@ class ImportScripts::Sfn < ImportScripts::Basedef cleanup_raw(raw)# fix some html- raw.gsub!(/<br\s*\/?>/i, "\n")+ raw.gsub!(%r{<br\s*/?>}i, "\n")# remove "This message has been cross posted to the following eGroups: ..."raw.gsub!(/^This message has been cross posted to the following eGroups: .+\n-{3,}/i, "")# remove signatures@@ -320,7 +322,6 @@ class ImportScripts::Sfn < ImportScripts::Base@client ||= Mysql2::Client.new(username: "root", database: "sfn")@client.query(sql)end-endImportScripts::Sfn.new.performdiff --git a/script/import_scripts/simplepress.rb b/script/import_scripts/simplepress.rbindex 3375258790f..b0aa7f5f114 100644--- a/script/import_scripts/simplepress.rb+++ b/script/import_scripts/simplepress.rb@@ -1,22 +1,17 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::SimplePress < ImportScripts::Base-- SIMPLE_PRESS_DB ||= ENV['SIMPLEPRESS_DB'] || "simplepress"+ SIMPLE_PRESS_DB ||= ENV["SIMPLEPRESS_DB"] || "simplepress"TABLE_PREFIX = "wp_sf"BATCH_SIZE ||= 1000def initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- database: SIMPLE_PRESS_DB,- )+ @client = Mysql2::Client.new(host: "localhost", username: "root", database: SIMPLE_PRESS_DB)SiteSetting.max_username_length = 50end@@ -32,10 +27,11 @@ class ImportScripts::SimplePress < ImportScripts::Baseputs "", "importing users..."last_user_id = -1- total_users = mysql_query("SELECT COUNT(*) count FROM wp_users WHERE user_email LIKE '%@%'").first["count"]+ total_users =+ mysql_query("SELECT COUNT(*) count FROM wp_users WHERE user_email LIKE '%@%'").first["count"]batches(BATCH_SIZE) do |offset|- users = mysql_query(<<-SQL+ users = mysql_query(<<-SQL).to_aSELECT ID id, user_nicename, display_name, user_email, user_registered, user_urlFROM wp_usersWHERE user_email LIKE '%@%'@@ -43,7 +39,6 @@ class ImportScripts::SimplePress < ImportScripts::BaseORDER BY idLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?@@ -55,13 +50,12 @@ class ImportScripts::SimplePress < ImportScripts::Baseuser_ids_sql = user_ids.join(",")users_description = {}- mysql_query(<<-SQL+ mysql_query(<<-SQL).each { |um| users_description[um["user_id"]] = um["description"] }SELECT user_id, meta_value descriptionFROM wp_usermetaWHERE user_id IN (#{user_ids_sql})AND meta_key = 'description'SQL- ).each { |um| users_description[um["user_id"]] = um["description"] }create_users(users, total: total_users, offset: offset) do |u|{@@ -71,7 +65,7 @@ class ImportScripts::SimplePress < ImportScripts::Basename: u["display_name"],created_at: u["user_registered"],website: u["user_url"],- bio_raw: users_description[u["id"]]+ bio_raw: users_description[u["id"]],}endend@@ -80,16 +74,20 @@ class ImportScripts::SimplePress < ImportScripts::Basedef import_categoriesputs "", "importing categories..."- categories = mysql_query(<<-SQL+ categories = mysql_query(<<-SQL)SELECT forum_id, forum_name, forum_seq, forum_desc, parentFROM #{TABLE_PREFIX}forumsORDER BY forum_idSQL- )create_categories(categories) do |c|- category = { id: c['forum_id'], name: CGI.unescapeHTML(c['forum_name']), description: CGI.unescapeHTML(c['forum_desc']), position: c['forum_seq'] }- if (parent_id = c['parent'].to_i) > 0+ category = {+ id: c["forum_id"],+ name: CGI.unescapeHTML(c["forum_name"]),+ description: CGI.unescapeHTML(c["forum_desc"]),+ position: c["forum_seq"],+ }+ if (parent_id = c["parent"].to_i) > 0category[:parent_category_id] = category_id_from_imported_category_id(parent_id)endcategory@@ -99,10 +97,15 @@ class ImportScripts::SimplePress < ImportScripts::Basedef import_topicsputs "", "creating topics"- total_count = mysql_query("SELECT COUNT(*) count FROM #{TABLE_PREFIX}posts WHERE post_index = 1").first["count"]+ total_count =+ mysql_query("SELECT COUNT(*) count FROM #{TABLE_PREFIX}posts WHERE post_index = 1").first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.post_id id,p.topic_id topic_id,t.forum_id category_id,@@ -119,23 +122,24 @@ class ImportScripts::SimplePress < ImportScripts::BaseORDER BY p.post_idLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|- created_at = Time.zone.at(m['post_time'])+ created_at = Time.zone.at(m["post_time"]){- id: m['id'],- user_id: user_id_from_imported_user_id(m['user_id']) || -1,- raw: process_simplepress_post(m['raw'], m['id']),+ id: m["id"],+ user_id: user_id_from_imported_user_id(m["user_id"]) || -1,+ raw: process_simplepress_post(m["raw"], m["id"]),created_at: created_at,- category: category_id_from_imported_category_id(m['category_id']),- title: CGI.unescapeHTML(m['title']),- views: m['views'],- pinned_at: m['pinned'] == 1 ? created_at : nil,+ category: category_id_from_imported_category_id(m["category_id"]),+ title: CGI.unescapeHTML(m["title"]),+ views: m["views"],+ pinned_at: m["pinned"] == 1 ? created_at : nil,}endend@@ -146,17 +150,24 @@ class ImportScripts::SimplePress < ImportScripts::Basetopic_first_post_id = {}- mysql_query("+ mysql_query(+ "SELECT t.topic_id, p.post_idFROM #{TABLE_PREFIX}topics tJOIN #{TABLE_PREFIX}posts p ON p.topic_id = t.topic_idWHERE p.post_index = 1- ").each { |r| topic_first_post_id[r["topic_id"]] = r["post_id"] }+ ",+ ).each { |r| topic_first_post_id[r["topic_id"]] = r["post_id"] }- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}posts WHERE post_index <> 1").first["count"]+ total_count =+ mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}posts WHERE post_index <> 1").first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- results = mysql_query("+ results =+ mysql_query(+ "SELECT p.post_id id,p.topic_id topic_id,p.user_id user_id,@@ -169,23 +180,24 @@ class ImportScripts::SimplePress < ImportScripts::BaseORDER BY p.post_idLIMIT #{BATCH_SIZE}OFFSET #{offset};- ")+ ",+ )break if results.size < 1- next if all_records_exist? :posts, results.map { |m| m['id'].to_i }+ next if all_records_exist? :posts, results.map { |m| m["id"].to_i }create_posts(results, total: total_count, offset: offset) do |m|- if parent = topic_lookup_from_imported_post_id(topic_first_post_id[m['topic_id']])+ if parent = topic_lookup_from_imported_post_id(topic_first_post_id[m["topic_id"]]){- id: m['id'],- user_id: user_id_from_imported_user_id(m['user_id']) || -1,+ id: m["id"],+ user_id: user_id_from_imported_user_id(m["user_id"]) || -1,topic_id: parent[:topic_id],- raw: process_simplepress_post(m['raw'], m['id']),- created_at: Time.zone.at(m['post_time']),+ raw: process_simplepress_post(m["raw"], m["id"]),+ created_at: Time.zone.at(m["post_time"]),}else- puts "Parent post #{m['topic_id']} doesn't exist. Skipping #{m["id"]}"+ puts "Parent post #{m["topic_id"]} doesn't exist. Skipping #{m["id"]}"nilendend@@ -196,28 +208,27 @@ class ImportScripts::SimplePress < ImportScripts::Bases = raw.dup# fix invalid byte sequence in UTF-8 (ArgumentError)- unless s.valid_encoding?- s.force_encoding("UTF-8")- end+ s.force_encoding("UTF-8") unless s.valid_encoding?# convert the quote line- s.gsub!(/\[quote='([^']+)'.*?pid='(\d+).*?\]/) {- "[quote=\"#{convert_username($1, import_id)}, " + post_id_to_post_num_and_topic($2, import_id) + '"]'- }+ s.gsub!(/\[quote='([^']+)'.*?pid='(\d+).*?\]/) do+ "[quote=\"#{convert_username($1, import_id)}, " ++ post_id_to_post_num_and_topic($2, import_id) + '"]'+ end# :) is encoded as <!-- s:) --><img src="{SMILIES_PATH}/icon_e_smile.gif" alt=":)" title="Smile" /><!-- s:) -->s.gsub!(/<!-- s(\S+) -->(?:.*)<!-- s(?:\S+) -->/, '\1')# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- s.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/, '[\2](\1)')+ s.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}, '[\2](\1)')# Many phpbb bbcode tags have a hash attached to them. Examples:# [url=https://google.com:1qh1i7ky]click here[/url:1qh1i7ky]# [quote="cybereality":b0wtlzex]Some text.[/quote:b0wtlzex]- s.gsub!(/:(?:\w{8})\]/, ']')+ s.gsub!(/:(?:\w{8})\]/, "]")# Remove mybb video tags.- s.gsub!(/(^\[video=.*?\])|(\[\/video\]$)/, '')+ s.gsub!(%r{(^\[video=.*?\])|(\[/video\]$)}, "")s = CGI.unescapeHTML(s)@@ -225,7 +236,7 @@ class ImportScripts::SimplePress < ImportScripts::Base# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)## Work around it for now:- s.gsub!(/\[http(s)?:\/\/(www\.)?/, '[')+ s.gsub!(%r{\[http(s)?://(www\.)?}, "[")send@@ -233,7 +244,6 @@ class ImportScripts::SimplePress < ImportScripts::Basedef mysql_query(sql)@client.query(sql, cache_rows: false)end-endImportScripts::SimplePress.new.performdiff --git a/script/import_scripts/smf1.rb b/script/import_scripts/smf1.rbindex 90ec314ea97..5d601f2fa2e 100644--- a/script/import_scripts/smf1.rb+++ b/script/import_scripts/smf1.rb@@ -5,21 +5,21 @@ require "htmlentities"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::Smf1 < ImportScripts::Base-- BATCH_SIZE ||= 5000+ BATCH_SIZE ||= 5000UPLOADS_DIR ||= ENV["UPLOADS_DIR"].presence- FORUM_URL ||= ENV["FORUM_URL"].presence+ FORUM_URL ||= ENV["FORUM_URL"].presencedef initialize- fail "UPLOADS_DIR env variable is required (example: '/path/to/attachments')" unless UPLOADS_DIR+ fail "UPLOADS_DIR env variable is required (example: '/path/to/attachments')" unless UPLOADS_DIRfail "FORUM_URL env variable is required (example: 'https://domain.com/forum')" unless FORUM_URL- @client = Mysql2::Client.new(- host: ENV["DB_HOST"] || "localhost",- username: ENV["DB_USER"] || "root",- password: ENV["DB_PW"],- database: ENV["DB_NAME"],- )+ @client =+ Mysql2::Client.new(+ host: ENV["DB_HOST"] || "localhost",+ username: ENV["DB_USER"] || "root",+ password: ENV["DB_PW"],+ database: ENV["DB_NAME"],+ )check_version!@@ -29,7 +29,12 @@ class ImportScripts::Smf1 < ImportScripts::Baseputs "Loading existing usernames..."- @old_to_new_usernames = UserCustomField.joins(:user).where(name: "import_username").pluck("value", "users.username").to_h+ @old_to_new_usernames =+ UserCustomField+ .joins(:user)+ .where(name: "import_username")+ .pluck("value", "users.username")+ .to_hputs "Loading pm mapping..."@@ -41,13 +46,14 @@ class ImportScripts::Smf1 < ImportScripts::Base.where("title NOT ILIKE 'Re: %'").group(:id).order(:id)- .pluck("string_agg(topic_allowed_users.user_id::text, ',' ORDER BY topic_allowed_users.user_id), title, topics.id")+ .pluck(+ "string_agg(topic_allowed_users.user_id::text, ',' ORDER BY topic_allowed_users.user_id), title, topics.id",+ ).each do |users, title, topic_id|- @pm_mapping[users] ||= {}- @pm_mapping[users][title] ||= []- @pm_mapping[users][title] << topic_id- end-+ @pm_mapping[users] ||= {}+ @pm_mapping[users][title] ||= []+ @pm_mapping[users][title] << topic_id+ endenddef execute@@ -71,7 +77,10 @@ class ImportScripts::Smf1 < ImportScripts::Baseenddef check_version!- version = mysql_query("SELECT value FROM smf_settings WHERE variable = 'smfVersion' LIMIT 1").first["value"]+ version =+ mysql_query("SELECT value FROM smf_settings WHERE variable = 'smfVersion' LIMIT 1").first[+ "value"+ ]fail "Incompatible version (#{version})" unless version&.start_with?("1.")end@@ -84,10 +93,7 @@ class ImportScripts::Smf1 < ImportScripts::Basecreate_groups(groups) do |g|next if g["groupName"].blank?- {- id: g["id_group"],- full_name: g["groupName"],- }+ { id: g["id_group"], full_name: g["groupName"] }endend@@ -98,7 +104,7 @@ class ImportScripts::Smf1 < ImportScripts::Basetotal = mysql_query("SELECT COUNT(*) count FROM smf_members").first["count"]batches(BATCH_SIZE) do |offset|- users = mysql_query(<<~SQL+ users = mysql_query(<<~SQL).to_aSELECT m.id_member, memberName, dateRegistered@@ -125,7 +131,6 @@ class ImportScripts::Smf1 < ImportScripts::BaseORDER BY m.id_memberLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?@@ -158,38 +163,45 @@ class ImportScripts::Smf1 < ImportScripts::Baseip_address: u["memberIP2"],active: u["is_activated"] == 1,approved: u["is_activated"] == 1,- post_create_action: proc do |user|- # usernames- @old_to_new_usernames[u["memberName"]] = user.username-- # groups- GroupUser.transaction do- group_ids.each do |gid|- (group_id = group_id_from_imported_group_id(gid)) && GroupUser.find_or_create_by(user: user, group_id: group_id)+ post_create_action:+ proc do |user|+ # usernames+ @old_to_new_usernames[u["memberName"]] = user.username++ # groups+ GroupUser.transaction do+ group_ids.each do |gid|+ (group_id = group_id_from_imported_group_id(gid)) &&+ GroupUser.find_or_create_by(user: user, group_id: group_id)+ endend- end- # avatar- avatar_url = nil+ # avatar+ avatar_url = nil- if u["avatar"].present?- if u["avatar"].start_with?("http")- avatar_url = u["avatar"]- elsif u["avatar"].start_with?("avatar_")- avatar_url = "#{FORUM_URL}/avatar-members/#{u["avatar"]}"+ if u["avatar"].present?+ if u["avatar"].start_with?("http")+ avatar_url = u["avatar"]+ elsif u["avatar"].start_with?("avatar_")+ avatar_url = "#{FORUM_URL}/avatar-members/#{u["avatar"]}"+ endend- end-- avatar_url ||= if u["attachmentType"] == 0 && u["id_attach"].present?- "#{FORUM_URL}/index.php?action=dlattach;attach=#{u["id_attach"]};type=avatar"- elsif u["attachmentType"] == 1 && u["filename"].present?- "#{FORUM_URL}/avatar-members/#{u["filename"]}"- end- if avatar_url.present?- UserAvatar.import_url_for_user(avatar_url, user) rescue nil- end- end+ avatar_url ||=+ if u["attachmentType"] == 0 && u["id_attach"].present?+ "#{FORUM_URL}/index.php?action=dlattach;attach=#{u["id_attach"]};type=avatar"+ elsif u["attachmentType"] == 1 && u["filename"].present?+ "#{FORUM_URL}/avatar-members/#{u["filename"]}"+ end++ if avatar_url.present?+ begin+ UserAvatar.import_url_for_user(avatar_url, user)+ rescue StandardError+ nil+ end+ end+ end,}endend@@ -198,7 +210,7 @@ class ImportScripts::Smf1 < ImportScripts::Basedef import_categoriesputs "", "Importing categories..."- categories = mysql_query(<<~SQL+ categories = mysql_query(<<~SQL).to_aSELECT id_board, id_parent, boardOrder@@ -207,7 +219,6 @@ class ImportScripts::Smf1 < ImportScripts::BaseFROM smf_boardsORDER BY id_parent, id_boardSQL- ).to_aparent_categories = categories.select { |c| c["id_parent"] == 0 }children_categories = categories.select { |c| c["id_parent"] != 0 }@@ -218,9 +229,13 @@ class ImportScripts::Smf1 < ImportScripts::Basename: c["name"],description: pre_process_raw(c["description"].presence),position: c["boardOrder"],- post_create_action: proc do |category|- Permalink.find_or_create_by(url: "forums/index.php/board,#{c["id_board"]}.0.html", category_id: category.id)- end,+ post_create_action:+ proc do |category|+ Permalink.find_or_create_by(+ url: "forums/index.php/board,#{c["id_board"]}.0.html",+ category_id: category.id,+ )+ end,}end@@ -231,9 +246,13 @@ class ImportScripts::Smf1 < ImportScripts::Basename: c["name"],description: pre_process_raw(c["description"].presence),position: c["boardOrder"],- post_create_action: proc do |category|- Permalink.find_or_create_by(url: "forums/index.php/board,#{c["id_board"]}.0.html", category_id: category.id)- end,+ post_create_action:+ proc do |category|+ Permalink.find_or_create_by(+ url: "forums/index.php/board,#{c["id_board"]}.0.html",+ category_id: category.id,+ )+ end,}endend@@ -245,7 +264,7 @@ class ImportScripts::Smf1 < ImportScripts::Basetotal = mysql_query("SELECT COUNT(*) count FROM smf_messages").first["count"]batches(BATCH_SIZE) do |offset|- posts = mysql_query(<<~SQL+ posts = mysql_query(<<~SQL).to_aSELECT m.id_msg, m.id_topic, m.id_board@@ -262,7 +281,6 @@ class ImportScripts::Smf1 < ImportScripts::BaseORDER BY m.id_msgLIMIT #{BATCH_SIZE}SQL- ).to_abreak if posts.empty?@@ -287,12 +305,18 @@ class ImportScripts::Smf1 < ImportScripts::Basepost[:views] = p["numViews"]post[:pinned_at] = created_at if p["isSticky"] == 1post[:post_create_action] = proc do |pp|- Permalink.find_or_create_by(url: "forums/index.php/topic,#{p["id_topic"]}.0.html", topic_id: pp.topic_id)+ Permalink.find_or_create_by(+ url: "forums/index.php/topic,#{p["id_topic"]}.0.html",+ topic_id: pp.topic_id,+ )endelsif parent = topic_lookup_from_imported_post_id(p["id_first_msg"])post[:topic_id] = parent[:topic_id]post[:post_create_action] = proc do |pp|- Permalink.find_or_create_by(url: "forums/index.php/topic,#{p["id_topic"]}.msg#{p["id_msg"]}.html", post_id: pp.id)+ Permalink.find_or_create_by(+ url: "forums/index.php/topic,#{p["id_topic"]}.msg#{p["id_msg"]}.html",+ post_id: pp.id,+ )endelsenext@@ -307,10 +331,15 @@ class ImportScripts::Smf1 < ImportScripts::Baseputs "", "Importing personal posts..."last_post_id = -1- total = mysql_query("SELECT COUNT(*) count FROM smf_personal_messages WHERE deletedBySender = 0").first["count"]+ total =+ mysql_query(+ "SELECT COUNT(*) count FROM smf_personal_messages WHERE deletedBySender = 0",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- posts = mysql_query(<<~SQL+ posts = mysql_query(<<~SQL).to_aSELECT id_pm, id_member_from, msgtime@@ -323,7 +352,6 @@ class ImportScripts::Smf1 < ImportScripts::BaseORDER BY id_pmLIMIT #{BATCH_SIZE}SQL- ).to_abreak if posts.empty?@@ -335,7 +363,8 @@ class ImportScripts::Smf1 < ImportScripts::Basecreate_posts(posts, total: total, offset: offset) do |p|next unless user_id = user_id_from_imported_user_id(p["id_member_from"])next if p["recipients"].blank?- recipients = p["recipients"].split(",").map { |id| user_id_from_imported_user_id(id) }.compact.uniq+ recipients =+ p["recipients"].split(",").map { |id| user_id_from_imported_user_id(id) }.compact.uniqnext if recipients.empty?id = "pm-#{p["id_pm"]}"@@ -385,10 +414,13 @@ class ImportScripts::Smf1 < ImportScripts::Basecount = 0last_upload_id = -1- total = mysql_query("SELECT COUNT(*) count FROM smf_attachments WHERE id_msg IS NOT NULL").first["count"]+ total =+ mysql_query("SELECT COUNT(*) count FROM smf_attachments WHERE id_msg IS NOT NULL").first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- uploads = mysql_query(<<~SQL+ uploads = mysql_query(<<~SQL).to_aSELECT id_attach, id_msg, filename@@ -399,7 +431,6 @@ class ImportScripts::Smf1 < ImportScripts::BaseORDER BY id_attachLIMIT #{BATCH_SIZE}SQL- ).to_abreak if uploads.empty?@@ -408,7 +439,13 @@ class ImportScripts::Smf1 < ImportScripts::Baseuploads.each do |u|count += 1- next unless post = PostCustomField.joins(:post).find_by(name: "import_id", value: u["id_msg"].to_s)&.post+ unless post =+ PostCustomField+ .joins(:post)+ .find_by(name: "import_id", value: u["id_msg"].to_s)+ &.post+ next+ endpath = File.join(UPLOADS_DIR, "#{u["id_attach"]}_#{u["file_hash"]}")next unless File.exist?(path) && File.size(path) > 0@@ -433,15 +470,25 @@ class ImportScripts::Smf1 < ImportScripts::Baseputs "", "Importing likes..."count = 0- total = mysql_query("SELECT COUNT(*) count FROM smf_thank_you_post WHERE thx_time > 0").first["count"]+ total =+ mysql_query("SELECT COUNT(*) count FROM smf_thank_you_post WHERE thx_time > 0").first["count"]like = PostActionType.types[:like]- mysql_query("SELECT id_msg, id_member, thx_time FROM smf_thank_you_post WHERE thx_time > 0 ORDER BY id_thx_post").each do |l|+ mysql_query(+ "SELECT id_msg, id_member, thx_time FROM smf_thank_you_post WHERE thx_time > 0 ORDER BY id_thx_post",+ ).each do |l|print_status(count += 1, total, get_start_time("likes"))next unless post_id = post_id_from_imported_post_id(l["id_msg"])next unless user_id = user_id_from_imported_user_id(l["id_member"])- next if PostAction.where(post_action_type_id: like, post_id: post_id, user_id: user_id).exists?- PostAction.create(post_action_type_id: like, post_id: post_id, user_id: user_id, created_at: Time.at(l["thx_time"]))+ if PostAction.where(post_action_type_id: like, post_id: post_id, user_id: user_id).exists?+ next+ end+ PostAction.create(+ post_action_type_id: like,+ post_id: post_id,+ user_id: user_id,+ created_at: Time.at(l["thx_time"]),+ )endend@@ -457,7 +504,7 @@ class ImportScripts::Smf1 < ImportScripts::Basecount = 0total = mysql_query("SELECT COUNT(*) count FROM smf_feedback WHERE approved").first["count"]- mysql_query(<<~SQL+ mysql_query(<<~SQL).each do |f|SELECT feedbackid, id_member, feedbackmember_id@@ -470,7 +517,6 @@ class ImportScripts::Smf1 < ImportScripts::BaseWHERE approvedORDER BY feedbackidSQL- ).each do |f|print_status(count += 1, total, get_start_time("feedbacks"))next unless user_id_from = user_id_from_imported_user_id(f["feedbackmember_id"])next unless user_id_to = user_id_from_imported_user_id(f["id_member"])@@ -498,7 +544,10 @@ class ImportScripts::Smf1 < ImportScripts::Baseputs "", "Importing banned email domains..."blocklist = SiteSetting.blocked_email_domains.split("|")- banned_domains = mysql_query("SELECT SUBSTRING(email_address, 3) domain FROM smf_ban_items WHERE email_address RLIKE '^%@[^%]+$' GROUP BY email_address").map { |r| r["domain"] }+ banned_domains =+ mysql_query(+ "SELECT SUBSTRING(email_address, 3) domain FROM smf_ban_items WHERE email_address RLIKE '^%@[^%]+$' GROUP BY email_address",+ ).map { |r| r["domain"] }SiteSetting.blocked_email_domains = (blocklist + banned_domains).uniq.sort.join("|")end@@ -508,7 +557,10 @@ class ImportScripts::Smf1 < ImportScripts::Basecount = 0- banned_emails = mysql_query("SELECT email_address FROM smf_ban_items WHERE email_address RLIKE '^[^%]+@[^%]+$' GROUP BY email_address").map { |r| r["email_address"] }+ banned_emails =+ mysql_query(+ "SELECT email_address FROM smf_ban_items WHERE email_address RLIKE '^[^%]+@[^%]+$' GROUP BY email_address",+ ).map { |r| r["email_address"] }banned_emails.each do |email|print_status(count += 1, banned_emails.size, get_start_time("banned_emails"))ScreenedEmail.find_or_create_by(email: email)@@ -520,7 +572,7 @@ class ImportScripts::Smf1 < ImportScripts::Basecount = 0- banned_ips = mysql_query(<<~SQL+ banned_ips = mysql_query(<<~SQL).to_aSELECT CONCAT_WS('.', ip_low1, ip_low2, ip_low3, ip_low4) low, CONCAT_WS('.', ip_high1, ip_high2, ip_high3, ip_high4) high, hits@@ -528,7 +580,6 @@ class ImportScripts::Smf1 < ImportScripts::BaseWHERE (ip_low1 + ip_low2 + ip_low3 + ip_low4 + ip_high1 + ip_high2 + ip_high3 + ip_high4) > 0GROUP BY low, high, hits;SQL- ).to_abanned_ips.each do |r|print_status(count += 1, banned_ips.size, get_start_time("banned_ips"))@@ -537,15 +588,15 @@ class ImportScripts::Smf1 < ImportScripts::BaseScreenedIpAddress.create(ip_address: r["low"], match_count: r["hits"])endelse- low_values = r["low"].split(".").map(&:to_i)+ low_values = r["low"].split(".").map(&:to_i)high_values = r["high"].split(".").map(&:to_i)- first_diff = low_values.zip(high_values).count { |a, b| a == b }+ first_diff = low_values.zip(high_values).count { |a, b| a == b }first_diff -= 1 if low_values[first_diff] == 0 && high_values[first_diff] == 255- prefix = low_values[0...first_diff]- suffix = [0] * (3 - first_diff)- mask = 8 * (first_diff + 1)- values = (low_values[first_diff]..high_values[first_diff])- hits = (r["hits"] / [1, values.count].max).floor+ prefix = low_values[0...first_diff]+ suffix = [0] * (3 - first_diff)+ mask = 8 * (first_diff + 1)+ values = (low_values[first_diff]..high_values[first_diff])+ hits = (r["hits"] / [1, values.count].max).floorvalues.each do |v|range_values = prefix + [v] + suffixip_address = "#{range_values.join(".")}/#{mask}"@@ -562,10 +613,28 @@ class ImportScripts::Smf1 < ImportScripts::BaseScreenedIpAddress.roll_upend- IGNORED_BBCODE ||= %w{- black blue center color email flash font glow green iurl left list move red- right shadown size table time white- }+ IGNORED_BBCODE ||= %w[+ black+ blue+ center+ color+ flash+ font+ glow+ green+ iurl+ left+ list+ move+ red+ right+ shadown+ size+ table+ time+ white+ ]def pre_process_raw(raw)return "" if raw.blank?@@ -573,59 +642,59 @@ class ImportScripts::Smf1 < ImportScripts::Baseraw = @htmlentities.decode(raw)# [acronym]- raw.gsub!(/\[acronym=([^\]]+)\](.*?)\[\/acronym\]/im) { %{<abbr title="#{$1}">#{$2}</abbr>} }+ raw.gsub!(%r{\[acronym=([^\]]+)\](.*?)\[/acronym\]}im) { %{<abbr title="#{$1}">#{$2}</abbr>} }# [br]raw.gsub!(/\[br\]/i, "\n")- raw.gsub!(/<br\s*\/?>/i, "\n")+ raw.gsub!(%r{<br\s*/?>}i, "\n")# [hr]raw.gsub!(/\[hr\]/i, "<hr/>")# [sub]- raw.gsub!(/\[sub\](.*?)\[\/sub\]/im) { "<sub>#{$1}</sub>" }+ raw.gsub!(%r{\[sub\](.*?)\[/sub\]}im) { "<sub>#{$1}</sub>" }# [sup]- raw.gsub!(/\[sup\](.*?)\[\/sup\]/im) { "<sup>#{$1}</sup>" }+ raw.gsub!(%r{\[sup\](.*?)\[/sup\]}im) { "<sup>#{$1}</sup>" }# [html]raw.gsub!(/\[html\]/i, "\n```html\n")- raw.gsub!(/\[\/html\]/i, "\n```\n")+ raw.gsub!(%r{\[/html\]}i, "\n```\n")# [php]raw.gsub!(/\[php\]/i, "\n```php\n")- raw.gsub!(/\[\/php\]/i, "\n```\n")+ raw.gsub!(%r{\[/php\]}i, "\n```\n")# [code]- raw.gsub!(/\[\/?code\]/i, "\n```\n")+ raw.gsub!(%r{\[/?code\]}i, "\n```\n")# [pre]- raw.gsub!(/\[\/?pre\]/i, "\n```\n")+ raw.gsub!(%r{\[/?pre\]}i, "\n```\n")# [tt]- raw.gsub!(/\[\/?tt\]/i, "`")+ raw.gsub!(%r{\[/?tt\]}i, "`")# [ftp]raw.gsub!(/\[ftp/i, "[url")- raw.gsub!(/\[\/ftp\]/i, "[/url]")+ raw.gsub!(%r{\[/ftp\]}i, "[/url]")# [me]- raw.gsub!(/\[me=([^\]]*)\](.*?)\[\/me\]/im) { "_\\* #{$1} #{$2}_" }+ raw.gsub!(%r{\[me=([^\]]*)\](.*?)\[/me\]}im) { "_\\* #{$1} #{$2}_" }# [li]- raw.gsub!(/\[li\](.*?)\[\/li\]/im) { "- #{$1}" }+ raw.gsub!(%r{\[li\](.*?)\[/li\]}im) { "- #{$1}" }# puts [img] on their own line- raw.gsub!(/\[img[^\]]*\](.*?)\[\/img\]/im) { "\n#{$1}\n" }+ raw.gsub!(%r{\[img[^\]]*\](.*?)\[/img\]}im) { "\n#{$1}\n" }# puts [youtube] on their own line- raw.gsub!(/\[youtube\](.*?)\[\/youtube\]/im) { "\n#{$1}\n" }+ raw.gsub!(%r{\[youtube\](.*?)\[/youtube\]}im) { "\n#{$1}\n" }- IGNORED_BBCODE.each { |code| raw.gsub!(/\[#{code}[^\]]*\](.*?)\[\/#{code}\]/im, '\1') }+ IGNORED_BBCODE.each { |code| raw.gsub!(%r{\[#{code}[^\]]*\](.*?)\[/#{code}\]}im, '\1') }# ensure [/quote] are on their own line- raw.gsub!(/\s*\[\/quote\]\s*/im, "\n[/quote]\n")+ raw.gsub!(%r{\s*\[/quote\]\s*}im, "\n[/quote]\n")# [quote]- raw.gsub!(/\s*\[quote (.+?)\]\s/im) {+ raw.gsub!(/\s*\[quote (.+?)\]\s/im) doparams = $1post_id = params[/msg(\d+)/, 1]username = params[/author=(.+) link=/, 1]@@ -636,14 +705,14 @@ class ImportScripts::Smf1 < ImportScripts::Baseelse%{\n[quote="#{username}"]\n}end- }+ end# remove tapatalk mess- raw.gsub!(/Sent from .+? using \[url=.*?\].+?\[\/url\]/i, "")+ raw.gsub!(%r{Sent from .+? using \[url=.*?\].+?\[/url\]}i, "")raw.gsub!(/Sent from .+? using .+?\z/i, "")# clean URLs- raw.gsub!(/\[url=(.+?)\]\1\[\/url\]/i, '\1')+ raw.gsub!(%r{\[url=(.+?)\]\1\[/url\]}i, '\1')rawend@@ -651,7 +720,6 @@ class ImportScripts::Smf1 < ImportScripts::Basedef mysql_query(sql)@client.query(sql)end-endImportScripts::Smf1.new.performdiff --git a/script/import_scripts/smf2.rb b/script/import_scripts/smf2.rbindex a70faff4cb9..97eb20a92ba 100644--- a/script/import_scripts/smf2.rb+++ b/script/import_scripts/smf2.rb@@ -1,18 +1,17 @@# coding: utf-8# frozen_string_literal: true-require 'mysql2'-require File.expand_path(File.dirname(__FILE__) + '/base.rb')+require "mysql2"+require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'-require 'tsort'-require 'set'-require 'optparse'-require 'etc'-require 'open3'+require "htmlentities"+require "tsort"+require "set"+require "optparse"+require "etc"+require "open3"class ImportScripts::Smf2 < ImportScripts::Base-def self.runoptions = Options.newbegin@@ -54,9 +53,9 @@ class ImportScripts::Smf2 < ImportScripts::Baseexit 1endif options.password == :ask- require 'highline'+ require "highline"$stderr.print "Enter password for MySQL database `#{options.database}`: "- options.password = HighLine.new.ask('') { |q| q.echo = false }+ options.password = HighLine.new.ask("") { |q| q.echo = false }end@default_db_connection = create_db_connection@@ -68,11 +67,11 @@ class ImportScripts::Smf2 < ImportScripts::Baseimport_categoriesimport_postspostprocess_posts- make_prettyurl_permalinks('/forum')+ make_prettyurl_permalinks("/forum")enddef import_groups- puts '', 'creating groups'+ puts "", "creating groups"total = query(<<-SQL, as: :single)SELECT COUNT(*) FROM {prefix}membergroups@@ -92,7 +91,7 @@ class ImportScripts::Smf2 < ImportScripts::BaseMODERATORS_GROUP = 2def import_users- puts '', 'creating users'+ puts "", "creating users"total = query("SELECT COUNT(*) FROM {prefix}members", as: :single)create_users(query(<<-SQL), total: total) do |member|@@ -103,10 +102,25 @@ class ImportScripts::Smf2 < ImportScripts::BaseFROM {prefix}members AS aLEFT JOIN {prefix}attachments AS b ON a.id_member = b.id_memberSQL- group_ids = [ member[:id_group], *member[:additional_groups].split(',').map(&:to_i) ]- create_time = Time.zone.at(member[:date_registered]) rescue Time.now- last_seen_time = Time.zone.at(member[:last_login]) rescue nil- ip_addr = IPAddr.new(member[:member_ip]) rescue nil+ group_ids = [member[:id_group], *member[:additional_groups].split(",").map(&:to_i)]+ create_time =+ begin+ Time.zone.at(member[:date_registered])+ rescue StandardError+ Time.now+ end+ last_seen_time =+ begin+ Time.zone.at(member[:last_login])+ rescue StandardError+ nil+ end+ ip_addr =+ begin+ IPAddr.new(member[:member_ip])+ rescue StandardError+ nil+ end{id: member[:id_member],username: member[:member_name],@@ -121,27 +135,33 @@ class ImportScripts::Smf2 < ImportScripts::Baseip_address: ip_addr,admin: group_ids.include?(ADMIN_GROUP),moderator: group_ids.include?(MODERATORS_GROUP),-- post_create_action: proc do |user|- user.update(created_at: create_time) if create_time < user.created_at- user.save- GroupUser.transaction do- group_ids.each do |gid|- (group_id = group_id_from_imported_group_id(gid)) &&- GroupUser.find_or_create_by(user: user, group_id: group_id)- end- end- if options.smfroot && member[:id_attach].present? && user.uploaded_avatar_id.blank?- (path = find_smf_attachment_path(member[:id_attach], member[:file_hash], member[:filename])) && begin- upload = create_upload(user.id, path, member[:filename])- if upload.persisted?- user.update(uploaded_avatar_id: upload.id)+ post_create_action:+ proc do |user|+ user.update(created_at: create_time) if create_time < user.created_at+ user.save+ GroupUser.transaction do+ group_ids.each do |gid|+ (group_id = group_id_from_imported_group_id(gid)) &&+ GroupUser.find_or_create_by(user: user, group_id: group_id)end- rescue SystemCallError => err- puts "Could not import avatar: #{err.message}"end- end- end+ if options.smfroot && member[:id_attach].present? && user.uploaded_avatar_id.blank?+ (+ path =+ find_smf_attachment_path(+ member[:id_attach],+ member[:file_hash],+ member[:filename],+ )+ ) &&+ begin+ upload = create_upload(user.id, path, member[:filename])+ user.update(uploaded_avatar_id: upload.id) if upload.persisted?+ rescue SystemCallError => err+ puts "Could not import avatar: #{err.message}"+ end+ end+ end,}endend@@ -155,38 +175,39 @@ class ImportScripts::Smf2 < ImportScripts::Baseparent_id = category_id_from_imported_category_id(board[:id_parent]) if board[:id_parent] > 0groups = (board[:member_groups] || "").split(/,/).map(&:to_i)restricted = !groups.include?(GUEST_GROUP) && !groups.include?(MEMBER_GROUP)- if Category.find_by_name(board[:name])- board[:name] += board[:id_board].to_s- end+ board[:name] += board[:id_board].to_s if Category.find_by_name(board[:name]){id: board[:id_board],name: board[:name],description: board[:description],parent_category_id: parent_id,- post_create_action: restricted && proc do |category|- category.update(read_restricted: true)- groups.each do |imported_group_id|- (group_id = group_id_from_imported_group_id(imported_group_id)) &&- CategoryGroup.find_or_create_by(category: category, group_id: group_id) do |cg|- cg.permission_type = CategoryGroup.permission_types[:full]- end- end- end,+ post_create_action:+ restricted &&+ proc do |category|+ category.update(read_restricted: true)+ groups.each do |imported_group_id|+ (group_id = group_id_from_imported_group_id(imported_group_id)) &&+ CategoryGroup.find_or_create_by(category: category, group_id: group_id) do |cg|+ cg.permission_type = CategoryGroup.permission_types[:full]+ end+ end+ end,}endenddef import_posts- puts '', 'creating posts'- spinner = %w(/ - \\ |).cycle+ puts "", "creating posts"+ spinner = %w[/ - \\ |].cycletotal = query("SELECT COUNT(*) FROM {prefix}messages", as: :single)PostCreator.class_eval dodef guardian- @guardian ||= if opts[:import_mode]- @@system_guardian ||= Guardian.new(Discourse.system_user)- else- Guardian.new(@user)- end+ @guardian ||=+ if opts[:import_mode]+ @@system_guardian ||= Guardian.new(Discourse.system_user)+ else+ Guardian.new(@user)+ endendend@@ -208,10 +229,12 @@ class ImportScripts::Smf2 < ImportScripts::Baseid: message[:id_msg],user_id: user_id_from_imported_user_id(message[:id_member]) || -1,created_at: Time.zone.at(message[:poster_time]),- post_create_action: ignore_quotes && proc do |p|- p.custom_fields['import_rebake'] = 't'- p.save- end+ post_create_action:+ ignore_quotes &&+ proc do |p|+ p.custom_fields["import_rebake"] = "t"+ p.save+ end,}if message[:id_msg] == message[:id_first_msg]@@ -228,31 +251,48 @@ class ImportScripts::Smf2 < ImportScripts::Baseendnext nil if skip- attachments = message[:attachment_count] == 0 ? [] : query(<<-SQL, connection: db2, as: :array)+ attachments =+ message[:attachment_count] == 0 ? [] : query(<<-SQL, connection: db2, as: :array)SELECT id_attach, file_hash, filename FROM {prefix}attachmentsWHERE attachment_type = 0 AND id_msg = #{message[:id_msg]}ORDER BY id_attach ASCSQL- attachments.map! { |a| import_attachment(post, a) rescue (puts $! ; nil) }+ attachments.map! do |a|+ begin+ import_attachment(post, a)+ rescue StandardError+ (+ puts $!+ nil+ )+ end+ endpost[:raw] = convert_message_body(message[:body], attachments, ignore_quotes: ignore_quotes)next postendenddef import_attachment(post, attachment)- path = find_smf_attachment_path(attachment[:id_attach], attachment[:file_hash], attachment[:filename])+ path =+ find_smf_attachment_path(+ attachment[:id_attach],+ attachment[:file_hash],+ attachment[:filename],+ )raise "Attachment for post #{post[:id]} failed: #{attachment[:filename]}" unless path.present?upload = create_upload(post[:user_id], path, attachment[:filename])- raise "Attachment for post #{post[:id]} failed: #{upload.errors.full_messages.join(', ')}" unless upload.persisted?+ unless upload.persisted?+ raise "Attachment for post #{post[:id]} failed: #{upload.errors.full_messages.join(", ")}"+ enduploadrescue SystemCallError => errraise "Attachment for post #{post[:id]} failed: #{err.message}"enddef postprocess_posts- puts '', 'rebaking posts'+ puts "", "rebaking posts"- tags = PostCustomField.where(name: 'import_rebake', value: 't')+ tags = PostCustomField.where(name: "import_rebake", value: "t")tags_total = tags.counttags_done = 0@@ -271,38 +311,47 @@ class ImportScripts::Smf2 < ImportScripts::Baseprivatedef create_db_connection- Mysql2::Client.new(host: options.host, username: options.username,- password: options.password, database: options.database)+ Mysql2::Client.new(+ host: options.host,+ username: options.username,+ password: options.password,+ database: options.database,+ )enddef query(sql, **opts, &block)db = opts[:connection] || @default_db_connection- return __query(db, sql).to_a if opts[:as] == :array- return __query(db, sql, as: :array).first[0] if opts[:as] == :single+ return __query(db, sql).to_a if opts[:as] == :array+ return __query(db, sql, as: :array).first[0] if opts[:as] == :singlereturn __query(db, sql, stream: true).each(&block) if block_given?__query(db, sql, stream: true)enddef __query(db, sql, **opts)- db.query(sql.gsub('{prefix}', options.prefix),- { symbolize_keys: true, cache_rows: false }.merge(opts))+ db.query(+ sql.gsub("{prefix}", options.prefix),+ { symbolize_keys: true, cache_rows: false }.merge(opts),+ )end- TRTR_TABLE = begin- from = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ"- to = "SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy"- from.chars.zip(to.chars)- end+ TRTR_TABLE =+ begin+ from = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ"+ to = "SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy"+ from.chars.zip(to.chars)+ enddef find_smf_attachment_path(attachment_id, file_hash, filename)cleaned_name = filename.dupTRTR_TABLE.each { |from, to| cleaned_name.gsub!(from, to) }- cleaned_name.gsub!(/\s/, '_')- cleaned_name.gsub!(/[^\w_\.\-]/, '')- legacy_name = "#{attachment_id}_#{cleaned_name.gsub('.', '_')}#{Digest::MD5.hexdigest(cleaned_name)}"+ cleaned_name.gsub!(/\s/, "_")+ cleaned_name.gsub!(/[^\w_\.\-]/, "")+ legacy_name =+ "#{attachment_id}_#{cleaned_name.gsub(".", "_")}#{Digest::MD5.hexdigest(cleaned_name)}"- [ filename, "#{attachment_id}_#{file_hash}", legacy_name ]- .map { |name| File.join(options.smfroot, 'attachments', name) }+ [filename, "#{attachment_id}_#{file_hash}", legacy_name].map do |name|+ File.join(options.smfroot, "attachments", name)+ end.detect { |file| File.exist?(file) }end@@ -311,16 +360,16 @@ class ImportScripts::Smf2 < ImportScripts::Baseenddef convert_message_body(body, attachments = [], **opts)- body = decode_entities(body.gsub(/<br\s*\/>/, "\n"))+ body = decode_entities(body.gsub(%r{<br\s*/>}, "\n"))body.gsub!(ColorPattern, '\k<inner>')body.gsub!(ListPattern) do |s|params = parse_tag_params($~[:params])- tag = params['type'] == 'decimal' ? 'ol' : 'ul'+ tag = params["type"] == "decimal" ? "ol" : "ul""\n[#{tag}]#{$~[:inner].strip}[/#{tag}]\n"endbody.gsub!(XListPattern) do |s|r = +"\n[ul]"- s.lines.each { |l| "#{r}[li]#{l.strip.sub(/^\[x\]\s*/, '')}[/li]" }+ s.lines.each { |l| "#{r}[li]#{l.strip.sub(/^\[x\]\s*/, "")}[/li]" }"#{r}[/ul]\n"end@@ -338,9 +387,7 @@ class ImportScripts::Smf2 < ImportScripts::Baseif use_count.keys.length < attachments.select(&:present?).lengthbody = "#{body}\n\n---"attachments.each_with_index do |upload, num|- if upload.present? && use_count[num] == (0)- "#{body}\n\n#{get_upload_markdown(upload)}"- end+ "#{body}\n\n#{get_upload_markdown(upload)}" if upload.present? && use_count[num] == (0)endendend@@ -353,26 +400,46 @@ class ImportScripts::Smf2 < ImportScripts::Baseenddef convert_quotes(body)- body.to_s.gsub(QuotePattern) do |s|- inner = $~[:inner].strip- params = parse_tag_params($~[:params])- if params['author'].present?- quote = +"\n[quote=\"#{params['author']}"- if QuoteParamsPattern =~ params['link']- tl = topic_lookup_from_imported_post_id($~[:msg].to_i)- quote = "#{quote} post:#{tl[:post_number]}, topic:#{tl[:topic_id]}" if tl+ body+ .to_s+ .gsub(QuotePattern) do |s|+ inner = $~[:inner].strip+ params = parse_tag_params($~[:params])+ if params["author"].present?+ quote = +"\n[quote=\"#{params["author"]}"+ if QuoteParamsPattern =~ params["link"]+ tl = topic_lookup_from_imported_post_id($~[:msg].to_i)+ quote = "#{quote} post:#{tl[:post_number]}, topic:#{tl[:topic_id]}" if tl+ end+ quote = "#{quote}\"]\n#{convert_quotes(inner)}\n[/quote]"+ else+ "<blockquote>#{convert_quotes(inner)}</blockquote>"end- quote = "#{quote}\"]\n#{convert_quotes(inner)}\n[/quote]"- else- "<blockquote>#{convert_quotes(inner)}</blockquote>"end- endend- IGNORED_BBCODE ||= %w{- black blue center color email flash font glow green iurl left list move red- right shadown size table time white- }+ IGNORED_BBCODE ||= %w[+ black+ blue+ center+ color+ flash+ font+ glow+ green+ iurl+ left+ list+ move+ red+ right+ shadown+ size+ table+ time+ white+ ]def convert_bbcode(raw)return "" if raw.blank?@@ -380,67 +447,67 @@ class ImportScripts::Smf2 < ImportScripts::Baseraw = convert_quotes(raw)# [acronym]- raw.gsub!(/\[acronym=([^\]]+)\](.*?)\[\/acronym\]/im) { %{<abbr title="#{$1}">#{$2}</abbr>} }+ raw.gsub!(%r{\[acronym=([^\]]+)\](.*?)\[/acronym\]}im) { %{<abbr title="#{$1}">#{$2}</abbr>} }# [br]raw.gsub!(/\[br\]/i, "\n")- raw.gsub!(/<br\s*\/?>/i, "\n")+ raw.gsub!(%r{<br\s*/?>}i, "\n")# [hr]raw.gsub!(/\[hr\]/i, "<hr/>")# [sub]- raw.gsub!(/\[sub\](.*?)\[\/sub\]/im) { "<sub>#{$1}</sub>" }+ raw.gsub!(%r{\[sub\](.*?)\[/sub\]}im) { "<sub>#{$1}</sub>" }# [sup]- raw.gsub!(/\[sup\](.*?)\[\/sup\]/im) { "<sup>#{$1}</sup>" }+ raw.gsub!(%r{\[sup\](.*?)\[/sup\]}im) { "<sup>#{$1}</sup>" }# [html]raw.gsub!(/\[html\]/i, "\n```html\n")- raw.gsub!(/\[\/html\]/i, "\n```\n")+ raw.gsub!(%r{\[/html\]}i, "\n```\n")# [php]raw.gsub!(/\[php\]/i, "\n```php\n")- raw.gsub!(/\[\/php\]/i, "\n```\n")+ raw.gsub!(%r{\[/php\]}i, "\n```\n")# [code]- raw.gsub!(/\[\/?code\]/i, "\n```\n")+ raw.gsub!(%r{\[/?code\]}i, "\n```\n")# [pre]- raw.gsub!(/\[\/?pre\]/i, "\n```\n")+ raw.gsub!(%r{\[/?pre\]}i, "\n```\n")# [tt]- raw.gsub!(/\[\/?tt\]/i, "`")+ raw.gsub!(%r{\[/?tt\]}i, "`")# [ftp]raw.gsub!(/\[ftp/i, "[url")- raw.gsub!(/\[\/ftp\]/i, "[/url]")+ raw.gsub!(%r{\[/ftp\]}i, "[/url]")# [me]- raw.gsub!(/\[me=([^\]]*)\](.*?)\[\/me\]/im) { "_\\* #{$1} #{$2}_" }+ raw.gsub!(%r{\[me=([^\]]*)\](.*?)\[/me\]}im) { "_\\* #{$1} #{$2}_" }# [ul]raw.gsub!(/\[ul\]/i, "")- raw.gsub!(/\[\/ul\]/i, "")+ raw.gsub!(%r{\[/ul\]}i, "")# [li]- raw.gsub!(/\[li\](.*?)\[\/li\]/im) { "- #{$1}" }+ raw.gsub!(%r{\[li\](.*?)\[/li\]}im) { "- #{$1}" }# puts [img] on their own line- raw.gsub!(/\[img[^\]]*\](.*?)\[\/img\]/im) { "\n#{$1}\n" }+ raw.gsub!(%r{\[img[^\]]*\](.*?)\[/img\]}im) { "\n#{$1}\n" }# puts [youtube] on their own line- raw.gsub!(/\[youtube\](.*?)\[\/youtube\]/im) { "\n#{$1}\n" }+ raw.gsub!(%r{\[youtube\](.*?)\[/youtube\]}im) { "\n#{$1}\n" }- IGNORED_BBCODE.each { |code| raw.gsub!(/\[#{code}[^\]]*\](.*?)\[\/#{code}\]/im, '\1') }+ IGNORED_BBCODE.each { |code| raw.gsub!(%r{\[#{code}[^\]]*\](.*?)\[/#{code}\]}im, '\1') }# ensure [/quote] are on their own line- raw.gsub!(/\s*\[\/quote\]\s*/im, "\n[/quote]\n")+ raw.gsub!(%r{\s*\[/quote\]\s*}im, "\n[/quote]\n")# remove tapatalk mess- raw.gsub!(/Sent from .+? using \[url=.*?\].+?\[\/url\]/i, "")+ raw.gsub!(%r{Sent from .+? using \[url=.*?\].+?\[/url\]}i, "")raw.gsub!(/Sent from .+? using .+?\z/i, "")# clean URLs- raw.gsub!(/\[url=(.+?)\]\1\[\/url\]/i, '\1')+ raw.gsub!(%r{\[url=(.+?)\]\1\[/url\]}i, '\1')rawend@@ -460,8 +527,14 @@ class ImportScripts::Smf2 < ImportScripts::Base# param1=value1=still1 value1 param2=value2 ...# => {'param1' => 'value1=still1 value1', 'param2' => 'value2 ...'}def parse_tag_params(params)- params.to_s.strip.scan(/(?<param>\w+)=(?<value>(?:(?>\S+)|\s+(?!\w+=))*)/).- inject({}) { |h, e| h[e[0]] = e[1]; h }+ params+ .to_s+ .strip+ .scan(/(?<param>\w+)=(?<value>(?:(?>\S+)|\s+(?!\w+=))*)/)+ .inject({}) do |h, e|+ h[e[0]] = e[1]+ h+ endendclass << self@@ -474,8 +547,8 @@ class ImportScripts::Smf2 < ImportScripts::Base# => match[:params] == 'param=value param2=value2'# match[:inner] == "\n text\n [tag nested=true]text[/tag]\n"def build_nested_tag_regex(ltag, rtag = nil)- rtag ||= '/' + ltag- %r{+ rtag ||= "/" + ltag+ /\[#{ltag}(?-x:[ =](?<params>[^\]]*))?\] # consume open tag, followed by...(?<inner>(?:(?> [^\[]+ ) # non-tags, or...@@ -495,40 +568,41 @@ class ImportScripts::Smf2 < ImportScripts::Base))*)\[#{rtag}\]- }x+ /xendendQuoteParamsPattern = /^topic=(?<topic>\d+).msg(?<msg>\d+)#msg\k<msg>$/XListPattern = /(?<xblock>(?>^\[x\]\s*(?<line>.*)$\n?)+)/- QuotePattern = build_nested_tag_regex('quote')- ColorPattern = build_nested_tag_regex('color')- ListPattern = build_nested_tag_regex('list')+ QuotePattern = build_nested_tag_regex("quote")+ ColorPattern = build_nested_tag_regex("color")+ ListPattern = build_nested_tag_regex("list")AttachmentPatterns = [[/^\[attach(?:|img|url|mini)=(?<num>\d+)\]$/, ->(u) { "\n" + get_upload_markdown(u) + "\n" }],- [/\[attach(?:|img|url|mini)=(?<num>\d+)\]/, ->(u) { get_upload_markdown(u) }]+ [/\[attach(?:|img|url|mini)=(?<num>\d+)\]/, ->(u) { get_upload_markdown(u) }],]# Provides command line options and parses the SMF settings file.class Options-- class Error < StandardError ; end- class SettingsError < Error ; end+ class Error < StandardError+ end+ class SettingsError < Error+ enddef parse!(args = ARGV)- raise Error, 'not enough arguments' if ARGV.empty?+ raise Error, "not enough arguments" if ARGV.empty?beginparser.parse!(args)rescue OptionParser::ParseError => errraise Error, err.messageend- raise Error, 'too many arguments' if args.length > 1+ raise Error, "too many arguments" if args.length > 1self.smfroot = args.firstread_smf_settings if self.smfroot- self.host ||= 'localhost'+ self.host ||= "localhost"self.username ||= Etc.getlogin- self.prefix ||= 'smf_'+ self.prefix ||= "smf_"self.timezone ||= get_php_timezoneend@@ -547,44 +621,63 @@ class ImportScripts::Smf2 < ImportScripts::Baseprivatedef get_php_timezone- phpinfo, status = Open3.capture2('php', '-i')+ phpinfo, status = Open3.capture2("php", "-i")phpinfo.lines.each do |line|- key, *vals = line.split(' => ').map(&:strip)- break vals[0] if key == 'Default timezone'+ key, *vals = line.split(" => ").map(&:strip)+ break vals[0] if key == "Default timezone"endrescue Errno::ENOENT$stderr.puts "Error: PHP CLI executable not found"enddef read_smf_settings- settings = File.join(self.smfroot, 'Settings.php')- File.readlines(settings).each do |line|- next unless m = /\$([a-z_]+)\s*=\s*['"](.+?)['"]\s*;\s*((#|\/\/).*)?$/.match(line)- case m[1]- when 'db_server' then self.host ||= m[2]- when 'db_user' then self.username ||= m[2]- when 'db_passwd' then self.password ||= m[2]- when 'db_name' then self.database ||= m[2]- when 'db_prefix' then self.prefix ||= m[2]+ settings = File.join(self.smfroot, "Settings.php")+ File+ .readlines(settings)+ .each do |line|+ next unless m = %r{\$([a-z_]+)\s*=\s*['"](.+?)['"]\s*;\s*((#|//).*)?$}.match(line)+ case m[1]+ when "db_server"+ self.host ||= m[2]+ when "db_user"+ self.username ||= m[2]+ when "db_passwd"+ self.password ||= m[2]+ when "db_name"+ self.database ||= m[2]+ when "db_prefix"+ self.prefix ||= m[2]+ endend- endrescue => errraise SettingsError, err.message unless self.databaseenddef parser- @parser ||= OptionParser.new(nil, 12) do |o|- o.banner = "Usage:\t#{File.basename($0)} <SMFROOT> [options]\n"- o.banner = "${o.banner}\t#{File.basename($0)} -d <DATABASE> [options]"- o.on('-h HOST', :REQUIRED, "MySQL server hostname [\"#{self.host}\"]") { |s| self.host = s }- o.on('-u USER', :REQUIRED, "MySQL username [\"#{self.username}\"]") { |s| self.username = s }- o.on('-p [PASS]', :OPTIONAL, 'MySQL password. Without argument, reads password from STDIN.') { |s| self.password = s || :ask }- o.on('-d DBNAME', :REQUIRED, 'Name of SMF database') { |s| self.database = s }- o.on('-f PREFIX', :REQUIRED, "Table names prefix [\"#{self.prefix}\"]") { |s| self.prefix = s }- o.on('-t TIMEZONE', :REQUIRED, 'Timezone used by SMF2 [auto-detected from PHP]') { |s| self.timezone = s }- end+ @parser ||=+ OptionParser.new(nil, 12) do |o|+ o.banner = "Usage:\t#{File.basename($0)} <SMFROOT> [options]\n"+ o.banner = "${o.banner}\t#{File.basename($0)} -d <DATABASE> [options]"+ o.on("-h HOST", :REQUIRED, "MySQL server hostname [\"#{self.host}\"]") do |s|+ self.host = s+ end+ o.on("-u USER", :REQUIRED, "MySQL username [\"#{self.username}\"]") do |s|+ self.username = s+ end+ o.on(+ "-p [PASS]",+ :OPTIONAL,+ "MySQL password. Without argument, reads password from STDIN.",+ ) { |s| self.password = s || :ask }+ o.on("-d DBNAME", :REQUIRED, "Name of SMF database") { |s| self.database = s }+ o.on("-f PREFIX", :REQUIRED, "Table names prefix [\"#{self.prefix}\"]") do |s|+ self.prefix = s+ end+ o.on("-t TIMEZONE", :REQUIRED, "Timezone used by SMF2 [auto-detected from PHP]") do |s|+ self.timezone = s+ end+ endend-end #Options# Framework around TSort, used to build a dependency graph over messages@@ -644,10 +737,14 @@ class ImportScripts::Smf2 < ImportScripts::Baseenddef dependencies- @dependencies ||= Set.new.tap do |deps|- deps.merge(quoted) unless ignore_quotes?- deps << prev if prev.present?- end.to_a+ @dependencies ||=+ Set+ .new+ .tap do |deps|+ deps.merge(quoted) unless ignore_quotes?+ deps << prev if prev.present?+ end+ .to_aenddef hash@@ -659,7 +756,7 @@ class ImportScripts::Smf2 < ImportScripts::Baseenddef inspect- "#<#{self.class.name}: id=#{id.inspect}, prev=#{safe_id(@prev)}, quoted=[#{@quoted.map(&method(:safe_id)).join(', ')}]>"+ "#<#{self.class.name}: id=#{id.inspect}, prev=#{safe_id(@prev)}, quoted=[#{@quoted.map(&method(:safe_id)).join(", ")}]>"endprivate@@ -668,11 +765,10 @@ class ImportScripts::Smf2 < ImportScripts::Base@graph[id].present? ? @graph[id].id.inspect : "(#{id})"endend #Node-end #MessageDependencyGraphdef make_prettyurl_permalinks(prefix)- puts 'creating permalinks for prettyurl plugin'+ puts "creating permalinks for prettyurl plugin"beginserialized = query(<<-SQL, as: :single)SELECT value FROM {prefix}settings@@ -680,9 +776,7 @@ class ImportScripts::Smf2 < ImportScripts::BaseSQLboard_slugs = Array.newser = /\{(.*)\}/.match(serialized)[1]- ser.scan(/i:(\d+);s:\d+:\"(.*?)\";/).each do |nv|- board_slugs[nv[0].to_i] = nv[1]- end+ ser.scan(/i:(\d+);s:\d+:\"(.*?)\";/).each { |nv| board_slugs[nv[0].to_i] = nv[1] }topic_urls = query(<<-SQL, as: :array)SELECT t.id_first_msg, t.id_board,u.pretty_urlFROM smf_topics t@@ -690,12 +784,14 @@ class ImportScripts::Smf2 < ImportScripts::BaseSQLtopic_urls.each do |url|t = topic_lookup_from_imported_post_id(url[:id_first_msg])- Permalink.create(url: "#{prefix}/#{board_slugs[url[:id_board]]}/#{url[:pretty_url]}", topic_id: t[:topic_id])+ Permalink.create(+ url: "#{prefix}/#{board_slugs[url[:id_board]]}/#{url[:pretty_url]}",+ topic_id: t[:topic_id],+ )end- rescue+ rescue StandardErrorendend-endImportScripts::Smf2.rundiff --git a/script/import_scripts/socialcast/create_title.rb b/script/import_scripts/socialcast/create_title.rbindex 8af625eddb5..ea656fadb7e 100644--- a/script/import_scripts/socialcast/create_title.rb+++ b/script/import_scripts/socialcast/create_title.rb@@ -1,9 +1,8 @@# frozen_string_literal: true-require 'uri'+require "uri"class CreateTitle-def self.from_body(body)title = remove_mentions bodytitle = remove_urls title@@ -24,11 +23,11 @@ class CreateTitleprivatedef self.remove_mentions(text)- text.gsub(/@[\w]*/, '')+ text.gsub(/@[\w]*/, "")enddef self.remove_urls(text)- text.gsub(URI::regexp(['http', 'https', 'mailto', 'ftp', 'ldap', 'ldaps']), '')+ text.gsub(URI.regexp(%w[http https mailto ftp ldap ldaps]), "")enddef self.remove_stray_punctuation(text)@@ -42,7 +41,7 @@ class CreateTitleenddef self.complete_sentences(text)- /(^.*[\S]{2,}[.!?:]+)\W/.match(text[0...80] + ' ')+ /(^.*[\S]{2,}[.!?:]+)\W/.match(text[0...80] + " ")enddef self.complete_words(text)diff --git a/script/import_scripts/socialcast/export.rb b/script/import_scripts/socialcast/export.rbindex 1c44c7c5c99..ac3a4690c1e 100644--- a/script/import_scripts/socialcast/export.rb+++ b/script/import_scripts/socialcast/export.rb@@ -1,14 +1,14 @@# frozen_string_literal: true-require 'yaml'-require 'fileutils'-require_relative 'socialcast_api'+require "yaml"+require "fileutils"+require_relative "socialcast_api"def load_config(file)- config = YAML::load_file(File.join(__dir__, file))- @domain = config['domain']- @username = config['username']- @password = config['password']+ config = YAML.load_file(File.join(__dir__, file))+ @domain = config["domain"]+ @username = config["username"]+ @password = config["password"]enddef export@@ -23,8 +23,8 @@ def export_users(page = 1)users = @api.list_users(page: page)return if users.empty?users.each do |user|- File.open("output/users/#{user['id']}.json", 'w') do |f|- puts user['contact_info']['email']+ File.open("output/users/#{user["id"]}.json", "w") do |f|+ puts user["contact_info"]["email"]f.write user.to_jsonf.closeend@@ -36,12 +36,12 @@ def export_messages(page = 1)messages = @api.list_messages(page: page)return if messages.empty?messages.each do |message|- File.open("output/messages/#{message['id']}.json", 'w') do |f|- title = message['title']- title = message['body'] if title.empty?+ File.open("output/messages/#{message["id"]}.json", "w") do |f|+ title = message["title"]+ title = message["body"] if title.empty?title = title.split('\n')[0][0..50] unless title.empty?- puts "#{message['id']}: #{title}"+ puts "#{message["id"]}: #{title}"f.write message.to_jsonf.closeend@@ -51,9 +51,7 @@ enddef create_dir(path)path = File.join(__dir__, path)- unless File.directory?(path)- FileUtils.mkdir_p(path)- end+ FileUtils.mkdir_p(path) unless File.directory?(path)endload_config ARGV.shiftdiff --git a/script/import_scripts/socialcast/import.rb b/script/import_scripts/socialcast/import.rbindex 413fd18ff81..c20237f66ce 100644--- a/script/import_scripts/socialcast/import.rb+++ b/script/import_scripts/socialcast/import.rb@@ -1,12 +1,11 @@# frozen_string_literal: true-require_relative './socialcast_message.rb'-require_relative './socialcast_user.rb'-require 'set'+require_relative "./socialcast_message.rb"+require_relative "./socialcast_user.rb"+require "set"require File.expand_path(File.dirname(__FILE__) + "/../base.rb")class ImportScripts::Socialcast < ImportScripts::Base-MESSAGES_DIR = "output/messages"USERS_DIR = "output/users"@@ -29,15 +28,13 @@ class ImportScripts::Socialcast < ImportScripts::Baseimported = 0total = count_files(MESSAGES_DIR)Dir.foreach(MESSAGES_DIR) do |filename|- next if filename == ('.') || filename == ('..')+ next if filename == (".") || filename == ("..")topics += 1- message_json = File.read MESSAGES_DIR + '/' + filename+ message_json = File.read MESSAGES_DIR + "/" + filenamemessage = SocialcastMessage.new(message_json)next unless message.titlecreated_topic = import_topic message.topic- if created_topic- import_posts message.replies, created_topic.topic_id- end+ import_posts message.replies, created_topic.topic_id if created_topicimported += 1print_status topics, totalend@@ -48,8 +45,8 @@ class ImportScripts::Socialcast < ImportScripts::Baseusers = 0total = count_files(USERS_DIR)Dir.foreach(USERS_DIR) do |filename|- next if filename == ('.') || filename == ('..')- user_json = File.read USERS_DIR + '/' + filename+ next if filename == (".") || filename == ("..")+ user_json = File.read USERS_DIR + "/" + filenameuser = SocialcastUser.new(user_json).usercreate_user user, user[:id]users += 1@@ -58,7 +55,7 @@ class ImportScripts::Socialcast < ImportScripts::Baseenddef count_files(path)- Dir.foreach(path).select { |f| f != '.' && f != '..' }.count+ Dir.foreach(path).select { |f| f != "." && f != ".." }.countenddef import_topic(topic)@@ -80,9 +77,7 @@ class ImportScripts::Socialcast < ImportScripts::Baseenddef import_posts(posts, topic_id)- posts.each do |post|- import_post post, topic_id- end+ posts.each { |post| import_post post, topic_id }enddef import_post(post, topic_id)@@ -95,9 +90,6 @@ class ImportScripts::Socialcast < ImportScripts::Baseputs new_post.inspectendend-end-if __FILE__ == $0- ImportScripts::Socialcast.new.perform-end+ImportScripts::Socialcast.new.perform if __FILE__ == $0diff --git a/script/import_scripts/socialcast/socialcast_api.rb b/script/import_scripts/socialcast/socialcast_api.rbindex 84fc6397703..6b080692c3e 100644--- a/script/import_scripts/socialcast/socialcast_api.rb+++ b/script/import_scripts/socialcast/socialcast_api.rb@@ -1,10 +1,9 @@# frozen_string_literal: true-require 'base64'-require 'json'+require "base64"+require "json"class SocialcastApi-attr_accessor :domain, :username, :passworddef initialize(domain, username, password)@@ -29,12 +28,12 @@ class SocialcastApidef list_users(opts = {})page = opts[:page] ? opts[:page] : 1response = request "#{base_url}/users?page=#{page}"- response['users'].sort { |u| u['id'] }+ response["users"].sort { |u| u["id"] }enddef list_messages(opts = {})page = opts[:page] ? opts[:page] : 1response = request "#{base_url}/messages?page=#{page}"- response['messages'].sort { |m| m['id'] }+ response["messages"].sort { |m| m["id"] }endenddiff --git a/script/import_scripts/socialcast/socialcast_message.rb b/script/import_scripts/socialcast/socialcast_message.rbindex 4c7cf7a445d..457713983a5 100644--- a/script/import_scripts/socialcast/socialcast_message.rb+++ b/script/import_scripts/socialcast/socialcast_message.rb@@ -1,24 +1,23 @@# frozen_string_literal: true-require 'json'-require 'cgi'-require 'time'-require_relative 'create_title.rb'+require "json"+require "cgi"+require "time"+require_relative "create_title.rb"class SocialcastMessage-DEFAULT_CATEGORY = "Socialcast Import"DEFAULT_TAG = "socialcast-import"TAGS_AND_CATEGORIES = {"somegroupname" => {category: "Apple Stems",- tags: ["waxy", "tough"]+ tags: %w[waxy tough],},"someothergroupname" => {category: "Orange Peels",- tags: ["oily"]- }- }+ tags: ["oily"],+ },+ }def initialize(message_json)@parsed_json = JSON.parse message_json@@ -26,18 +25,18 @@ class SocialcastMessagedef topictopic = {}- topic[:id] = @parsed_json['id']- topic[:author_id] = @parsed_json['user']['id']+ topic[:id] = @parsed_json["id"]+ topic[:author_id] = @parsed_json["user"]["id"]topic[:title] = title- topic[:raw] = @parsed_json['body']- topic[:created_at] = Time.parse @parsed_json['created_at']+ topic[:raw] = @parsed_json["body"]+ topic[:created_at] = Time.parse @parsed_json["created_at"]topic[:tags] = tagstopic[:category] = categorytopicenddef title- CreateTitle.from_body @parsed_json['body']+ CreateTitle.from_body @parsed_json["body"]enddef tags@@ -55,39 +54,37 @@ class SocialcastMessagedef categorycategory = DEFAULT_CATEGORY- if group && TAGS_AND_CATEGORIES[group]- category = TAGS_AND_CATEGORIES[group][:category]- end+ category = TAGS_AND_CATEGORIES[group][:category] if group && TAGS_AND_CATEGORIES[group]categoryenddef group- @parsed_json['group']['groupname'].downcase if @parsed_json['group'] && @parsed_json['group']['groupname']+ if @parsed_json["group"] && @parsed_json["group"]["groupname"]+ @parsed_json["group"]["groupname"].downcase+ endenddef url- @parsed_json['url']+ @parsed_json["url"]enddef message_type- @parsed_json['message_type']+ @parsed_json["message_type"]enddef repliesposts = []- comments = @parsed_json['comments']- comments.each do |comment|- posts << post_from_comment(comment)- end+ comments = @parsed_json["comments"]+ comments.each { |comment| posts << post_from_comment(comment) }postsenddef post_from_comment(comment)post = {}- post[:id] = comment['id']- post[:author_id] = comment['user']['id']- post[:raw] = comment['text']- post[:created_at] = Time.parse comment['created_at']+ post[:id] = comment["id"]+ post[:author_id] = comment["user"]["id"]+ post[:raw] = comment["text"]+ post[:created_at] = Time.parse comment["created_at"]postenddiff --git a/script/import_scripts/socialcast/socialcast_user.rb b/script/import_scripts/socialcast/socialcast_user.rbindex 1ffc93081ce..f882637f66b 100644--- a/script/import_scripts/socialcast/socialcast_user.rb+++ b/script/import_scripts/socialcast/socialcast_user.rb@@ -1,26 +1,24 @@# frozen_string_literal: true-require 'json'-require 'cgi'-require 'time'+require "json"+require "cgi"+require "time"class SocialcastUser-def initialize(user_json)@parsed_json = JSON.parse user_jsonenddef user- email = @parsed_json['contact_info']['email']- email = "#{@parsed_json['id']}@noemail.com" unless email+ email = @parsed_json["contact_info"]["email"]+ email = "#{@parsed_json["id"]}@noemail.com" unless emailuser = {}- user[:id] = @parsed_json['id']- user[:name] = @parsed_json['name']- user[:username] = @parsed_json['username']+ user[:id] = @parsed_json["id"]+ user[:name] = @parsed_json["name"]+ user[:username] = @parsed_json["username"]user[:email] = emailuser[:staged] = trueuserend-enddiff --git a/script/import_scripts/socialcast/test/test_create_title.rb b/script/import_scripts/socialcast/test/test_create_title.rbindex ee934a4f891..0dac092550f 100644--- a/script/import_scripts/socialcast/test/test_create_title.rb+++ b/script/import_scripts/socialcast/test/test_create_title.rb@@ -1,26 +1,28 @@# frozen_string_literal: true-require 'minitest/autorun'-require_relative '../create_title.rb'+require "minitest/autorun"+require_relative "../create_title.rb"class TestCreateTitle < Minitest::Test-def test_create_title_1- body = "@GreatCheerThreading \nWhere can I find information on how GCTS stacks up against the competition? What are the key differentiators?"+ body =+ "@GreatCheerThreading \nWhere can I find information on how GCTS stacks up against the competition? What are the key differentiators?"expected = "Where can I find information on how GCTS stacks up against the competition?"title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_2- body = "GCTS in 200 stores across town. How many threads per inch would you guess? @GreatCheerThreading"+ body =+ "GCTS in 200 stores across town. How many threads per inch would you guess? @GreatCheerThreading"expected = "GCTS in 200 stores across town. How many threads per inch would you guess?"title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_3- body = "gFabric Sheets 1.2 now has Great Cheer Threads, letting you feel the softness running through the cotton fibers."+ body =+ "gFabric Sheets 1.2 now has Great Cheer Threads, letting you feel the softness running through the cotton fibers."expected = "gFabric Sheets 1.2 now has Great Cheer Threads, letting you feel the softness..."title = CreateTitle.from_body bodyassert_equal(expected, title)@@ -34,49 +36,56 @@ class TestCreateTitle < Minitest::Testenddef test_create_title_5- body = "One sentence. Two sentence. Three sentence. Four is going to go on and on for more words than we want."+ body =+ "One sentence. Two sentence. Three sentence. Four is going to go on and on for more words than we want."expected = "One sentence. Two sentence. Three sentence."title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_6- body = "Anyone know of any invite codes for www.greatcheer.io (the Great Cheer v2 site)?\n\n//cc @RD @GreatCheerThreading"+ body =+ "Anyone know of any invite codes for www.greatcheer.io (the Great Cheer v2 site)?\n\n//cc @RD @GreatCheerThreading"expected = "Anyone know of any invite codes for www.greatcheer.io (the Great Cheer v2 site)?"title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_6b- body = "Anyone know of any invite codes for www.greatcheer.io (the Great Cheer v2 site of yore)?\n\n//cc @RD @GreatCheerThreading"+ body =+ "Anyone know of any invite codes for www.greatcheer.io (the Great Cheer v2 site of yore)?\n\n//cc @RD @GreatCheerThreading"expected = "Anyone know of any invite codes for www.greatcheer.io (the Great Cheer v2 site..."title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_6c- body = "Anyone know of any invite codes for www.greatcheer.io?! (the Great Cheer v2 site of yore)?\n\n//cc @RD @GreatCheerThreading"+ body =+ "Anyone know of any invite codes for www.greatcheer.io?! (the Great Cheer v2 site of yore)?\n\n//cc @RD @GreatCheerThreading"expected = "Anyone know of any invite codes for www.greatcheer.io?!"title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_7- body = "@GreatCheerThreading \n\nDoes anyone know what the plan is to move to denser 1.2 threads for GCTS?\n\nI have a customer interested in the higher thread counts offered in 1.2."+ body =+ "@GreatCheerThreading \n\nDoes anyone know what the plan is to move to denser 1.2 threads for GCTS?\n\nI have a customer interested in the higher thread counts offered in 1.2."expected = "Does anyone know what the plan is to move to denser 1.2 threads for GCTS?"title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_8- body = "@GreatCheerThreading @FabricWeavingWorldwide \n\nI was just chatting with a customer, after receiving this email:\n\n\"Ours is more of a ‘conceptual’ question. We have too much fiber"+ body =+ "@GreatCheerThreading @FabricWeavingWorldwide \n\nI was just chatting with a customer, after receiving this email:\n\n\"Ours is more of a ‘conceptual’ question. We have too much fiber"expected = "I was just chatting with a customer, after receiving this email:"title = CreateTitle.from_body bodyassert_equal(expected, title)enddef test_create_title_9- body = "Hi,\n\nDoes anyone have a PPT deck on whats new in cotton (around 10 or so slides) nothing to detailed as per what we have in the current 1.x version?\n\nI am not after a what's coming in cotton 2"+ body =+ "Hi,\n\nDoes anyone have a PPT deck on whats new in cotton (around 10 or so slides) nothing to detailed as per what we have in the current 1.x version?\n\nI am not after a what's coming in cotton 2"expected = "Does anyone have a PPT deck on whats new in cotton (around 10 or so slides)..."title = CreateTitle.from_body bodyassert_equal(expected, title)@@ -90,7 +99,8 @@ class TestCreateTitle < Minitest::Testenddef test_create_title_11- body = "Hi Guys,\nI'm working with #gtcs and one of the things we're playing with is TC. What better tool to demo and use than our own \nhttps://greatcheerthreading.com/themostthreads/cool-stuff\n\nThis used to work great in 2013,"+ body =+ "Hi Guys,\nI'm working with #gtcs and one of the things we're playing with is TC. What better tool to demo and use than our own \nhttps://greatcheerthreading.com/themostthreads/cool-stuff\n\nThis used to work great in 2013,"expected = "I'm working with #gtcs and one of the things we're playing with is TC."title = CreateTitle.from_body bodyassert_equal(expected, title)@@ -104,10 +114,10 @@ class TestCreateTitle < Minitest::Testenddef test_create_title_13- body = "Embroidered TC ... http://blogs.greatcheerthreading.com/thread/embroidering-the-threads-is-just-the-beginning\n@SoftStuff @TightWeave and team hopefully can share their thoughts on this recent post."+ body =+ "Embroidered TC ... http://blogs.greatcheerthreading.com/thread/embroidering-the-threads-is-just-the-beginning\n@SoftStuff @TightWeave and team hopefully can share their thoughts on this recent post."expected = "and team hopefully can share their thoughts on this recent post."title = CreateTitle.from_body bodyassert_equal(expected, title)end-enddiff --git a/script/import_scripts/socialcast/test/test_data.rb b/script/import_scripts/socialcast/test/test_data.rbindex 5bdbf52cc9f..2dd018c32da 100644--- a/script/import_scripts/socialcast/test/test_data.rb+++ b/script/import_scripts/socialcast/test/test_data.rb@@ -1,6 +1,7 @@# frozen_string_literal: true-USERS = '{+USERS =+ '{"users": [{"contact_info": {@@ -1082,7 +1083,8 @@ USERS = '{]}'-MESSAGES = '{+MESSAGES =+ '{"messages": [{"id": 426,@@ -5429,7 +5431,8 @@ MESSAGES = '{"messages_next_page": 2}'-MESSAGES_PG_2 = '{+MESSAGES_PG_2 =+ '{"messages": [{"id": 386,diff --git a/script/import_scripts/socialcast/test/test_socialcast_api.rb b/script/import_scripts/socialcast/test/test_socialcast_api.rbindex 70ad038c8b4..f46e0fefd55 100644--- a/script/import_scripts/socialcast/test/test_socialcast_api.rb+++ b/script/import_scripts/socialcast/test/test_socialcast_api.rb@@ -1,21 +1,20 @@# frozen_string_literal: true-require 'minitest/autorun'-require 'yaml'-require_relative '../socialcast_api.rb'-require_relative './test_data.rb'+require "minitest/autorun"+require "yaml"+require_relative "../socialcast_api.rb"+require_relative "./test_data.rb"class TestSocialcastApi < Minitest::Test-DEBUG = falsedef initialize(args)- config = YAML::load_file(File.join(__dir__, 'config.ex.yml'))- @domain = config['domain']- @username = config['username']- @password = config['password']- @kb_id = config['kb_id']- @question_id = config['question_id']+ config = YAML.load_file(File.join(__dir__, "config.ex.yml"))+ @domain = config["domain"]+ @username = config["username"]+ @password = config["password"]+ @kb_id = config["kb_id"]+ @question_id = config["question_id"]super argsend@@ -30,18 +29,18 @@ class TestSocialcastApi < Minitest::Testenddef test_base_url- assert_equal 'https://demo.socialcast.com/api', @socialcast.base_url+ assert_equal "https://demo.socialcast.com/api", @socialcast.base_urlenddef test_headersheaders = @socialcast.headers- assert_equal 'Basic ZW1pbHlAc29jaWFsY2FzdC5jb206ZGVtbw==', headers[:Authorization]- assert_equal 'application/json', headers[:Accept]+ assert_equal "Basic ZW1pbHlAc29jaWFsY2FzdC5jb206ZGVtbw==", headers[:Authorization]+ assert_equal "application/json", headers[:Accept]enddef test_list_usersusers = @socialcast.list_users- expected = JSON.parse(USERS)['users'].sort { |u| u['id'] }+ expected = JSON.parse(USERS)["users"].sort { |u| u["id"] }assert_equal 15, users.sizeassert_equal expected[0], users[0]end@@ -53,14 +52,14 @@ class TestSocialcastApi < Minitest::Testdef test_list_messagesmessages = @socialcast.list_messages- expected = JSON.parse(MESSAGES)['messages'].sort { |m| m['id'] }+ expected = JSON.parse(MESSAGES)["messages"].sort { |m| m["id"] }assert_equal 20, messages.sizecheck_keys expected[0], messages[0]enddef test_messages_next_pagemessages = @socialcast.list_messages(page: 2)- expected = JSON.parse(MESSAGES_PG_2)['messages'].sort { |m| m['id'] }+ expected = JSON.parse(MESSAGES_PG_2)["messages"].sort { |m| m["id"] }assert_equal 20, messages.sizecheck_keys expected[0], messages[0]end@@ -69,18 +68,16 @@ class TestSocialcastApi < Minitest::Testdef check_keys(expected, actual)msg = "### caller[0]:\nKey not found in actual keys: #{actual.keys}\n"- expected.keys.each do |k|- assert (actual.keys.include? k), "#{k}"- end+ expected.keys.each { |k| assert (actual.keys.include? k), "#{k}" }enddef debug(message, show = false)if show || DEBUG- puts '### ' + caller[0]- puts ''+ puts "### " + caller[0]+ puts ""puts message- puts ''- puts ''+ puts ""+ puts ""endendenddiff --git a/script/import_scripts/socialcast/title.rb b/script/import_scripts/socialcast/title.rbindex b9f0e3c8ae9..9f2c3dd82d5 100644--- a/script/import_scripts/socialcast/title.rb+++ b/script/import_scripts/socialcast/title.rb@@ -1,8 +1,8 @@# frozen_string_literal: true-require_relative './socialcast_message.rb'-require_relative './socialcast_user.rb'-require 'set'+require_relative "./socialcast_message.rb"+require_relative "./socialcast_user.rb"+require "set"require File.expand_path(File.dirname(__FILE__) + "/../base.rb")MESSAGES_DIR = "output/messages"@@ -11,8 +11,8 @@ def titlestopics = 0total = count_files(MESSAGES_DIR)Dir.foreach(MESSAGES_DIR) do |filename|- next if filename == ('.') || filename == ('..')- message_json = File.read MESSAGES_DIR + '/' + filename+ next if filename == (".") || filename == ("..")+ message_json = File.read MESSAGES_DIR + "/" + filenamemessage = SocialcastMessage.new(message_json)next unless message.title#puts "#{filename}, #{message.replies.size}, #{message.topic[:raw].size}, #{message.message_type}, #{message.title}"@@ -23,7 +23,7 @@ def titlesenddef count_files(path)- Dir.foreach(path).select { |f| f != '.' && f != '..' }.count+ Dir.foreach(path).select { |f| f != "." && f != ".." }.countendtitlesdiff --git a/script/import_scripts/sourceforge.rb b/script/import_scripts/sourceforge.rbindex 7d7de0cb8c2..8d165a7fa0e 100644--- a/script/import_scripts/sourceforge.rb+++ b/script/import_scripts/sourceforge.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-require_relative 'base.rb'+require_relative "base.rb"# Import script for SourceForge discussions.#@@ -15,10 +15,10 @@ require_relative 'base.rb'class ImportScripts::Sourceforge < ImportScripts::Base# When the URL of your project is https://sourceforge.net/projects/foo/# than the value of PROJECT_NAME is 'foo'- PROJECT_NAME = 'project_name'+ PROJECT_NAME = "project_name"# This is the path to the discussion.json that you exported from SourceForge.- JSON_FILE = '/path/to/discussion.json'+ JSON_FILE = "/path/to/discussion.json"def initializesuper@@ -27,7 +27,7 @@ class ImportScripts::Sourceforge < ImportScripts::Baseenddef execute- puts '', 'Importing from SourceForge...'+ puts "", "Importing from SourceForge..."load_json@@ -40,25 +40,26 @@ class ImportScripts::Sourceforge < ImportScripts::Baseenddef import_categories- puts '', 'importing categories'+ puts "", "importing categories"create_categories(@json[:forums]) do |forum|{id: forum[:shortname],name: forum[:name],- post_create_action: proc do |category|- changes = { raw: forum[:description] }- opts = { revised_at: Time.now, bypass_bump: true }-- post = category.topic.first_post- post.revise(@system_user, changes, opts)- end+ post_create_action:+ proc do |category|+ changes = { raw: forum[:description] }+ opts = { revised_at: Time.now, bypass_bump: true }++ post = category.topic.first_post+ post.revise(@system_user, changes, opts)+ end,}endenddef import_topics- puts '', 'importing posts'+ puts "", "importing posts"imported_post_count = 0total_post_count = count_posts@@ -78,7 +79,7 @@ class ImportScripts::Sourceforge < ImportScripts::Baseid: "#{thread[:_id]}_#{post[:slug]}",user_id: @system_user,created_at: Time.zone.parse(post[:timestamp]),- raw: process_post_text(forum, thread, post)+ raw: process_post_text(forum, thread, post),}if post == first_post@@ -103,9 +104,7 @@ class ImportScripts::Sourceforge < ImportScripts::Basetotal_count = 0@json[:forums].each do |forum|- forum[:threads].each do |thread|- total_count += thread[:posts].size- end+ forum[:threads].each { |thread| total_count += thread[:posts].size }endtotal_count@@ -117,20 +116,22 @@ class ImportScripts::Sourceforge < ImportScripts::Basedef process_post_text(forum, thread, post)text = post[:text]- text.gsub!(/~{3,}/, '```') # Discourse doesn't recognize ~~~ as beginning/end of code blocks+ text.gsub!(/~{3,}/, "```") # Discourse doesn't recognize ~~~ as beginning/end of code blocks# SourceForge doesn't allow symbols in usernames, so we are safe here.# Well, unless it's the anonymous user, which has an evil asterisk in the JSON file...username = post[:author]- username = 'anonymous' if username == '*anonymous'+ username = "anonymous" if username == "*anonymous"# anonymous and nobody are nonexistent users. Make sure we don't create links for them.- user_without_profile = username == 'anonymous' || username == 'nobody'- user_link = user_without_profile ? username : "[#{username}](https://sourceforge.net/u/#{username}/)"+ user_without_profile = username == "anonymous" || username == "nobody"+ user_link =+ user_without_profile ? username : "[#{username}](https://sourceforge.net/u/#{username}/)"# Create a nice looking header for each imported post that links to the author's user profile and the old post.- post_date = Time.zone.parse(post[:timestamp]).strftime('%A, %B %d, %Y')- post_url = "https://sourceforge.net/p/#{PROJECT_NAME}/discussion/#{forum[:shortname]}/thread/#{thread[:_id]}/##{post[:slug]}"+ post_date = Time.zone.parse(post[:timestamp]).strftime("%A, %B %d, %Y")+ post_url =+ "https://sourceforge.net/p/#{PROJECT_NAME}/discussion/#{forum[:shortname]}/thread/#{thread[:_id]}/##{post[:slug]}""**#{user_link}** wrote on [#{post_date}](#{post_url}):\n\n#{text}"enddiff --git a/script/import_scripts/stack_overflow.rb b/script/import_scripts/stack_overflow.rbindex 2eca547dbca..30ddf2e551c 100644--- a/script/import_scripts/stack_overflow.rb+++ b/script/import_scripts/stack_overflow.rb@@ -5,18 +5,18 @@ require "tiny_tds"require File.expand_path(File.dirname(__FILE__) + "/base.rb")class ImportScripts::StackOverflow < ImportScripts::Base-BATCH_SIZE ||= 1000def initializesuper- @client = TinyTds::Client.new(- host: ENV["DB_HOST"],- username: ENV["DB_USERNAME"],- password: ENV["DB_PASSWORD"],- database: ENV["DB_NAME"],- )+ @client =+ TinyTds::Client.new(+ host: ENV["DB_HOST"],+ username: ENV["DB_USERNAME"],+ password: ENV["DB_PASSWORD"],+ database: ENV["DB_NAME"],+ )enddef execute@@ -36,7 +36,7 @@ class ImportScripts::StackOverflow < ImportScripts::Basetotal = query("SELECT COUNT(*) count FROM Users WHERE Id > 0").first["count"]batches(BATCH_SIZE) do |offset|- users = query(<<~SQL+ users = query(<<~SQL).to_aSELECT TOP #{BATCH_SIZE}Id, UserTypeId@@ -55,7 +55,6 @@ class ImportScripts::StackOverflow < ImportScripts::BaseAND Id > #{last_user_id}ORDER BY IdSQL- ).to_abreak if users.empty?@@ -77,11 +76,16 @@ class ImportScripts::StackOverflow < ImportScripts::Basename: u["RealName"],location: u["Location"],date_of_birth: u["Birthday"],- post_create_action: proc do |user|- if u["ProfileImageUrl"].present?- UserAvatar.import_url_for_user(u["ProfileImageUrl"], user) rescue nil- end- end+ post_create_action:+ proc do |user|+ if u["ProfileImageUrl"].present?+ begin+ UserAvatar.import_url_for_user(u["ProfileImageUrl"], user)+ rescue StandardError+ nil+ end+ end+ end,}endend@@ -91,11 +95,16 @@ class ImportScripts::StackOverflow < ImportScripts::Baseputs "", "Importing posts..."last_post_id = -1- total = query("SELECT COUNT(*) count FROM Posts WHERE PostTypeId IN (1,2,3)").first["count"] +- query("SELECT COUNT(*) count FROM PostComments WHERE PostId IN (SELECT Id FROM Posts WHERE PostTypeId IN (1,2,3))").first["count"]+ total =+ query("SELECT COUNT(*) count FROM Posts WHERE PostTypeId IN (1,2,3)").first["count"] ++ query(+ "SELECT COUNT(*) count FROM PostComments WHERE PostId IN (SELECT Id FROM Posts WHERE PostTypeId IN (1,2,3))",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- posts = query(<<~SQL+ posts = query(<<~SQL).to_aSELECT TOP #{BATCH_SIZE}Id, PostTypeId@@ -113,14 +122,13 @@ class ImportScripts::StackOverflow < ImportScripts::BaseAND Id > #{last_post_id}ORDER BY IdSQL- ).to_abreak if posts.empty?last_post_id = posts[-1]["Id"]post_ids = posts.map { |p| p["Id"] }- comments = query(<<~SQL+ comments = query(<<~SQL).to_aSELECT CONCAT('Comment-', Id) AS Id, PostId AS ParentId, Text@@ -130,7 +138,6 @@ class ImportScripts::StackOverflow < ImportScripts::BaseWHERE PostId IN (#{post_ids.join(",")})ORDER BY IdSQL- ).to_aposts_and_comments = (posts + comments).sort_by { |p| p["CreationDate"] }post_and_comment_ids = posts_and_comments.map { |p| p["Id"] }@@ -173,7 +180,7 @@ class ImportScripts::StackOverflow < ImportScripts::Baselast_like_id = -1batches(BATCH_SIZE) do |offset|- likes = query(<<~SQL+ likes = query(<<~SQL).to_aSELECT TOP #{BATCH_SIZE}Id, PostId@@ -185,7 +192,6 @@ class ImportScripts::StackOverflow < ImportScripts::BaseAND Id > #{last_like_id}ORDER BY IdSQL- ).to_abreak if likes.empty?@@ -196,17 +202,26 @@ class ImportScripts::StackOverflow < ImportScripts::Basenext unless post_id = post_id_from_imported_post_id(l["PostId"])next unless user = User.find_by(id: user_id)next unless post = Post.find_by(id: post_id)- PostActionCreator.like(user, post) rescue nil+ begin+ PostActionCreator.like(user, post)+ rescue StandardError+ nil+ endendendputs "", "Importing comment likes..."last_like_id = -1- total = query("SELECT COUNT(*) count FROM Comments2Votes WHERE VoteTypeId = 2 AND DeletionDate IS NULL").first["count"]+ total =+ query(+ "SELECT COUNT(*) count FROM Comments2Votes WHERE VoteTypeId = 2 AND DeletionDate IS NULL",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- likes = query(<<~SQL+ likes = query(<<~SQL).to_aSELECT TOP #{BATCH_SIZE}Id, CONCAT('Comment-', PostCommentId) AS PostCommentId@@ -218,7 +233,6 @@ class ImportScripts::StackOverflow < ImportScripts::BaseAND Id > #{last_like_id}ORDER BY IdSQL- ).to_abreak if likes.empty?@@ -229,7 +243,11 @@ class ImportScripts::StackOverflow < ImportScripts::Basenext unless post_id = post_id_from_imported_post_id(l["PostCommentId"])next unless user = User.find_by(id: user_id)next unless post = Post.find_by(id: post_id)- PostActionCreator.like(user, post) rescue nil+ begin+ PostActionCreator.like(user, post)+ rescue StandardError+ nil+ endendendend@@ -249,7 +267,6 @@ class ImportScripts::StackOverflow < ImportScripts::Basedef query(sql)@client.execute(sql)end-endImportScripts::StackOverflow.new.performdiff --git a/script/import_scripts/support/convert_mysql_xml_to_mysql.rb b/script/import_scripts/support/convert_mysql_xml_to_mysql.rbindex be0e45ca2fb..070bfb41232 100644--- a/script/import_scripts/support/convert_mysql_xml_to_mysql.rb+++ b/script/import_scripts/support/convert_mysql_xml_to_mysql.rb@@ -3,11 +3,10 @@# convert huge XML dump to mysql friendly import#-require 'ox'-require 'set'+require "ox"+require "set"class Saxy < Ox::Sax-def initialize@stack = []end@@ -32,7 +31,6 @@ class Saxy < Ox::Saxdef cdata(val)@stack[-1][:text] = valend-endclass Convert < Saxy@@ -59,10 +57,13 @@ class Convert < Saxyenddef output_table_definition(data)- cols = data[:cols].map do |col|- attrs = col[:attrs]- "#{attrs[:Field]} #{attrs[:Type]}"- end.join(", ")+ cols =+ data[:cols]+ .map do |col|+ attrs = col[:attrs]+ "#{attrs[:Field]} #{attrs[:Type]}"+ end+ .join(", ")puts "CREATE TABLE #{data[:attrs][:name]} (#{cols});"end@@ -77,4 +78,4 @@ class Convert < Saxyendend-Ox.sax_parse(Convert.new(skip_data: ['metrics2', 'user_log']), File.open(ARGV[0]))+Ox.sax_parse(Convert.new(skip_data: %w[metrics2 user_log]), File.open(ARGV[0]))diff --git a/script/import_scripts/telligent.rb b/script/import_scripts/telligent.rbindex 32ffda8acb1..c46be23facb 100644--- a/script/import_scripts/telligent.rb+++ b/script/import_scripts/telligent.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-require_relative 'base'-require 'tiny_tds'+require_relative "base"+require "tiny_tds"# Import script for Telligent communities#@@ -40,17 +40,19 @@ require 'tiny_tds'class ImportScripts::Telligent < ImportScripts::BaseBATCH_SIZE ||= 1000- LOCAL_AVATAR_REGEX ||= /\A~\/.*(?<directory>communityserver-components-(?:selectable)?avatars)\/(?<path>[^\/]+)\/(?<filename>.+)/i- REMOTE_AVATAR_REGEX ||= /\Ahttps?:\/\//i+ LOCAL_AVATAR_REGEX ||=+ %r{\A~/.*(?<directory>communityserver-components-(?:selectable)?avatars)/(?<path>[^/]+)/(?<filename>.+)}i+ REMOTE_AVATAR_REGEX ||= %r{\Ahttps?://}iATTACHMENT_REGEXES ||= [- /<a[^>]*\shref="[^"]*?\/cfs-file(?:systemfile)?(?:\.ashx)?\/__key\/(?<directory>[^\/]+)\/(?<path>[^\/]+)\/(?<filename>.+?)".*?>.*?<\/a>/i,- /<img[^>]*\ssrc="[^"]*?\/cfs-file(?:systemfile)?(?:\.ashx)?\/__key\/(?<directory>[^\/]+)\/(?<path>[^\/]+)\/(?<filename>.+?)".*?>/i,- /\[View:[^\]]*?\/cfs-file(?:systemfile)?(?:\.ashx)?\/__key\/(?<directory>[^\/]+)\/(?<path>[^\/]+)\/(?<filename>.+?)(?:\:[:\d\s]*?)?\]/i,- /\[(?<tag>img|url)\][^\[]*?cfs-file(?:systemfile)?(?:\.ashx)?\/__key\/(?<directory>[^\/]+)\/(?<path>[^\/]+)\/(?<filename>.+?)\[\/\k<tag>\]/i,- /\[(?<tag>img|url)=[^\[]*?cfs-file(?:systemfile)?(?:\.ashx)?\/__key\/(?<directory>[^\/]+)\/(?<path>[^\/]+)\/(?<filename>.+?)\][^\[]*?\[\/\k<tag>\]/i+ %r{<a[^>]*\shref="[^"]*?/cfs-file(?:systemfile)?(?:\.ashx)?/__key/(?<directory>[^/]+)/(?<path>[^/]+)/(?<filename>.+?)".*?>.*?</a>}i,+ %r{<img[^>]*\ssrc="[^"]*?/cfs-file(?:systemfile)?(?:\.ashx)?/__key/(?<directory>[^/]+)/(?<path>[^/]+)/(?<filename>.+?)".*?>}i,+ %r{\[View:[^\]]*?/cfs-file(?:systemfile)?(?:\.ashx)?/__key/(?<directory>[^/]+)/(?<path>[^/]+)/(?<filename>.+?)(?:\:[:\d\s]*?)?\]}i,+ %r{\[(?<tag>img|url)\][^\[]*?cfs-file(?:systemfile)?(?:\.ashx)?/__key/(?<directory>[^/]+)/(?<path>[^/]+)/(?<filename>.+?)\[/\k<tag>\]}i,+ %r{\[(?<tag>img|url)=[^\[]*?cfs-file(?:systemfile)?(?:\.ashx)?/__key/(?<directory>[^/]+)/(?<path>[^/]+)/(?<filename>.+?)\][^\[]*?\[/\k<tag>\]}i,]PROPERTY_NAMES_REGEX ||= /(?<name>\w+):S:(?<start>\d+):(?<length>\d+):/- INTERNAL_LINK_REGEX ||= /\shref=".*?\/f\/\d+(?:(\/t\/(?<topic_id>\d+))|(?:\/p\/\d+\/(?<post_id>\d+))|(?:\/p\/(?<post_id>\d+)\/reply))\.aspx[^"]*?"/i+ INTERNAL_LINK_REGEX ||=+ %r{\shref=".*?/f/\d+(?:(/t/(?<topic_id>\d+))|(?:/p/\d+/(?<post_id>\d+))|(?:/p/(?<post_id>\d+)/reply))\.aspx[^"]*?"}iCATEGORY_LINK_NORMALIZATION = '/.*?(f\/\d+)$/\1'TOPIC_LINK_NORMALIZATION = '/.*?(f\/\d+\/t\/\d+)$/\1'@@ -82,19 +84,20 @@ class ImportScripts::Telligent < ImportScripts::Base"1D20" => "”","B000" => "°","0003" => ["0300".to_i(16)].pack("U"),- "0103" => ["0301".to_i(16)].pack("U")+ "0103" => ["0301".to_i(16)].pack("U"),}def initializesuper()- @client = TinyTds::Client.new(- host: ENV["DB_HOST"],- username: ENV["DB_USERNAME"],- password: ENV["DB_PASSWORD"],- database: ENV["DB_NAME"],- timeout: 60 # the user query is very slow- )+ @client =+ TinyTds::Client.new(+ host: ENV["DB_HOST"],+ username: ENV["DB_USERNAME"],+ password: ENV["DB_PASSWORD"],+ database: ENV["DB_NAME"],+ timeout: 60, # the user query is very slow+ )@filestore_root_directory = ENV["FILE_BASE_DIR"]@files = {}@@ -180,10 +183,11 @@ class ImportScripts::Telligent < ImportScripts::Basebio_raw: html_to_markdown(ap_properties["bio"]),location: ap_properties["location"],website: ap_properties["webAddress"],- post_create_action: proc do |user|- import_avatar(user, up_properties["avatarUrl"])- suspend_user(user, up_properties["BannedUntil"], up_properties["UserBanReason"])- end+ post_create_action:+ proc do |user|+ import_avatar(user, up_properties["avatarUrl"])+ suspend_user(user, up_properties["BannedUntil"], up_properties["UserBanReason"])+ end,}end@@ -193,13 +197,18 @@ class ImportScripts::Telligent < ImportScripts::Base# TODO move into base importer (create_user) and use consistent error handlingdef import_avatar(user, avatar_url)- return if @filestore_root_directory.blank? || avatar_url.blank? || avatar_url.include?("anonymous")+ if @filestore_root_directory.blank? || avatar_url.blank? || avatar_url.include?("anonymous")+ return+ endif match_data = avatar_url.match(LOCAL_AVATAR_REGEX)- avatar_path = File.join(@filestore_root_directory,- match_data[:directory].gsub("-", "."),- match_data[:path].split("-"),- match_data[:filename])+ avatar_path =+ File.join(+ @filestore_root_directory,+ match_data[:directory].gsub("-", "."),+ match_data[:path].split("-"),+ match_data[:filename],+ )if File.file?(avatar_path)@uploader.create_avatar(user, avatar_path)@@ -207,7 +216,11 @@ class ImportScripts::Telligent < ImportScripts::BaseSTDERR.puts "Could not find avatar: #{avatar_path}"endelsif avatar_url.match?(REMOTE_AVATAR_REGEX)- UserAvatar.import_url_for_user(avatar_url, user) rescue nil+ begin+ UserAvatar.import_url_for_user(avatar_url, user)+ rescue StandardError+ nil+ endendend@@ -224,7 +237,7 @@ class ImportScripts::Telligent < ImportScripts::Baseenddef import_categories- if ENV['CATEGORY_MAPPING']+ if ENV["CATEGORY_MAPPING"]import_mapped_forums_as_categorieselseimport_groups_and_forums_as_categories@@ -234,7 +247,7 @@ class ImportScripts::Telligent < ImportScripts::Basedef import_mapped_forums_as_categoriesputs "", "Importing categories..."- json = JSON.parse(File.read(ENV['CATEGORY_MAPPING']))+ json = JSON.parse(File.read(ENV["CATEGORY_MAPPING"]))categories = []@forum_ids_to_tags = {}@@ -256,7 +269,7 @@ class ImportScripts::Telligent < ImportScripts::Baseid: id,name: name,parent_id: parent_id,- forum_ids: index == last_index ? forum_ids : nil+ forum_ids: index == last_index ? forum_ids : nil,}parent_id = idend@@ -271,9 +284,7 @@ class ImportScripts::Telligent < ImportScripts::Baseid: c[:id],name: c[:name],parent_category_id: category_id_from_imported_category_id(c[:parent_id]),- post_create_action: proc do |category|- map_forum_ids(category.id, c[:forum_ids])- end+ post_create_action: proc { |category| map_forum_ids(category.id, c[:forum_ids]) },}endend@@ -302,10 +313,10 @@ class ImportScripts::Telligent < ImportScripts::Basecreate_categories(parent_categories) do |row|{- id: "G#{row['GroupID']}",+ id: "G#{row["GroupID"]}",name: clean_category_name(row["Name"]),description: html_to_markdown(row["HtmlDescription"]),- position: row["SortOrder"]+ position: row["SortOrder"],}end@@ -320,28 +331,31 @@ class ImportScripts::Telligent < ImportScripts::Baseparent_category_id = parent_category_id_for(row)if category_id = replace_with_category_id(child_categories, parent_category_id)- add_category(row['ForumId'], Category.find_by_id(category_id))- url = "f/#{row['ForumId']}"+ add_category(row["ForumId"], Category.find_by_id(category_id))+ url = "f/#{row["ForumId"]}"Permalink.create(url: url, category_id: category_id) unless Permalink.exists?(url: url)nilelse{- id: row['ForumId'],+ id: row["ForumId"],parent_category_id: parent_category_id,name: clean_category_name(row["Name"]),description: html_to_markdown(row["Description"]),position: row["SortOrder"],- post_create_action: proc do |category|- url = "f/#{row['ForumId']}"- Permalink.create(url: url, category_id: category.id) unless Permalink.exists?(url: url)- end+ post_create_action:+ proc do |category|+ url = "f/#{row["ForumId"]}"+ unless Permalink.exists?(url: url)+ Permalink.create(url: url, category_id: category.id)+ end+ end,}endendenddef parent_category_id_for(row)- category_id_from_imported_category_id("G#{row['GroupId']}") if row.key?("GroupId")+ category_id_from_imported_category_id("G#{row["GroupId"]}") if row.key?("GroupId")enddef replace_with_category_id(child_categories, parent_category_id)@@ -351,23 +365,21 @@ class ImportScripts::Telligent < ImportScripts::Basedef only_child?(child_categories, parent_category_id)count = 0- child_categories.each do |row|- count += 1 if parent_category_id_for(row) == parent_category_id- end+ child_categories.each { |row| count += 1 if parent_category_id_for(row) == parent_category_id }count == 1enddef clean_category_name(name)- CGI.unescapeHTML(name)- .strip+ CGI.unescapeHTML(name).stripenddef import_topicsputs "", "Importing topics..."last_topic_id = -1- total_count = count("SELECT COUNT(1) AS count FROM te_Forum_Threads t WHERE #{ignored_forum_sql_condition}")+ total_count =+ count("SELECT COUNT(1) AS count FROM te_Forum_Threads t WHERE #{ignored_forum_sql_condition}")batches do |offset|rows = query(<<~SQL)@@ -399,13 +411,16 @@ class ImportScripts::Telligent < ImportScripts::Basecreated_at: row["DateCreated"],closed: row["IsLocked"],views: row["TotalViews"],- post_create_action: proc do |action_post|- topic = action_post.topic- Jobs.enqueue_at(topic.pinned_until, :unpin_topic, topic_id: topic.id) if topic.pinned_until- url = "f/#{row['ForumId']}/t/#{row['ThreadId']}"- Permalink.create(url: url, topic_id: topic.id) unless Permalink.exists?(url: url)- import_topic_views(topic, row["TopicContentId"])- end+ post_create_action:+ proc do |action_post|+ topic = action_post.topic+ if topic.pinned_until+ Jobs.enqueue_at(topic.pinned_until, :unpin_topic, topic_id: topic.id)+ end+ url = "f/#{row["ForumId"]}/t/#{row["ThreadId"]}"+ Permalink.create(url: url, topic_id: topic.id) unless Permalink.exists?(url: url)+ import_topic_views(topic, row["TopicContentId"])+ end,}if row["StickyDate"] > Time.now@@ -446,9 +461,8 @@ class ImportScripts::Telligent < ImportScripts::Baseenddef ignored_forum_sql_condition- @ignored_forum_sql_condition ||= @ignored_forum_ids.present? \- ? "t.ForumId NOT IN (#{@ignored_forum_ids.join(',')})" \- : "1 = 1"+ @ignored_forum_sql_condition ||=+ @ignored_forum_ids.present? ? "t.ForumId NOT IN (#{@ignored_forum_ids.join(",")})" : "1 = 1"enddef import_posts@@ -492,7 +506,8 @@ class ImportScripts::Telligent < ImportScripts::Basenext if all_records_exist?(:post, rows.map { |row| row["ThreadReplyId"] })create_posts(rows, total: total_count, offset: offset) do |row|- imported_parent_id = row["ParentReplyId"]&.nonzero? ? row["ParentReplyId"] : import_topic_id(row["ThreadId"])+ imported_parent_id =+ row["ParentReplyId"]&.nonzero? ? row["ParentReplyId"] : import_topic_id(row["ThreadId"])parent_post = topic_lookup_from_imported_post_id(imported_parent_id)user_id = user_id_from_imported_user_id(row["UserId"]) || Discourse::SYSTEM_USER_ID@@ -503,13 +518,13 @@ class ImportScripts::Telligent < ImportScripts::Baseuser_id: user_id,topic_id: parent_post[:topic_id],created_at: row["ThreadReplyDate"],- reply_to_post_number: parent_post[:post_number]+ reply_to_post_number: parent_post[:post_number],}post[:custom_fields] = { is_accepted_answer: "true" } if row["IsFirstVerifiedAnswer"]postelse- puts "Failed to import post #{row['ThreadReplyId']}. Parent was not found."+ puts "Failed to import post #{row["ThreadReplyId"]}. Parent was not found."endendend@@ -565,7 +580,7 @@ class ImportScripts::Telligent < ImportScripts::Baseid: row["MessageId"],raw: raw_with_attachment(row, user_id, :message),user_id: user_id,- created_at: row["DateCreated"]+ created_at: row["DateCreated"],}if current_conversation_id == row["ConversationId"]@@ -574,7 +589,7 @@ class ImportScripts::Telligent < ImportScripts::Baseif parent_postpost[:topic_id] = parent_post[:topic_id]else- puts "Failed to import message #{row['MessageId']}. Parent was not found."+ puts "Failed to import message #{row["MessageId"]}. Parent was not found."post = nilendelse@@ -583,7 +598,7 @@ class ImportScripts::Telligent < ImportScripts::Basepost[:target_usernames] = get_recipient_usernames(row)if post[:target_usernames].empty?- puts "Private message without recipients. Skipping #{row['MessageId']}"+ puts "Private message without recipients. Skipping #{row["MessageId"]}"post = nilend@@ -611,7 +626,7 @@ class ImportScripts::Telligent < ImportScripts::Basedef get_recipient_user_ids(participant_ids)return [] if participant_ids.blank?- user_ids = participant_ids.split(';')+ user_ids = participant_ids.split(";")user_ids.uniq!user_ids.map!(&:strip)end@@ -619,9 +634,9 @@ class ImportScripts::Telligent < ImportScripts::Basedef get_recipient_usernames(row)import_user_ids = get_recipient_user_ids(row["ParticipantIds"])- import_user_ids.map! do |import_user_id|- find_user_by_import_id(import_user_id).try(:username)- end.compact+ import_user_ids+ .map! { |import_user_id| find_user_by_import_id(import_user_id).try(:username) }+ .compactenddef index_directory(root_directory)@@ -646,17 +661,16 @@ class ImportScripts::Telligent < ImportScripts::Basefilename = row["FileName"]return raw if @filestore_root_directory.blank? || filename.blank?- if row["IsRemote"]- return "#{raw}\n#{filename}"- end+ return "#{raw}\n#{filename}" if row["IsRemote"]- path = File.join(- "telligent.evolution.components.attachments",- "%02d" % row["ApplicationTypeId"],- "%02d" % row["ApplicationId"],- "%02d" % row["ApplicationContentTypeId"],- ("%010d" % row["ContentId"]).scan(/.{2}/)- )+ path =+ File.join(+ "telligent.evolution.components.attachments",+ "%02d" % row["ApplicationTypeId"],+ "%02d" % row["ApplicationId"],+ "%02d" % row["ApplicationContentTypeId"],+ ("%010d" % row["ContentId"]).scan(/.{2}/),+ )path = fix_attachment_path(path, filename)if path && !embedded_paths.include?(path)@@ -677,11 +691,11 @@ class ImportScripts::Telligent < ImportScripts::Basedef print_file_not_found_error(type, path, row)case typewhen :topic- id = row['ThreadId']+ id = row["ThreadId"]when :post- id = row['ThreadReplyId']+ id = row["ThreadReplyId"]when :message- id = row['MessageId']+ id = row["MessageId"]endSTDERR.puts "Could not find file for #{type} #{id}: #{path}"@@ -692,30 +706,31 @@ class ImportScripts::Telligent < ImportScripts::Basepaths = []upload_ids = []- return [raw, paths, upload_ids] if @filestore_root_directory.blank?+ return raw, paths, upload_ids if @filestore_root_directory.blank?ATTACHMENT_REGEXES.each do |regex|- raw = raw.gsub(regex) do- match_data = Regexp.last_match-- path = File.join(match_data[:directory], match_data[:path])- fixed_path = fix_attachment_path(path, match_data[:filename])-- if fixed_path && File.file?(fixed_path)- filename = File.basename(fixed_path)- upload = @uploader.create_upload(user_id, fixed_path, filename)-- if upload.present? && upload.persisted?- paths << fixed_path- upload_ids << upload.id- @uploader.html_for_upload(upload, filename)+ raw =+ raw.gsub(regex) do+ match_data = Regexp.last_match++ path = File.join(match_data[:directory], match_data[:path])+ fixed_path = fix_attachment_path(path, match_data[:filename])++ if fixed_path && File.file?(fixed_path)+ filename = File.basename(fixed_path)+ upload = @uploader.create_upload(user_id, fixed_path, filename)++ if upload.present? && upload.persisted?+ paths << fixed_path+ upload_ids << upload.id+ @uploader.html_for_upload(upload, filename)+ end+ else+ path = File.join(path, match_data[:filename])+ print_file_not_found_error(type, path, row)+ match_data[0]end- else- path = File.join(path, match_data[:filename])- print_file_not_found_error(type, path, row)- match_data[0]end- endend[raw, paths, upload_ids]@@ -806,8 +821,8 @@ class ImportScripts::Telligent < ImportScripts::Basemd = HtmlToMarkdown.new(html).to_markdownmd.gsub!(/\[quote.*?\]/, "\n" + '\0' + "\n")- md.gsub!(/(?<!^)\[\/quote\]/, "\n[/quote]\n")- md.gsub!(/\[\/quote\](?!$)/, "\n[/quote]\n")+ md.gsub!(%r{(?<!^)\[/quote\]}, "\n[/quote]\n")+ md.gsub!(%r{\[/quote\](?!$)}, "\n[/quote]\n")md.gsub!(/\[View:(http.*?)[:\d\s]*?(?:\]|\z)/i, '\1')md.strip!md@@ -832,13 +847,15 @@ class ImportScripts::Telligent < ImportScripts::Baseproperties = {}return properties if names.blank? || values.blank?- names.scan(PROPERTY_NAMES_REGEX).each do |property|- name = property[0]- start_index = property[1].to_i- end_index = start_index + property[2].to_i - 1+ names+ .scan(PROPERTY_NAMES_REGEX)+ .each do |property|+ name = property[0]+ start_index = property[1].to_i+ end_index = start_index + property[2].to_i - 1- properties[name] = values[start_index..end_index]- end+ properties[name] = values[start_index..end_index]+ endpropertiesend@@ -862,12 +879,12 @@ class ImportScripts::Telligent < ImportScripts::Basedef add_permalink_normalizationsnormalizations = SiteSetting.permalink_normalizations- normalizations = normalizations.blank? ? [] : normalizations.split('|')+ normalizations = normalizations.blank? ? [] : normalizations.split("|")add_normalization(normalizations, CATEGORY_LINK_NORMALIZATION)add_normalization(normalizations, TOPIC_LINK_NORMALIZATION)- SiteSetting.permalink_normalizations = normalizations.join('|')+ SiteSetting.permalink_normalizations = normalizations.join("|")enddef add_normalization(normalizations, normalization)diff --git a/script/import_scripts/vanilla.rb b/script/import_scripts/vanilla.rbindex 1d67cd045ac..c2e9cb85821 100644--- a/script/import_scripts/vanilla.rb+++ b/script/import_scripts/vanilla.rb@@ -7,14 +7,17 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# user documentation: https://meta.discourse.org/t/how-to-migrate-import-from-vanilla-to-discourse/27273class ImportScripts::Vanilla < ImportScripts::Base-def initializesuper@vanilla_file = ARGV[0]- raise ArgumentError.new('Vanilla file argument missing. Provide full path to vanilla csv file.') if @vanilla_file.blank?+ if @vanilla_file.blank?+ raise ArgumentError.new(+ "Vanilla file argument missing. Provide full path to vanilla csv file.",+ )+ end- @use_lastest_activity_as_user_bio = true if ARGV.include?('use-latest-activity-as-user-bio')+ @use_lastest_activity_as_user_bio = true if ARGV.include?("use-latest-activity-as-user-bio")enddef execute@@ -34,7 +37,9 @@ class ImportScripts::Vanilla < ImportScripts::Baseprivatedef check_file_exist- raise ArgumentError.new("File does not exist: #{@vanilla_file}") unless File.exist?(@vanilla_file)+ unless File.exist?(@vanilla_file)+ raise ArgumentError.new("File does not exist: #{@vanilla_file}")+ endenddef parse_file@@ -65,7 +70,10 @@ class ImportScripts::Vanilla < ImportScripts::Basenext if useless_tables.include?(table)# parse the dataputs "parsing #{table}..."- parsed_data = CSV.parse(data.join("\n"), headers: true, header_converters: :symbol).map { |row| row.to_hash }+ parsed_data =+ CSV+ .parse(data.join("\n"), headers: true, header_converters: :symbol)+ .map { |row| row.to_hash }instance_variable_set("@#{table}".to_sym, parsed_data)endend@@ -73,11 +81,14 @@ class ImportScripts::Vanilla < ImportScripts::Basedef read_fileputs "reading file..."- string = File.read(@vanilla_file).gsub("\\N", "")- .gsub(/\\$\n/m, "\\n")- .gsub("\\,", ",")- .gsub(/(?<!\\)\\"/, '""')- .gsub(/\\\\\\"/, '\\""')+ string =+ File+ .read(@vanilla_file)+ .gsub("\\N", "")+ .gsub(/\\$\n/m, "\\n")+ .gsub("\\,", ",")+ .gsub(/(?<!\\)\\"/, '""')+ .gsub(/\\\\\\"/, '\\""')StringIO.new(string)end@@ -106,8 +117,16 @@ class ImportScripts::Vanilla < ImportScripts::Basecreated_at: parse_date(user[:date_inserted]),bio_raw: clean_up(bio_raw),avatar_url: user[:photo],- moderator: @user_roles.select { |ur| ur[:user_id] == user[:user_id] }.map { |ur| ur[:role_id] }.include?(moderator_role_id),- admin: @user_roles.select { |ur| ur[:user_id] == user[:user_id] }.map { |ur| ur[:role_id] }.include?(admin_role_id),+ moderator:+ @user_roles+ .select { |ur| ur[:user_id] == user[:user_id] }+ .map { |ur| ur[:role_id] }+ .include?(moderator_role_id),+ admin:+ @user_roles+ .select { |ur| ur[:user_id] == user[:user_id] }+ .map { |ur| ur[:role_id] }+ .include?(admin_role_id),}u@@ -143,7 +162,8 @@ class ImportScripts::Vanilla < ImportScripts::Basec = {id: category[:category_id],name: category[:name],- user_id: user_id_from_imported_user_id(category[:insert_user_id]) || Discourse::SYSTEM_USER_ID,+ user_id:+ user_id_from_imported_user_id(category[:insert_user_id]) || Discourse::SYSTEM_USER_ID,position: category[:sort].to_i,created_at: parse_category_date(category[:date_inserted]),description: clean_up(category[:description]),@@ -164,7 +184,8 @@ class ImportScripts::Vanilla < ImportScripts::Basecreate_posts(@discussions) do |discussion|{id: "discussion#" + discussion[:discussion_id],- user_id: user_id_from_imported_user_id(discussion[:insert_user_id]) || Discourse::SYSTEM_USER_ID,+ user_id:+ user_id_from_imported_user_id(discussion[:insert_user_id]) || Discourse::SYSTEM_USER_ID,title: discussion[:name],category: category_id_from_imported_category_id(discussion[:category_id]),raw: clean_up(discussion[:body]),@@ -181,7 +202,8 @@ class ImportScripts::Vanilla < ImportScripts::Base{id: "comment#" + comment[:comment_id],- user_id: user_id_from_imported_user_id(comment[:insert_user_id]) || Discourse::SYSTEM_USER_ID,+ user_id:+ user_id_from_imported_user_id(comment[:insert_user_id]) || Discourse::SYSTEM_USER_ID,topic_id: t[:topic_id],raw: clean_up(comment[:body]),created_at: parse_date(comment[:date_inserted]),@@ -196,20 +218,30 @@ class ImportScripts::Vanilla < ImportScripts::Basenext if conversation[:first_message_id].blank?# list all other user ids in the conversation- user_ids_in_conversation = @user_conversations.select { |uc| uc[:conversation_id] == conversation[:conversation_id] && uc[:user_id] != conversation[:insert_user_id] }- .map { |uc| uc[:user_id] }+ user_ids_in_conversation =+ @user_conversations+ .select do |uc|+ uc[:conversation_id] == conversation[:conversation_id] &&+ uc[:user_id] != conversation[:insert_user_id]+ end+ .map { |uc| uc[:user_id] }# retrieve their emails- user_emails_in_conversation = @users.select { |u| user_ids_in_conversation.include?(u[:user_id]) }- .map { |u| u[:email] }+ user_emails_in_conversation =+ @users.select { |u| user_ids_in_conversation.include?(u[:user_id]) }.map { |u| u[:email] }# retrieve their usernames from the database- target_usernames = User.joins(:user_emails)- .where(user_emails: { email: user_emails_in_conversation })- .pluck(:username)+ target_usernames =+ User+ .joins(:user_emails)+ .where(user_emails: { email: user_emails_in_conversation })+ .pluck(:username)next if target_usernames.blank?user = find_user_by_import_id(conversation[:insert_user_id]) || Discourse.system_user- first_message = @conversation_messages.select { |cm| cm[:message_id] == conversation[:first_message_id] }.first+ first_message =+ @conversation_messages+ .select { |cm| cm[:message_id] == conversation[:first_message_id] }+ .first{id: "conversation#" + conversation[:conversation_id],@@ -229,12 +261,15 @@ class ImportScripts::Vanilla < ImportScripts::Base@conversation_messages.reject! { |cm| first_message_ids.include?(cm[:message_id]) }create_posts(@conversation_messages) do |message|- next unless t = topic_lookup_from_imported_post_id("conversation#" + message[:conversation_id])+ unless t = topic_lookup_from_imported_post_id("conversation#" + message[:conversation_id])+ next+ end{archetype: Archetype.private_message,id: "message#" + message[:message_id],- user_id: user_id_from_imported_user_id(message[:insert_user_id]) || Discourse::SYSTEM_USER_ID,+ user_id:+ user_id_from_imported_user_id(message[:insert_user_id]) || Discourse::SYSTEM_USER_ID,topic_id: t[:topic_id],raw: clean_up(message[:body]),created_at: parse_date(message[:date_inserted]),@@ -248,13 +283,13 @@ class ImportScripts::Vanilla < ImportScripts::Basedef clean_up(raw)return "" if raw.blank?- raw.gsub("\\n", "\n")- .gsub(/<\/?pre\s*>/i, "\n```\n")- .gsub(/<\/?code\s*>/i, "`")+ raw+ .gsub("\\n", "\n")+ .gsub(%r{</?pre\s*>}i, "\n```\n")+ .gsub(%r{</?code\s*>}i, "`").gsub("<", "<").gsub(">", ">")end-endImportScripts::Vanilla.new.performdiff --git a/script/import_scripts/vanilla_body_parser.rb b/script/import_scripts/vanilla_body_parser.rbindex ba4608e3ff8..74c39583b95 100644--- a/script/import_scripts/vanilla_body_parser.rb+++ b/script/import_scripts/vanilla_body_parser.rb@@ -14,9 +14,9 @@ class VanillaBodyParserenddef parse- return clean_up(@row['Body']) unless rich?+ return clean_up(@row["Body"]) unless rich?- full_text = json.each_with_index.map(&method(:parse_fragment)).join('')+ full_text = json.each_with_index.map(&method(:parse_fragment)).join("")normalize full_textend@@ -25,30 +25,46 @@ class VanillaBodyParserdef clean_up(text)# <pre class="CodeBlock">...</pre>- text = text.gsub(/\<pre class="CodeBlock"\>(.*?)\<\/pre\>/im) { "\n```\n#{$1}\n```\n" }+ text = text.gsub(%r{\<pre class="CodeBlock"\>(.*?)\</pre\>}im) { "\n```\n#{$1}\n```\n" }# <pre>...</pre>- text = text.gsub(/\<pre\>(.*?)\<\/pre\>/im) { "\n```\n#{$1}\n```\n" }+ text = text.gsub(%r{\<pre\>(.*?)\</pre\>}im) { "\n```\n#{$1}\n```\n" }# <code></code>- text = text.gsub("\<code\>\</code\>", "").gsub(/\<code\>(.*?)\<\/code\>/im) { "#{$1}" }+ text = text.gsub("\<code\>\</code\>", "").gsub(%r{\<code\>(.*?)\</code\>}im) { "#{$1}" }# <div class="Quote">...</div>- text = text.gsub(/\<div class="Quote"\>(.*?)\<\/div\>/im) { "\n[quote]\n#{$1}\n[/quote]\n" }+ text = text.gsub(%r{\<div class="Quote"\>(.*?)\</div\>}im) { "\n[quote]\n#{$1}\n[/quote]\n" }# [code], [quote]- text = text.gsub(/\[\/?code\]/i, "\n```\n").gsub(/\[quote.*?\]/i, "\n" + '\0' + "\n").gsub(/\[\/quote\]/i, "\n" + '\0' + "\n")+ text =+ text+ .gsub(%r{\[/?code\]}i, "\n```\n")+ .gsub(/\[quote.*?\]/i, "\n" + '\0' + "\n")+ .gsub(%r{\[/quote\]}i, "\n" + '\0' + "\n")- text.gsub(/<\/?font[^>]*>/, '').gsub(/<\/?span[^>]*>/, '').gsub(/<\/?div[^>]*>/, '').gsub(/^ +/, '').gsub(/ +/, ' ')+ text+ .gsub(%r{</?font[^>]*>}, "")+ .gsub(%r{</?span[^>]*>}, "")+ .gsub(%r{</?div[^>]*>}, "")+ .gsub(/^ +/, "")+ .gsub(/ +/, " ")enddef rich?- @row['Format'].casecmp?('Rich')+ @row["Format"].casecmp?("Rich")enddef jsonreturn nil unless rich?- @json ||= JSON.parse(@row['Body']).map(&:deep_symbolize_keys)+ @json ||= JSON.parse(@row["Body"]).map(&:deep_symbolize_keys)enddef parse_fragment(fragment, index)- text = fragment.keys.one? && fragment[:insert].is_a?(String) ? fragment[:insert] : rich_parse(fragment)+ text =+ (+ if fragment.keys.one? && fragment[:insert].is_a?(String)+ fragment[:insert]+ else+ rich_parse(fragment)+ end+ )text = parse_code(text, fragment, index)text = parse_list(text, fragment, index)@@ -59,16 +75,18 @@ class VanillaBodyParserdef rich_parse(fragment)insert = fragment[:insert]- return parse_mention(insert[:mention]) if insert.respond_to?(:dig) && insert.dig(:mention, :userID)+ if insert.respond_to?(:dig) && insert.dig(:mention, :userID)+ return parse_mention(insert[:mention])+ endreturn parse_formatting(fragment) if fragment[:attributes]- embed_type = insert.dig(:'embed-external', :data, :embedType)+ embed_type = insert.dig(:"embed-external", :data, :embedType)- quoting = embed_type == 'quote'+ quoting = embed_type == "quote"return parse_quote(insert) if quoting- embed = embed_type.in? ['image', 'link', 'file']+ embed = embed_type.in? %w[image link file]parse_embed(insert, embed_type) if embedend@@ -101,10 +119,10 @@ class VanillaBodyParserdef parse_code(text, fragment, index)next_fragment = next_fragment(index)- next_code = next_fragment.dig(:attributes, :'code-block')+ next_code = next_fragment.dig(:attributes, :"code-block")if next_codeprevious_fragment = previous_fragment(index)- previous_code = previous_fragment.dig(:attributes, :'code-block')+ previous_code = previous_fragment.dig(:attributes, :"code-block")if previous_codetext = text.gsub(/\\n(.*?)\\n/) { "\n```\n#{$1}\n```\n" }@@ -112,7 +130,7 @@ class VanillaBodyParserlast_pos = text.rindex(/\n/)if last_pos- array = [text[0..last_pos].strip, text[last_pos + 1 .. text.length].strip]+ array = [text[0..last_pos].strip, text[last_pos + 1..text.length].strip]text = array.join("\n```\n")elsetext = "\n```\n#{text}"@@ -120,10 +138,10 @@ class VanillaBodyParserendend- current_code = fragment.dig(:attributes, :'code-block')+ current_code = fragment.dig(:attributes, :"code-block")if current_codesecond_next_fragment = second_next_fragment(index)- second_next_code = second_next_fragment.dig(:attributes, :'code-block')+ second_next_code = second_next_fragment.dig(:attributes, :"code-block")# if current is code and 2 after is not, prepend ```text = "\n```\n#{text}" unless second_next_code@@ -138,13 +156,13 @@ class VanillaBodyParsernext_list = next_fragment.dig(:attributes, :list, :type)if next_list# if next is list, prepend <li>- text = '<li>' + text+ text = "<li>" + textprevious_fragment = previous_fragment(index)previous_list = previous_fragment.dig(:attributes, :list, :type)# if next is list and previous is not, prepend <ol> or <ul>- list_tag = next_list == 'ordered' ? '<ol>' : '<ul>'+ list_tag = next_list == "ordered" ? "<ol>" : "<ul>"text = "\n#{list_tag}\n#{text}" unless previous_listend@@ -152,13 +170,13 @@ class VanillaBodyParserif current_list# if current is list prepend </li>- tag_closings = '</li>'+ tag_closings = "</li>"second_next_fragment = second_next_fragment(index)second_next_list = second_next_fragment.dig(:attributes, :list, :type)# if current is list and 2 after is not, prepend </ol>- list_tag = current_list == 'ordered' ? '</ol>' : '</ul>'+ list_tag = current_list == "ordered" ? "</ol>" : "</ul>"tag_closings = "#{tag_closings}\n#{list_tag}" unless second_next_listtext = tag_closings + text@@ -180,24 +198,32 @@ class VanillaBodyParserenddef parse_quote(insert)- embed = insert.dig(:'embed-external', :data)+ embed = insert.dig(:"embed-external", :data)import_post_id = "#{embed[:recordType]}##{embed[:recordID]}"topic = @@lookup.topic_lookup_from_imported_post_id(import_post_id)user = user_from_imported_id(embed.dig(:insertUser, :userID))- quote_info = topic && user ? "=\"#{user.username}, post: #{topic[:post_number]}, topic: #{topic[:topic_id]}\"" : ''+ quote_info =+ (+ if topic && user+ "=\"#{user.username}, post: #{topic[:post_number]}, topic: #{topic[:topic_id]}\""+ else+ ""+ end+ )- "[quote#{quote_info}]\n#{embed[:body]}\n[/quote]\n\n"""+ "[quote#{quote_info}]\n#{embed[:body]}\n[/quote]\n\n" \+ ""enddef parse_embed(insert, embed_type)- embed = insert.dig(:'embed-external', :data)+ embed = insert.dig(:"embed-external", :data)url = embed[:url]- if /https?\:\/\/#{@@host}\/uploads\/.*/.match?(url)- remote_path = url.scan(/uploads\/(.*)/)+ if %r{https?\://#{@@host}/uploads/.*}.match?(url)+ remote_path = url.scan(%r{uploads/(.*)})path = File.join(@@uploads_path, remote_path)upload = @@uploader.create_upload(@user_id, path, embed[:name])@@ -206,7 +232,7 @@ class VanillaBodyParserreturn "\n" + @@uploader.html_for_upload(upload, embed[:name]) + "\n"elseputs "Failed to upload #{path}"- puts upload.errors.full_messages.join(', ') if upload+ puts upload.errors.full_messages.join(", ") if uploadendend@@ -222,9 +248,9 @@ class VanillaBodyParserdef normalize(full_text)code_matcher = /```(.*\n)+```/code_block = full_text[code_matcher]- full_text[code_matcher] = '{{{CODE_BLOCK}}}' if code_block+ full_text[code_matcher] = "{{{CODE_BLOCK}}}" if code_blockfull_text = double_new_lines(full_text)- full_text['{{{CODE_BLOCK}}}'] = code_block if code_block+ full_text["{{{CODE_BLOCK}}}"] = code_block if code_blockfull_textenddiff --git a/script/import_scripts/vanilla_mysql.rb b/script/import_scripts/vanilla_mysql.rbindex d0a5e348934..72f294337ae 100644--- a/script/import_scripts/vanilla_mysql.rb+++ b/script/import_scripts/vanilla_mysql.rb@@ -2,12 +2,11 @@require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'-require 'reverse_markdown'-require_relative 'vanilla_body_parser'+require "htmlentities"+require "reverse_markdown"+require_relative "vanilla_body_parser"class ImportScripts::VanillaSQL < ImportScripts::Base-VANILLA_DB = "vanilla"TABLE_PREFIX = "GDN_"ATTACHMENTS_BASE_DIR = nil # "/absolute/path/to/attachments" set the absolute path if you have attachments@@ -17,19 +16,15 @@ class ImportScripts::VanillaSQL < ImportScripts::Basedef initializesuper@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- database: VANILLA_DB- )+ @client = Mysql2::Client.new(host: "localhost", username: "root", database: VANILLA_DB)# by default, don't use the body parser as it's not pertinent to all versions@vb_parser = falseVanillaBodyParser.configure(lookup: @lookup,uploader: @uploader,- host: 'forum.example.com', # your Vanilla forum domain- uploads_path: 'uploads' # relative path to your vanilla uploads folder+ host: "forum.example.com", # your Vanilla forum domain+ uploads_path: "uploads", # relative path to your vanilla uploads folder)@import_tags = false@@ -77,80 +72,83 @@ class ImportScripts::VanillaSQL < ImportScripts::BaseSQLcreate_groups(groups) do |group|- {- id: group["RoleID"],- name: @htmlentities.decode(group["Name"]).strip- }+ { id: group["RoleID"], name: @htmlentities.decode(group["Name"]).strip }endenddef import_users- puts '', "creating users"+ puts "", "creating users"@user_is_deleted = false@last_deleted_username = nilusername = nil@last_user_id = -1- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}User;").first['count']+ total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}User;").first["count"]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT UserID, Name, Title, Location, About, Email, Admin, Banned, CountComments,+ results =+ mysql_query(+ "SELECT UserID, Name, Title, Location, About, Email, Admin, Banned, CountComments,DateInserted, DateLastActive, InsertIPAddressFROM #{TABLE_PREFIX}UserWHERE UserID > #{@last_user_id}ORDER BY UserID ASC- LIMIT #{BATCH_SIZE};")+ LIMIT #{BATCH_SIZE};",+ )break if results.size < 1- @last_user_id = results.to_a.last['UserID']- next if all_records_exist? :users, results.map { |u| u['UserID'].to_i }+ @last_user_id = results.to_a.last["UserID"]+ next if all_records_exist? :users, results.map { |u| u["UserID"].to_i }create_users(results, total: total_count, offset: offset) do |user|- email = user['Email'].squish+ email = user["Email"].squishnext if email.blank?- next if user['Name'].blank?- next if @lookup.user_id_from_imported_user_id(user['UserID'])- if user['Name'] == '[Deleted User]'+ next if user["Name"].blank?+ next if @lookup.user_id_from_imported_user_id(user["UserID"])+ if user["Name"] == "[Deleted User]"# EVERY deleted user record in Vanilla has the same username: [Deleted User]# Save our UserNameSuggester some pain:@user_is_deleted = true- username = @last_deleted_username || user['Name']+ username = @last_deleted_username || user["Name"]else@user_is_deleted = false- username = user['Name']+ username = user["Name"]end- banned = user['Banned'] != 0- commented = (user['CountComments'] || 0) > 0+ banned = user["Banned"] != 0+ commented = (user["CountComments"] || 0) > 0- { id: user['UserID'],+ {+ id: user["UserID"],email: email,username: username,- name: user['Name'],- created_at: user['DateInserted'] == nil ? 0 : Time.zone.at(user['DateInserted']),- bio_raw: user['About'],- registration_ip_address: user['InsertIPAddress'],- last_seen_at: user['DateLastActive'] == nil ? 0 : Time.zone.at(user['DateLastActive']),- location: user['Location'],- admin: user['Admin'] == 1,+ name: user["Name"],+ created_at: user["DateInserted"] == nil ? 0 : Time.zone.at(user["DateInserted"]),+ bio_raw: user["About"],+ registration_ip_address: user["InsertIPAddress"],+ last_seen_at: user["DateLastActive"] == nil ? 0 : Time.zone.at(user["DateLastActive"]),+ location: user["Location"],+ admin: user["Admin"] == 1,trust_level: !banned && commented ? 2 : 0,- post_create_action: proc do |newuser|- if @user_is_deleted- @last_deleted_username = newuser.username- end- if banned- newuser.suspended_at = Time.now- # banning on Vanilla doesn't have an end, so a thousand years seems equivalent- newuser.suspended_till = 1000.years.from_now- if newuser.save- StaffActionLogger.new(Discourse.system_user).log_user_suspend(newuser, 'Imported from Vanilla Forum')- else- puts "Failed to suspend user #{newuser.username}. #{newuser.errors.full_messages.join(', ')}"+ post_create_action:+ proc do |newuser|+ @last_deleted_username = newuser.username if @user_is_deleted+ if banned+ newuser.suspended_at = Time.now+ # banning on Vanilla doesn't have an end, so a thousand years seems equivalent+ newuser.suspended_till = 1000.years.from_now+ if newuser.save+ StaffActionLogger.new(Discourse.system_user).log_user_suspend(+ newuser,+ "Imported from Vanilla Forum",+ )+ else+ puts "Failed to suspend user #{newuser.username}. #{newuser.errors.full_messages.join(", ")}"+ endend- end- end }+ end,+ }endendend@@ -162,7 +160,10 @@ class ImportScripts::VanillaSQL < ImportScripts::BaseUser.find_each do |u|next unless u.custom_fields["import_id"]- r = mysql_query("SELECT photo FROM #{TABLE_PREFIX}User WHERE UserID = #{u.custom_fields['import_id']};").first+ r =+ mysql_query(+ "SELECT photo FROM #{TABLE_PREFIX}User WHERE UserID = #{u.custom_fields["import_id"]};",+ ).firstnext if r.nil?photo = r["photo"]next unless photo.present?@@ -175,9 +176,9 @@ class ImportScripts::VanillaSQL < ImportScripts::Basephoto_real_filename = nilparts = photo.squeeze("/").split("/")if parts[0] =~ /^[a-z0-9]{2}:/- photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[2..-2].join('/')}".squeeze("/")+ photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[2..-2].join("/")}".squeeze("/")elsif parts[0] == "~cf"- photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[1..-2].join('/')}".squeeze("/")+ photo_path = "#{ATTACHMENTS_BASE_DIR}/#{parts[1..-2].join("/")}".squeeze("/")elseputs "UNKNOWN FORMAT: #{photo}"next@@ -218,7 +219,7 @@ class ImportScripts::VanillaSQL < ImportScripts::Base# Otherwise, the file exists but with a prefix:# The p prefix seems to be the full file, so try to find that one first.- ['p', 't', 'n'].each do |prefix|+ %w[p t n].each do |prefix|full_guess = File.join(path, "#{prefix}#{base_guess}")return full_guess if File.exist?(full_guess)end@@ -230,38 +231,43 @@ class ImportScripts::VanillaSQL < ImportScripts::Basedef import_group_usersputs "", "importing group users..."- group_users = mysql_query("+ group_users =+ mysql_query(+ "SELECT RoleID, UserIDFROM #{TABLE_PREFIX}UserRole- ").to_a+ ",+ ).to_agroup_users.each do |row|user_id = user_id_from_imported_user_id(row["UserID"])group_id = group_id_from_imported_group_id(row["RoleID"])- if user_id && group_id- GroupUser.find_or_create_by(user_id: user_id, group_id: group_id)- end+ GroupUser.find_or_create_by(user_id: user_id, group_id: group_id) if user_id && group_idendenddef import_categoriesputs "", "importing categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT CategoryID, ParentCategoryID, Name, DescriptionFROM #{TABLE_PREFIX}CategoryWHERE CategoryID > 0ORDER BY CategoryID ASC- ").to_a+ ",+ ).to_a- top_level_categories = categories.select { |c| c['ParentCategoryID'].blank? || c['ParentCategoryID'] == -1 }+ top_level_categories =+ categories.select { |c| c["ParentCategoryID"].blank? || c["ParentCategoryID"] == -1 }create_categories(top_level_categories) do |category|{- id: category['CategoryID'],- name: CGI.unescapeHTML(category['Name']),- description: CGI.unescapeHTML(category['Description'])+ id: category["CategoryID"],+ name: CGI.unescapeHTML(category["Name"]),+ description: CGI.unescapeHTML(category["Description"]),}end@@ -272,37 +278,37 @@ class ImportScripts::VanillaSQL < ImportScripts::Base# Depth = 3create_categories(subcategories) do |category|{- id: category['CategoryID'],- parent_category_id: category_id_from_imported_category_id(category['ParentCategoryID']),- name: CGI.unescapeHTML(category['Name']),- description: category['Description'] ? CGI.unescapeHTML(category['Description']) : nil,+ id: category["CategoryID"],+ parent_category_id: category_id_from_imported_category_id(category["ParentCategoryID"]),+ name: CGI.unescapeHTML(category["Name"]),+ description: category["Description"] ? CGI.unescapeHTML(category["Description"]) : nil,}end- subcategory_ids = Set.new(subcategories.map { |c| c['CategoryID'] })+ subcategory_ids = Set.new(subcategories.map { |c| c["CategoryID"] })# Depth 4 and 5 need to be tagscategories.each do |c|- next if c['ParentCategoryID'] == -1- next if top_level_category_ids.include?(c['CategoryID'])- next if subcategory_ids.include?(c['CategoryID'])+ next if c["ParentCategoryID"] == -1+ next if top_level_category_ids.include?(c["CategoryID"])+ next if subcategory_ids.include?(c["CategoryID"])# Find a depth 3 category for topics in this categoryparent = c- while !parent.nil? && !subcategory_ids.include?(parent['CategoryID'])- parent = categories.find { |subcat| subcat['CategoryID'] == parent['ParentCategoryID'] }+ while !parent.nil? && !subcategory_ids.include?(parent["CategoryID"])+ parent = categories.find { |subcat| subcat["CategoryID"] == parent["ParentCategoryID"] }endif parent- tag_name = DiscourseTagging.clean_tag(c['Name'])+ tag_name = DiscourseTagging.clean_tag(c["Name"])tag = Tag.find_by_name(tag_name) || Tag.create(name: tag_name)- @category_mappings[c['CategoryID']] = {- category_id: category_id_from_imported_category_id(parent['CategoryID']),- tag: tag[:name]+ @category_mappings[c["CategoryID"]] = {+ category_id: category_id_from_imported_category_id(parent["CategoryID"]),+ tag: tag[:name],}else- puts '', "Couldn't find a category for #{c['CategoryID']} '#{c['Name']}'!"+ puts "", "Couldn't find a category for #{c["CategoryID"]} '#{c["Name"]}'!"endendend@@ -310,46 +316,66 @@ class ImportScripts::VanillaSQL < ImportScripts::Basedef import_topicsputs "", "importing topics..."- tag_names_sql = "select t.name as tag_name from GDN_Tag t, GDN_TagDiscussion td where t.tagid = td.tagid and td.discussionid = {discussionid} and t.name != '';"+ tag_names_sql =+ "select t.name as tag_name from GDN_Tag t, GDN_TagDiscussion td where t.tagid = td.tagid and td.discussionid = {discussionid} and t.name != '';"- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}Discussion;").first['count']+ total_count =+ mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}Discussion;").first["count"]@last_topic_id = -1batches(BATCH_SIZE) do |offset|- discussions = mysql_query(- "SELECT DiscussionID, CategoryID, Name, Body, Format, CountViews, Closed, Announce,+ discussions =+ mysql_query(+ "SELECT DiscussionID, CategoryID, Name, Body, Format, CountViews, Closed, Announce,DateInserted, InsertUserID, DateLastCommentFROM #{TABLE_PREFIX}DiscussionWHERE DiscussionID > #{@last_topic_id}ORDER BY DiscussionID ASC- LIMIT #{BATCH_SIZE};")+ LIMIT #{BATCH_SIZE};",+ )break if discussions.size < 1- @last_topic_id = discussions.to_a.last['DiscussionID']- next if all_records_exist? :posts, discussions.map { |t| "discussion#" + t['DiscussionID'].to_s }+ @last_topic_id = discussions.to_a.last["DiscussionID"]+ if all_records_exist? :posts, discussions.map { |t| "discussion#" + t["DiscussionID"].to_s }+ next+ endcreate_posts(discussions, total: total_count, offset: offset) do |discussion|- user_id = user_id_from_imported_user_id(discussion['InsertUserID']) || Discourse::SYSTEM_USER_ID+ user_id =+ user_id_from_imported_user_id(discussion["InsertUserID"]) || Discourse::SYSTEM_USER_ID{- id: "discussion#" + discussion['DiscussionID'].to_s,+ id: "discussion#" + discussion["DiscussionID"].to_s,user_id: user_id,- title: discussion['Name'],- category: category_id_from_imported_category_id(discussion['CategoryID']) || @category_mappings[discussion['CategoryID']].try(:[], :category_id),+ title: discussion["Name"],+ category:+ category_id_from_imported_category_id(discussion["CategoryID"]) ||+ @category_mappings[discussion["CategoryID"]].try(:[], :category_id),raw: get_raw(discussion, user_id),- views: discussion['CountViews'] || 0,- closed: discussion['Closed'] == 1,- pinned_at: discussion['Announce'] == 0 ? nil : Time.zone.at(discussion['DateLastComment'] || discussion['DateInserted']),- pinned_globally: discussion['Announce'] == 1,- created_at: Time.zone.at(discussion['DateInserted']),- post_create_action: proc do |post|- if @import_tags- tag_names = @client.query(tag_names_sql.gsub('{discussionid}', discussion['DiscussionID'].to_s)).map { |row| row['tag_name'] }- category_tag = @category_mappings[discussion['CategoryID']].try(:[], :tag)- tag_names = category_tag ? tag_names.append(category_tag) : tag_names- DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)- end- end+ views: discussion["CountViews"] || 0,+ closed: discussion["Closed"] == 1,+ pinned_at:+ (+ if discussion["Announce"] == 0+ nil+ else+ Time.zone.at(discussion["DateLastComment"] || discussion["DateInserted"])+ end+ ),+ pinned_globally: discussion["Announce"] == 1,+ created_at: Time.zone.at(discussion["DateInserted"]),+ post_create_action:+ proc do |post|+ if @import_tags+ tag_names =+ @client+ .query(tag_names_sql.gsub("{discussionid}", discussion["DiscussionID"].to_s))+ .map { |row| row["tag_name"] }+ category_tag = @category_mappings[discussion["CategoryID"]].try(:[], :tag)+ tag_names = category_tag ? tag_names.append(category_tag) : tag_names+ DiscourseTagging.tag_topic_by_names(post.topic, staff_guardian, tag_names)+ end+ end,}endend@@ -358,36 +384,42 @@ class ImportScripts::VanillaSQL < ImportScripts::Basedef import_postsputs "", "importing posts..."- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}Comment;").first['count']+ total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}Comment;").first["count"]@last_post_id = -1batches(BATCH_SIZE) do |offset|- comments = mysql_query(- "SELECT CommentID, DiscussionID, Body, Format,+ comments =+ mysql_query(+ "SELECT CommentID, DiscussionID, Body, Format,DateInserted, InsertUserID, QnAFROM #{TABLE_PREFIX}CommentWHERE CommentID > #{@last_post_id}ORDER BY CommentID ASC- LIMIT #{BATCH_SIZE};")+ LIMIT #{BATCH_SIZE};",+ )break if comments.size < 1- @last_post_id = comments.to_a.last['CommentID']- next if all_records_exist? :posts, comments.map { |comment| "comment#" + comment['CommentID'].to_s }+ @last_post_id = comments.to_a.last["CommentID"]+ if all_records_exist? :posts,+ comments.map { |comment| "comment#" + comment["CommentID"].to_s }+ next+ endcreate_posts(comments, total: total_count, offset: offset) do |comment|- next unless t = topic_lookup_from_imported_post_id("discussion#" + comment['DiscussionID'].to_s)- next if comment['Body'].blank?- user_id = user_id_from_imported_user_id(comment['InsertUserID']) || Discourse::SYSTEM_USER_ID+ unless t = topic_lookup_from_imported_post_id("discussion#" + comment["DiscussionID"].to_s)+ next+ end+ next if comment["Body"].blank?+ user_id =+ user_id_from_imported_user_id(comment["InsertUserID"]) || Discourse::SYSTEM_USER_IDpost = {- id: "comment#" + comment['CommentID'].to_s,+ id: "comment#" + comment["CommentID"].to_s,user_id: user_id,topic_id: t[:topic_id],raw: get_raw(comment, user_id),- created_at: Time.zone.at(comment['DateInserted'])+ created_at: Time.zone.at(comment["DateInserted"]),}- if comment['QnA'] == "Accepted"- post[:custom_fields] = { is_accepted_answer: true }- end+ post[:custom_fields] = { is_accepted_answer: true } if comment["QnA"] == "Accepted"postend@@ -397,19 +429,22 @@ class ImportScripts::VanillaSQL < ImportScripts::Basedef import_likesputs "", "importing likes..."- total_count = mysql_query("SELECT count(*) count FROM GDN_ThanksLog;").first['count']+ total_count = mysql_query("SELECT count(*) count FROM GDN_ThanksLog;").first["count"]current_count = 0start_time = Time.now- likes = mysql_query("+ likes =+ mysql_query(+ "SELECT CommentID, DateInserted, InsertUserIDFROM #{TABLE_PREFIX}ThanksLogORDER BY CommentID ASC;- ")+ ",+ )likes.each do |like|- post_id = post_id_from_imported_post_id("comment##{like['CommentID']}")- user_id = user_id_from_imported_user_id(like['InsertUserID'])+ post_id = post_id_from_imported_post_id("comment##{like["CommentID"]}")+ user_id = user_id_from_imported_user_id(like["InsertUserID"])post = Post.find(post_id) if post_iduser = User.find(user_id) if user_id@@ -428,51 +463,58 @@ class ImportScripts::VanillaSQL < ImportScripts::Basedef import_messagesputs "", "importing messages..."- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}ConversationMessage;").first['count']+ total_count =+ mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}ConversationMessage;").first["count"]@last_message_id = -1batches(BATCH_SIZE) do |offset|- messages = mysql_query(- "SELECT m.MessageID, m.Body, m.Format,+ messages =+ mysql_query(+ "SELECT m.MessageID, m.Body, m.Format,m.InsertUserID, m.DateInserted,m.ConversationID, c.ContributorsFROM #{TABLE_PREFIX}ConversationMessage mINNER JOIN #{TABLE_PREFIX}Conversation c on c.ConversationID = m.ConversationIDWHERE m.MessageID > #{@last_message_id}ORDER BY m.MessageID ASC- LIMIT #{BATCH_SIZE};")+ LIMIT #{BATCH_SIZE};",+ )break if messages.size < 1- @last_message_id = messages.to_a.last['MessageID']- next if all_records_exist? :posts, messages.map { |t| "message#" + t['MessageID'].to_s }+ @last_message_id = messages.to_a.last["MessageID"]+ next if all_records_exist? :posts, messages.map { |t| "message#" + t["MessageID"].to_s }create_posts(messages, total: total_count, offset: offset) do |message|- user_id = user_id_from_imported_user_id(message['InsertUserID']) || Discourse::SYSTEM_USER_ID+ user_id =+ user_id_from_imported_user_id(message["InsertUserID"]) || Discourse::SYSTEM_USER_IDbody = get_raw(message, user_id)common = {user_id: user_id,raw: body,- created_at: Time.zone.at(message['DateInserted']),+ created_at: Time.zone.at(message["DateInserted"]),custom_fields: {- conversation_id: message['ConversationID'],- participants: message['Contributors'],- message_id: message['MessageID']- }+ conversation_id: message["ConversationID"],+ participants: message["Contributors"],+ message_id: message["MessageID"],+ },}- conversation_id = "conversation#" + message['ConversationID'].to_s- message_id = "message#" + message['MessageID'].to_s+ conversation_id = "conversation#" + message["ConversationID"].to_s+ message_id = "message#" + message["MessageID"].to_simported_conversation = topic_lookup_from_imported_post_id(conversation_id)if imported_conversation.present?common.merge(id: message_id, topic_id: imported_conversation[:topic_id])else- user_ids = (message['Contributors'] || '').scan(/\"(\d+)\"/).flatten.map(&:to_i)- usernames = user_ids.map { |id| @lookup.find_user_by_import_id(id).try(:username) }.compact- usernames = [@lookup.find_user_by_import_id(message['InsertUserID']).try(:username)].compact if usernames.empty?+ user_ids = (message["Contributors"] || "").scan(/\"(\d+)\"/).flatten.map(&:to_i)+ usernames =+ user_ids.map { |id| @lookup.find_user_by_import_id(id).try(:username) }.compact+ usernames = [+ @lookup.find_user_by_import_id(message["InsertUserID"]).try(:username),+ ].compact if usernames.empty?title = body.truncate(40){@@ -487,8 +529,8 @@ class ImportScripts::VanillaSQL < ImportScripts::Baseenddef get_raw(record, user_id)- format = (record['Format'] || "").downcase- body = record['Body']+ format = (record["Format"] || "").downcase+ body = record["Body"]case formatwhen "html"@@ -507,7 +549,7 @@ class ImportScripts::VanillaSQL < ImportScripts::Baseraw = @htmlentities.decode(raw)# convert user profile links to user mentions- raw.gsub!(/<a.*>(@\S+?)<\/a>/) { $1 }+ raw.gsub!(%r{<a.*>(@\S+?)</a>}) { $1 }raw = ReverseMarkdown.convert(raw) unless skip_reverse_markdown@@ -526,14 +568,21 @@ class ImportScripts::VanillaSQL < ImportScripts::Baseenddef create_permalinks- puts '', 'Creating redirects...', ''+ puts "", "Creating redirects...", ""User.find_each do |u|ucf = u.custom_fieldsif ucf && ucf["import_id"] && ucf["import_username"]- encoded_username = CGI.escape(ucf['import_username']).gsub('+', '%20')- Permalink.create(url: "profile/#{ucf['import_id']}/#{encoded_username}", external_url: "/users/#{u.username}") rescue nil- print '.'+ encoded_username = CGI.escape(ucf["import_username"]).gsub("+", "%20")+ begin+ Permalink.create(+ url: "profile/#{ucf["import_id"]}/#{encoded_username}",+ external_url: "/users/#{u.username}",+ )+ rescue StandardError+ nil+ end+ print "."endend@@ -541,14 +590,22 @@ class ImportScripts::VanillaSQL < ImportScripts::Basepcf = post.custom_fieldsif pcf && pcf["import_id"]topic = post.topic- id = pcf["import_id"].split('#').last+ id = pcf["import_id"].split("#").lastif post.post_number == 1slug = Slug.for(topic.title) # probably matches what vanilla would do...- Permalink.create(url: "discussion/#{id}/#{slug}", topic_id: topic.id) rescue nil+ begin+ Permalink.create(url: "discussion/#{id}/#{slug}", topic_id: topic.id)+ rescue StandardError+ nil+ endelse- Permalink.create(url: "discussion/comment/#{id}", post_id: post.id) rescue nil+ begin+ Permalink.create(url: "discussion/comment/#{id}", post_id: post.id)+ rescue StandardError+ nil+ endend- print '.'+ print "."endendend@@ -561,75 +618,86 @@ class ImportScripts::VanillaSQL < ImportScripts::Basecount = 0# https://us.v-cdn.net/1234567/uploads/editor/xyz/image.jpg- cdn_regex = /https:\/\/us.v-cdn.net\/1234567\/uploads\/(\S+\/(\w|-)+.\w+)/i+ cdn_regex = %r{https://us.v-cdn.net/1234567/uploads/(\S+/(\w|-)+.\w+)}i# [attachment=10109:Screen Shot 2012-04-01 at 3.47.35 AM.png]attachment_regex = /\[attachment=(\d+):(.*?)\]/i- Post.where("raw LIKE '%/us.v-cdn.net/%' OR raw LIKE '%[attachment%'").find_each do |post|- count += 1- print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)]- new_raw = post.raw.dup-- new_raw.gsub!(attachment_regex) do |s|- matches = attachment_regex.match(s)- attachment_id = matches[1]- file_name = matches[2]- next unless attachment_id-- r = mysql_query("SELECT Path, Name FROM #{TABLE_PREFIX}Media WHERE MediaID = #{attachment_id};").first- next if r.nil?- path = r["Path"]- name = r["Name"]- next unless path.present?-- path.gsub!("s3://content/", "")- path.gsub!("s3://uploads/", "")- file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}"-- if File.exist?(file_path)- upload = create_upload(post.user.id, file_path, File.basename(file_path))- if upload && upload.errors.empty?- # upload.url- filename = name || file_name || File.basename(file_path)- html_for_upload(upload, normalize_text(filename))+ Post+ .where("raw LIKE '%/us.v-cdn.net/%' OR raw LIKE '%[attachment%'")+ .find_each do |post|+ count += 1+ print "\r%7d - %6d/sec" % [count, count.to_f / (Time.now - start)]+ new_raw = post.raw.dup++ new_raw.gsub!(attachment_regex) do |s|+ matches = attachment_regex.match(s)+ attachment_id = matches[1]+ file_name = matches[2]+ next unless attachment_id++ r =+ mysql_query(+ "SELECT Path, Name FROM #{TABLE_PREFIX}Media WHERE MediaID = #{attachment_id};",+ ).first+ next if r.nil?+ path = r["Path"]+ name = r["Name"]+ next unless path.present?++ path.gsub!("s3://content/", "")+ path.gsub!("s3://uploads/", "")+ file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}"++ if File.exist?(file_path)+ upload = create_upload(post.user.id, file_path, File.basename(file_path))+ if upload && upload.errors.empty?+ # upload.url+ filename = name || file_name || File.basename(file_path)+ html_for_upload(upload, normalize_text(filename))+ else+ puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ endelse- puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ puts "Couldn't find file for #{attachment_id}. Skipping."+ nextend- else- puts "Couldn't find file for #{attachment_id}. Skipping."- nextend- end- new_raw.gsub!(cdn_regex) do |s|- matches = cdn_regex.match(s)- attachment_id = matches[1]+ new_raw.gsub!(cdn_regex) do |s|+ matches = cdn_regex.match(s)+ attachment_id = matches[1]- file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}"+ file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}"- if File.exist?(file_path)- upload = create_upload(post.user.id, file_path, File.basename(file_path))- if upload && upload.errors.empty?- upload.url+ if File.exist?(file_path)+ upload = create_upload(post.user.id, file_path, File.basename(file_path))+ if upload && upload.errors.empty?+ upload.url+ else+ puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ endelse- puts "Error: Upload did not persist for #{post.id} #{attachment_id}!"+ puts "Couldn't find file for #{attachment_id}. Skipping."+ nextend- else- puts "Couldn't find file for #{attachment_id}. Skipping."- nextend- end- if new_raw != post.raw- begin- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, skip_revision: true, skip_validations: true, bypass_bump: true)- rescue- puts "PostRevisor error for #{post.id}"- post.raw = new_raw- post.save(validate: false)+ if new_raw != post.raw+ begin+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ skip_revision: true,+ skip_validations: true,+ bypass_bump: true,+ )+ rescue StandardError+ puts "PostRevisor error for #{post.id}"+ post.raw = new_raw+ post.save(validate: false)+ endendend- endendenddiff --git a/script/import_scripts/vbulletin.rb b/script/import_scripts/vbulletin.rbindex 8b3de80bdc3..f534b43848d 100644--- a/script/import_scripts/vbulletin.rb+++ b/script/import_scripts/vbulletin.rb@@ -1,14 +1,14 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'+require "htmlentities"begin- require 'php_serialize' # https://github.com/jqr/php-serialize+ require "php_serialize" # https://github.com/jqr/php-serializerescue LoadErrorputs- puts 'php_serialize not found.'- puts 'Add to Gemfile, like this: '+ puts "php_serialize not found."+ puts "Add to Gemfile, like this: "putsputs "echo gem \\'php-serialize\\' >> Gemfile"puts "bundle install"@@ -23,13 +23,13 @@ class ImportScripts::VBulletin < ImportScripts::Base# CHANGE THESE BEFORE RUNNING THE IMPORTER- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "vbulletin"- DB_PW ||= ENV['DB_PW'] || ""- DB_USER ||= ENV['DB_USER'] || "root"- TIMEZONE ||= ENV['TIMEZONE'] || "America/Los_Angeles"- TABLE_PREFIX ||= ENV['TABLE_PREFIX'] || "vb_"- ATTACHMENT_DIR ||= ENV['ATTACHMENT_DIR'] || '/path/to/your/attachment/folder'+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "vbulletin"+ DB_PW ||= ENV["DB_PW"] || ""+ DB_USER ||= ENV["DB_USER"] || "root"+ TIMEZONE ||= ENV["TIMEZONE"] || "America/Los_Angeles"+ TABLE_PREFIX ||= ENV["TABLE_PREFIX"] || "vb_"+ ATTACHMENT_DIR ||= ENV["ATTACHMENT_DIR"] || "/path/to/your/attachment/folder"puts "#{DB_USER}:#{DB_PW}@#{DB_HOST} wants #{DB_NAME}"@@ -44,16 +44,12 @@ class ImportScripts::VBulletin < ImportScripts::Base@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- password: DB_PW,- database: DB_NAME- )- rescue Exception => e- puts '=' * 50- puts e.message- puts <<~TEXT+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, password: DB_PW, database: DB_NAME)+ rescue Exception => e+ puts "=" * 50+ puts e.message+ puts <<~TEXTCannot connect in to database.Hostname: #{DB_HOST}@@ -72,11 +68,15 @@ class ImportScripts::VBulletin < ImportScripts::BaseExiting.TEXT- exit+ exitenddef execute- mysql_query("CREATE INDEX firstpostid_index ON #{TABLE_PREFIX}thread (firstpostid)") rescue nil+ begin+ mysql_query("CREATE INDEX firstpostid_index ON #{TABLE_PREFIX}thread (firstpostid)")+ rescue StandardError+ nil+ endimport_groupsimport_users@@ -104,10 +104,7 @@ class ImportScripts::VBulletin < ImportScripts::BaseSQLcreate_groups(groups) do |group|- {- id: group["usergroupid"],- name: @htmlentities.decode(group["title"]).strip- }+ { id: group["usergroupid"], name: @htmlentities.decode(group["title"]).strip }endend@@ -127,7 +124,7 @@ class ImportScripts::VBulletin < ImportScripts::Baselast_user_id = -1batches(BATCH_SIZE) do |offset|- users = mysql_query(<<-SQL+ users = mysql_query(<<-SQL).to_aSELECT userid, username, homepage@@ -142,7 +139,6 @@ class ImportScripts::VBulletin < ImportScripts::BaseORDER BY useridLIMIT #{BATCH_SIZE}SQL- ).to_abreak if users.empty?@@ -169,15 +165,21 @@ class ImportScripts::VBulletin < ImportScripts::Baseprimary_group_id: group_id_from_imported_group_id(user["usergroupid"].to_i),created_at: parse_timestamp(user["joindate"]),last_seen_at: parse_timestamp(user["lastvisit"]),- post_create_action: proc do |u|- import_profile_picture(user, u)- import_profile_background(user, u)- end+ post_create_action:+ proc do |u|+ import_profile_picture(user, u)+ import_profile_background(user, u)+ end,}endend- @usernames = UserCustomField.joins(:user).where(name: 'import_username').pluck('user_custom_fields.value', 'users.username').to_h+ @usernames =+ UserCustomField+ .joins(:user)+ .where(name: "import_username")+ .pluck("user_custom_fields.value", "users.username")+ .to_henddef create_groups_membership@@ -190,7 +192,10 @@ class ImportScripts::VBulletin < ImportScripts::Basenext if GroupUser.where(group_id: group.id).count > 0user_ids_in_group = User.where(primary_group_id: group.id).pluck(:id).to_anext if user_ids_in_group.size == 0- values = user_ids_in_group.map { |user_id| "(#{group.id}, #{user_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" }.join(",")+ values =+ user_ids_in_group+ .map { |user_id| "(#{group.id}, #{user_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" }+ .join(",")DB.exec <<~SQLINSERT INTO group_users (group_id, user_id, created_at, updated_at) VALUES #{values}@@ -230,8 +235,16 @@ class ImportScripts::VBulletin < ImportScripts::Baseimported_user.user_avatar.update(custom_upload_id: upload.id)imported_user.update(uploaded_avatar_id: upload.id)ensure- file.close rescue nil- file.unlind rescue nil+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlind+ rescue StandardError+ nil+ endenddef import_profile_background(old_user, imported_user)@@ -258,14 +271,25 @@ class ImportScripts::VBulletin < ImportScripts::Baseimported_user.user_profile.upload_profile_background(upload)ensure- file.close rescue nil- file.unlink rescue nil+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlink+ rescue StandardError+ nil+ endenddef import_categoriesputs "", "importing top level categories..."- categories = mysql_query("SELECT forumid, title, description, displayorder, parentid FROM #{TABLE_PREFIX}forum ORDER BY forumid").to_a+ categories =+ mysql_query(+ "SELECT forumid, title, description, displayorder, parentid FROM #{TABLE_PREFIX}forum ORDER BY forumid",+ ).to_atop_level_categories = categories.select { |c| c["parentid"] == -1 }@@ -274,7 +298,7 @@ class ImportScripts::VBulletin < ImportScripts::Baseid: category["forumid"],name: @htmlentities.decode(category["title"]).strip,position: category["displayorder"],- description: @htmlentities.decode(category["description"]).strip+ description: @htmlentities.decode(category["description"]).strip,}end@@ -296,7 +320,7 @@ class ImportScripts::VBulletin < ImportScripts::Basename: @htmlentities.decode(category["title"]).strip,position: category["displayorder"],description: @htmlentities.decode(category["description"]).strip,- parent_category_id: category_id_from_imported_category_id(category["parentid"])+ parent_category_id: category_id_from_imported_category_id(category["parentid"]),}endend@@ -304,12 +328,13 @@ class ImportScripts::VBulletin < ImportScripts::Basedef import_topicsputs "", "importing topics..."- topic_count = mysql_query("SELECT COUNT(threadid) count FROM #{TABLE_PREFIX}thread").first["count"]+ topic_count =+ mysql_query("SELECT COUNT(threadid) count FROM #{TABLE_PREFIX}thread").first["count"]last_topic_id = -1batches(BATCH_SIZE) do |offset|- topics = mysql_query(<<-SQL+ topics = mysql_query(<<-SQL).to_aSELECT t.threadid threadid, t.title title, forumid, open, postuserid, t.dateline dateline, views, t.visible visible, sticky,p.pagetext rawFROM #{TABLE_PREFIX}thread t@@ -318,7 +343,6 @@ class ImportScripts::VBulletin < ImportScripts::BaseORDER BY t.threadidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if topics.empty?@@ -326,7 +350,12 @@ class ImportScripts::VBulletin < ImportScripts::Basetopics.reject! { |t| @lookup.post_already_imported?("thread-#{t["threadid"]}") }create_posts(topics, total: topic_count, offset: offset) do |topic|- raw = preprocess_post_raw(topic["raw"]) rescue nil+ raw =+ begin+ preprocess_post_raw(topic["raw"])+ rescue StandardError+ nil+ endnext if raw.blank?topic_id = "thread-#{topic["threadid"]}"t = {@@ -351,28 +380,28 @@ class ImportScripts::VBulletin < ImportScripts::Basetopic = topic_lookup_from_imported_post_id(topic_id)if topic.present?url_slug = "thread/#{thread["threadid"]}" if thread["title"].present?- Permalink.create(url: url_slug, topic_id: topic[:topic_id].to_i) if url_slug.present? && topic[:topic_id].present?+ if url_slug.present? && topic[:topic_id].present?+ Permalink.create(url: url_slug, topic_id: topic[:topic_id].to_i)+ endendend-endenddef import_postsputs "", "importing posts..."- post_count = mysql_query(<<-SQL+ post_count = mysql_query(<<-SQL).first["count"]SELECT COUNT(postid) countFROM #{TABLE_PREFIX}post pJOIN #{TABLE_PREFIX}thread t ON t.threadid = p.threadidWHERE t.firstpostid <> p.postidSQL- ).first["count"]last_post_id = -1batches(BATCH_SIZE) do |offset|- posts = mysql_query(<<-SQL+ posts = mysql_query(<<-SQL).to_aSELECT p.postid, p.userid, p.threadid, p.pagetext raw, p.dateline, p.visible, p.parentidFROM #{TABLE_PREFIX}post pJOIN #{TABLE_PREFIX}thread t ON t.threadid = p.threadid@@ -381,7 +410,6 @@ class ImportScripts::VBulletin < ImportScripts::BaseORDER BY p.postidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if posts.empty?@@ -389,7 +417,12 @@ class ImportScripts::VBulletin < ImportScripts::Baseposts.reject! { |p| @lookup.post_already_imported?(p["postid"].to_i) }create_posts(posts, total: post_count, offset: offset) do |post|- raw = preprocess_post_raw(post["raw"]) rescue nil+ raw =+ begin+ preprocess_post_raw(post["raw"])+ rescue StandardError+ nil+ endnext if raw.blank?next unless topic = topic_lookup_from_imported_post_id("thread-#{post["threadid"]}")p = {@@ -410,7 +443,8 @@ class ImportScripts::VBulletin < ImportScripts::Base# find the uploaded file information from the dbdef find_upload(post, attachment_id)- sql = "SELECT a.attachmentid attachment_id, a.userid user_id, a.filedataid file_id, a.filename filename,+ sql =+ "SELECT a.attachmentid attachment_id, a.userid user_id, a.filedataid file_id, a.filename filename,LENGTH(fd.filedata) AS dbsize, filedata, a.caption captionFROM #{TABLE_PREFIX}attachment aLEFT JOIN #{TABLE_PREFIX}filedata fd ON fd.filedataid = a.filedataid@@ -418,25 +452,24 @@ class ImportScripts::VBulletin < ImportScripts::Baseresults = mysql_query(sql)unless row = results.first- puts "Couldn't find attachment record for post.id = #{post.id}, import_id = #{post.custom_fields['import_id']}"+ puts "Couldn't find attachment record for post.id = #{post.id}, import_id = #{post.custom_fields["import_id"]}"returnend- filename = File.join(ATTACHMENT_DIR, row['user_id'].to_s.split('').join('/'), "#{row['file_id']}.attach")- real_filename = row['filename']- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ filename =+ File.join(ATTACHMENT_DIR, row["user_id"].to_s.split("").join("/"), "#{row["file_id"]}.attach")+ real_filename = row["filename"]+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."unless File.exist?(filename)- if row['dbsize'].to_i == 0- puts "Attachment file #{row['filedataid']} doesn't exist"+ if row["dbsize"].to_i == 0+ puts "Attachment file #{row["filedataid"]} doesn't exist"return nilend- tmpfile = 'attach_' + row['filedataid'].to_s- filename = File.join('/tmp/', tmpfile)- File.open(filename, 'wb') { |f|- f.write(row['filedata'])- }+ tmpfile = "attach_" + row["filedataid"].to_s+ filename = File.join("/tmp/", tmpfile)+ File.open(filename, "wb") { |f| f.write(row["filedata"]) }endupload = create_upload(post.user.id, filename, real_filename)@@ -457,24 +490,24 @@ class ImportScripts::VBulletin < ImportScripts::Basedef import_private_messagesputs "", "importing private messages..."- topic_count = mysql_query("SELECT COUNT(pmtextid) count FROM #{TABLE_PREFIX}pmtext").first["count"]+ topic_count =+ mysql_query("SELECT COUNT(pmtextid) count FROM #{TABLE_PREFIX}pmtext").first["count"]last_private_message_id = -1batches(BATCH_SIZE) do |offset|- private_messages = mysql_query(<<-SQL+ private_messages = mysql_query(<<-SQL).to_aSELECT pmtextid, fromuserid, title, message, touserarray, datelineFROM #{TABLE_PREFIX}pmtextWHERE pmtextid > #{last_private_message_id}ORDER BY pmtextidLIMIT #{BATCH_SIZE}SQL- ).to_abreak if private_messages.empty?last_private_message_id = private_messages[-1]["pmtextid"]- private_messages.reject! { |pm| @lookup.post_already_imported?("pm-#{pm['pmtextid']}") }+ private_messages.reject! { |pm| @lookup.post_already_imported?("pm-#{pm["pmtextid"]}") }title_username_of_pm_first_post = {}@@ -482,11 +515,16 @@ class ImportScripts::VBulletin < ImportScripts::Baseskip = falsemapped = {}- mapped[:id] = "pm-#{m['pmtextid']}"- mapped[:user_id] = user_id_from_imported_user_id(m['fromuserid']) || Discourse::SYSTEM_USER_ID- mapped[:raw] = preprocess_post_raw(m['message']) rescue nil- mapped[:created_at] = Time.zone.at(m['dateline'])- title = @htmlentities.decode(m['title']).strip[0...255]+ mapped[:id] = "pm-#{m["pmtextid"]}"+ mapped[:user_id] = user_id_from_imported_user_id(m["fromuserid"]) ||+ Discourse::SYSTEM_USER_ID+ mapped[:raw] = begin+ preprocess_post_raw(m["message"])+ rescue StandardError+ nil+ end+ mapped[:created_at] = Time.zone.at(m["dateline"])+ title = @htmlentities.decode(m["title"]).strip[0...255]topic_id = nilnext if mapped[:raw].blank?@@ -495,9 +533,9 @@ class ImportScripts::VBulletin < ImportScripts::Basetarget_usernames = []target_userids = []begin- to_user_array = PHP.unserialize(m['touserarray'])- rescue- puts "#{m['pmtextid']} -- #{m['touserarray']}"+ to_user_array = PHP.unserialize(m["touserarray"])+ rescue StandardError+ puts "#{m["pmtextid"]} -- #{m["touserarray"]}"skip = trueend@@ -517,8 +555,8 @@ class ImportScripts::VBulletin < ImportScripts::Basetarget_usernames << username if usernameendend- rescue- puts "skipping pm-#{m['pmtextid']} `to_user_array` is not properly serialized -- #{to_user_array.inspect}"+ rescue StandardError+ puts "skipping pm-#{m["pmtextid"]} `to_user_array` is not properly serialized -- #{to_user_array.inspect}"skip = trueend@@ -526,18 +564,18 @@ class ImportScripts::VBulletin < ImportScripts::Baseparticipants << mapped[:user_id]beginparticipants.sort!- rescue+ rescue StandardErrorputs "one of the participant's id is nil -- #{participants.inspect}"endif title =~ /^Re:/-- parent_id = title_username_of_pm_first_post[[title[3..-1], participants]] ||- title_username_of_pm_first_post[[title[4..-1], participants]] ||- title_username_of_pm_first_post[[title[5..-1], participants]] ||- title_username_of_pm_first_post[[title[6..-1], participants]] ||- title_username_of_pm_first_post[[title[7..-1], participants]] ||- title_username_of_pm_first_post[[title[8..-1], participants]]+ parent_id =+ title_username_of_pm_first_post[[title[3..-1], participants]] ||+ title_username_of_pm_first_post[[title[4..-1], participants]] ||+ title_username_of_pm_first_post[[title[5..-1], participants]] ||+ title_username_of_pm_first_post[[title[6..-1], participants]] ||+ title_username_of_pm_first_post[[title[7..-1], participants]] ||+ title_username_of_pm_first_post[[title[8..-1], participants]]if parent_idif t = topic_lookup_from_imported_post_id("pm-#{parent_id}")@@ -545,18 +583,18 @@ class ImportScripts::VBulletin < ImportScripts::Baseendendelse- title_username_of_pm_first_post[[title, participants]] ||= m['pmtextid']+ title_username_of_pm_first_post[[title, participants]] ||= m["pmtextid"]endunless topic_idmapped[:title] = titlemapped[:archetype] = Archetype.private_message- mapped[:target_usernames] = target_usernames.join(',')+ mapped[:target_usernames] = target_usernames.join(",")if mapped[:target_usernames].size < 1 # pm with yourself?# skip = truemapped[:target_usernames] = "system"- puts "pm-#{m['pmtextid']} has no target (#{m['touserarray']})"+ puts "pm-#{m["pmtextid"]} has no target (#{m["touserarray"]})"endelsemapped[:topic_id] = topic_id@@ -568,25 +606,24 @@ class ImportScripts::VBulletin < ImportScripts::Baseenddef import_attachments- puts '', 'importing attachments...'+ puts "", "importing attachments..."mapping = {}- attachments = mysql_query(<<-SQL+ attachments = mysql_query(<<-SQL)SELECT a.attachmentid, a.contentid as postid, p.threadidFROM #{TABLE_PREFIX}attachment a, #{TABLE_PREFIX}post pWHERE a.contentid = p.postidAND contenttypeid = 1 AND state = 'visible'SQL- )attachments.each do |attachment|- post_id = post_id_from_imported_post_id(attachment['postid'])- post_id = post_id_from_imported_post_id("thread-#{attachment['threadid']}") unless post_id+ post_id = post_id_from_imported_post_id(attachment["postid"])+ post_id = post_id_from_imported_post_id("thread-#{attachment["threadid"]}") unless post_idif post_id.nil?- puts "Post for attachment #{attachment['attachmentid']} not found"+ puts "Post for attachment #{attachment["attachmentid"]} not found"nextendmapping[post_id] ||= []- mapping[post_id] << attachment['attachmentid'].to_i+ mapping[post_id] << attachment["attachmentid"].to_iendcurrent_count = 0@@ -594,7 +631,7 @@ class ImportScripts::VBulletin < ImportScripts::Basesuccess_count = 0fail_count = 0- attachment_regex = /\[attach[^\]]*\](\d+)\[\/attach\]/i+ attachment_regex = %r{\[attach[^\]]*\](\d+)\[/attach\]}iPost.find_each do |post|current_count += 1@@ -605,9 +642,7 @@ class ImportScripts::VBulletin < ImportScripts::Basematches = attachment_regex.match(s)attachment_id = matches[1]- unless mapping[post.id].nil?- mapping[post.id].delete(attachment_id.to_i)- end+ mapping[post.id].delete(attachment_id.to_i) unless mapping[post.id].nil?upload, filename = find_upload(post, attachment_id)unless upload@@ -621,13 +656,12 @@ class ImportScripts::VBulletin < ImportScripts::Base# make resumed imports fasterif new_raw == post.rawunless mapping[post.id].nil? || mapping[post.id].empty?- imported_text = mysql_query(<<-SQL+ imported_text = mysql_query(<<-SQL).first["pagetext"]SELECT p.pagetextFROM #{TABLE_PREFIX}attachment a, #{TABLE_PREFIX}post pWHERE a.contentid = p.postidAND a.attachmentid = #{mapping[post.id][0]}SQL- ).first["pagetext"]imported_text.scan(attachment_regex) do |match|attachment_id = match[0]@@ -646,14 +680,17 @@ class ImportScripts::VBulletin < ImportScripts::Base# internal upload deduplication will make sure that we do not import attachments againhtml = html_for_upload(upload, filename)- if !new_raw[html]- new_raw += "\n\n#{html}\n\n"- end+ new_raw += "\n\n#{html}\n\n" if !new_raw[html]endendif new_raw != post.raw- PostRevisor.new(post).revise!(post.user, { raw: new_raw }, bypass_bump: true, edit_reason: 'Import attachments from vBulletin')+ PostRevisor.new(post).revise!(+ post.user,+ { raw: new_raw },+ bypass_bump: true,+ edit_reason: "Import attachments from vBulletin",+ )endsuccess_count += 1@@ -728,22 +765,22 @@ class ImportScripts::VBulletin < ImportScripts::Base# [HTML]...[/HTML]raw.gsub!(/\[html\]/i, "\n```html\n")- raw.gsub!(/\[\/html\]/i, "\n```\n")+ raw.gsub!(%r{\[/html\]}i, "\n```\n")# [PHP]...[/PHP]raw.gsub!(/\[php\]/i, "\n```php\n")- raw.gsub!(/\[\/php\]/i, "\n```\n")+ raw.gsub!(%r{\[/php\]}i, "\n```\n")# [HIGHLIGHT="..."]raw.gsub!(/\[highlight="?(\w+)"?\]/i) { "\n```#{$1.downcase}\n" }# [CODE]...[/CODE]# [HIGHLIGHT]...[/HIGHLIGHT]- raw.gsub!(/\[\/?code\]/i, "\n```\n")- raw.gsub!(/\[\/?highlight\]/i, "\n```\n")+ raw.gsub!(%r{\[/?code\]}i, "\n```\n")+ raw.gsub!(%r{\[/?highlight\]}i, "\n```\n")# [SAMP]...[/SAMP]- raw.gsub!(/\[\/?samp\]/i, "`")+ raw.gsub!(%r{\[/?samp\]}i, "`")# replace all chevrons with HTML entities# NOTE: must be done@@ -758,96 +795,99 @@ class ImportScripts::VBulletin < ImportScripts::Baseraw.gsub!("\u2603", ">")# [URL=...]...[/URL]- raw.gsub!(/\[url="?([^"]+?)"?\](.*?)\[\/url\]/im) { "[#{$2.strip}](#{$1})" }- raw.gsub!(/\[url="?(.+?)"?\](.+)\[\/url\]/im) { "[#{$2.strip}](#{$1})" }+ raw.gsub!(%r{\[url="?([^"]+?)"?\](.*?)\[/url\]}im) { "[#{$2.strip}](#{$1})" }+ raw.gsub!(%r{\[url="?(.+?)"?\](.+)\[/url\]}im) { "[#{$2.strip}](#{$1})" }# [URL]...[/URL]# [MP3]...[/MP3]- raw.gsub!(/\[\/?url\]/i, "")- raw.gsub!(/\[\/?mp3\]/i, "")+ raw.gsub!(%r{\[/?url\]}i, "")+ raw.gsub!(%r{\[/?mp3\]}i, "")# [MENTION]<username>[/MENTION]- raw.gsub!(/\[mention\](.+?)\[\/mention\]/i) do+ raw.gsub!(%r{\[mention\](.+?)\[/mention\]}i) donew_username = get_username_for_old_username($1)"@#{new_username}"end# [FONT=blah] and [COLOR=blah]- raw.gsub! /\[FONT=.*?\](.*?)\[\/FONT\]/im, '\1'- raw.gsub! /\[COLOR=.*?\](.*?)\[\/COLOR\]/im, '\1'- raw.gsub! /\[COLOR=#.*?\](.*?)\[\/COLOR\]/im, '\1'+ raw.gsub! %r{\[FONT=.*?\](.*?)\[/FONT\]}im, '\1'+ raw.gsub! %r{\[COLOR=.*?\](.*?)\[/COLOR\]}im, '\1'+ raw.gsub! %r{\[COLOR=#.*?\](.*?)\[/COLOR\]}im, '\1'- raw.gsub! /\[SIZE=.*?\](.*?)\[\/SIZE\]/im, '\1'- raw.gsub! /\[SUP\](.*?)\[\/SUP\]/im, '\1'- raw.gsub! /\[h=.*?\](.*?)\[\/h\]/im, '\1'+ raw.gsub! %r{\[SIZE=.*?\](.*?)\[/SIZE\]}im, '\1'+ raw.gsub! %r{\[SUP\](.*?)\[/SUP\]}im, '\1'+ raw.gsub! %r{\[h=.*?\](.*?)\[/h\]}im, '\1'# [CENTER]...[/CENTER]- raw.gsub! /\[CENTER\](.*?)\[\/CENTER\]/im, '\1'+ raw.gsub! %r{\[CENTER\](.*?)\[/CENTER\]}im, '\1'# [INDENT]...[/INDENT]- raw.gsub! /\[INDENT\](.*?)\[\/INDENT\]/im, '\1'+ raw.gsub! %r{\[INDENT\](.*?)\[/INDENT\]}im, '\1'# Tables to MD- raw.gsub!(/\[TABLE.*?\](.*?)\[\/TABLE\]/im) { |t|- rows = $1.gsub!(/\s*\[TR\](.*?)\[\/TR\]\s*/im) { |r|- cols = $1.gsub! /\s*\[TD.*?\](.*?)\[\/TD\]\s*/im, '|\1'- "#{cols}|\n"- }+ raw.gsub!(%r{\[TABLE.*?\](.*?)\[/TABLE\]}im) do |t|+ rows =+ $1.gsub!(%r{\s*\[TR\](.*?)\[/TR\]\s*}im) do |r|+ cols = $1.gsub! %r{\s*\[TD.*?\](.*?)\[/TD\]\s*}im, '|\1'+ "#{cols}|\n"+ endheader, rest = rows.split "\n", 2c = header.count "|"sep = "|---" * (c - 1)"#{header}\n#{sep}|\n#{rest}\n"- }+ end# [QUOTE]...[/QUOTE]- raw.gsub!(/\[quote\](.+?)\[\/quote\]/im) { |quote|- quote.gsub!(/\[quote\](.+?)\[\/quote\]/im) { "\n#{$1}\n" }+ raw.gsub!(%r{\[quote\](.+?)\[/quote\]}im) do |quote|+ quote.gsub!(%r{\[quote\](.+?)\[/quote\]}im) { "\n#{$1}\n" }quote.gsub!(/\n(.+?)/) { "\n> #{$1}" }- }+ end# [QUOTE=<username>]...[/QUOTE]- raw.gsub!(/\[quote=([^;\]]+)\](.+?)\[\/quote\]/im) do+ raw.gsub!(%r{\[quote=([^;\]]+)\](.+?)\[/quote\]}im) doold_username, quote = $1, $2new_username = get_username_for_old_username(old_username)"\n[quote=\"#{new_username}\"]\n#{quote}\n[/quote]\n"end# [YOUTUBE]<id>[/YOUTUBE]- raw.gsub!(/\[youtube\](.+?)\[\/youtube\]/i) { "\n//youtu.be/#{$1}\n" }+ raw.gsub!(%r{\[youtube\](.+?)\[/youtube\]}i) { "\n//youtu.be/#{$1}\n" }# [VIDEO=youtube;<id>]...[/VIDEO]- raw.gsub!(/\[video=youtube;([^\]]+)\].*?\[\/video\]/i) { "\n//youtu.be/#{$1}\n" }+ raw.gsub!(%r{\[video=youtube;([^\]]+)\].*?\[/video\]}i) { "\n//youtu.be/#{$1}\n" }# Fix uppercase B U and I tags- raw.gsub!(/(\[\/?[BUI]\])/i) { $1.downcase }+ raw.gsub!(%r{(\[/?[BUI]\])}i) { $1.downcase }# More Additions ....# [spoiler=Some hidden stuff]SPOILER HERE!![/spoiler]- raw.gsub!(/\[spoiler="?(.+?)"?\](.+?)\[\/spoiler\]/im) { "\n#{$1}\n[spoiler]#{$2}[/spoiler]\n" }+ raw.gsub!(%r{\[spoiler="?(.+?)"?\](.+?)\[/spoiler\]}im) do+ "\n#{$1}\n[spoiler]#{$2}[/spoiler]\n"+ end# [IMG][IMG]http://i63.tinypic.com/akga3r.jpg[/IMG][/IMG]- raw.gsub!(/\[IMG\]\[IMG\](.+?)\[\/IMG\]\[\/IMG\]/i) { "[IMG]#{$1}[/IMG]" }+ raw.gsub!(%r{\[IMG\]\[IMG\](.+?)\[/IMG\]\[/IMG\]}i) { "[IMG]#{$1}[/IMG]" }# convert list tags to ul and list=1 tags to ol# (basically, we're only missing list=a here...)# (https://meta.discourse.org/t/phpbb-3-importer-old/17397)- raw.gsub!(/\[list\](.*?)\[\/list\]/im, '[ul]\1[/ul]')- raw.gsub!(/\[list=1\](.*?)\[\/list\]/im, '[ol]\1[/ol]')- raw.gsub!(/\[list\](.*?)\[\/list:u\]/im, '[ul]\1[/ul]')- raw.gsub!(/\[list=1\](.*?)\[\/list:o\]/im, '[ol]\1[/ol]')+ raw.gsub!(%r{\[list\](.*?)\[/list\]}im, '[ul]\1[/ul]')+ raw.gsub!(%r{\[list=1\](.*?)\[/list\]}im, '[ol]\1[/ol]')+ raw.gsub!(%r{\[list\](.*?)\[/list:u\]}im, '[ul]\1[/ul]')+ raw.gsub!(%r{\[list=1\](.*?)\[/list:o\]}im, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:- raw.gsub!(/\[\*\]\n/, '')- raw.gsub!(/\[\*\](.*?)\[\/\*:m\]/, '[li]\1[/li]')+ raw.gsub!(/\[\*\]\n/, "")+ raw.gsub!(%r{\[\*\](.*?)\[/\*:m\]}, '[li]\1[/li]')raw.gsub!(/\[\*\](.*?)\n/, '[li]\1[/li]')- raw.gsub!(/\[\*=1\]/, '')+ raw.gsub!(/\[\*=1\]/, "")rawenddef postprocess_post_raw(raw)# [QUOTE=<username>;<post_id>]...[/QUOTE]- raw.gsub!(/\[quote=([^;]+);(\d+)\](.+?)\[\/quote\]/im) do+ raw.gsub!(%r{\[quote=([^;]+);(\d+)\](.+?)\[/quote\]}im) doold_username, post_id, quote = $1, $2, $3new_username = get_username_for_old_username(old_username)@@ -859,7 +899,7 @@ class ImportScripts::VBulletin < ImportScripts::Baseif topic_lookup = topic_lookup_from_imported_post_id(post_id)post_number = topic_lookup[:post_number]- topic_id = topic_lookup[:topic_id]+ topic_id = topic_lookup[:topic_id]"\n[quote=\"#{new_username},post:#{post_number},topic:#{topic_id}\"]\n#{quote}\n[/quote]\n"else"\n[quote=\"#{new_username}\"]\n#{quote}\n[/quote]\n"@@ -867,11 +907,11 @@ class ImportScripts::VBulletin < ImportScripts::Baseend# remove attachments- raw.gsub!(/\[attach[^\]]*\]\d+\[\/attach\]/i, "")+ raw.gsub!(%r{\[attach[^\]]*\]\d+\[/attach\]}i, "")# [THREAD]<thread_id>[/THREAD]# ==> http://my.discourse.org/t/slug/<topic_id>- raw.gsub!(/\[thread\](\d+)\[\/thread\]/i) do+ raw.gsub!(%r{\[thread\](\d+)\[/thread\]}i) dothread_id = $1if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")topic_lookup[:url]@@ -882,7 +922,7 @@ class ImportScripts::VBulletin < ImportScripts::Base# [THREAD=<thread_id>]...[/THREAD]# ==> [...](http://my.discourse.org/t/slug/<topic_id>)- raw.gsub!(/\[thread=(\d+)\](.+?)\[\/thread\]/i) do+ raw.gsub!(%r{\[thread=(\d+)\](.+?)\[/thread\]}i) dothread_id, link = $1, $2if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")url = topic_lookup[:url]@@ -894,7 +934,7 @@ class ImportScripts::VBulletin < ImportScripts::Base# [POST]<post_id>[/POST]# ==> http://my.discourse.org/t/slug/<topic_id>/<post_number>- raw.gsub!(/\[post\](\d+)\[\/post\]/i) do+ raw.gsub!(%r{\[post\](\d+)\[/post\]}i) dopost_id = $1if topic_lookup = topic_lookup_from_imported_post_id(post_id)topic_lookup[:url]@@ -905,7 +945,7 @@ class ImportScripts::VBulletin < ImportScripts::Base# [POST=<post_id>]...[/POST]# ==> [...](http://my.discourse.org/t/<topic_slug>/<topic_id>/<post_number>)- raw.gsub!(/\[post=(\d+)\](.+?)\[\/post\]/i) do+ raw.gsub!(%r{\[post=(\d+)\](.+?)\[/post\]}i) dopost_id, link = $1, $2if topic_lookup = topic_lookup_from_imported_post_id(post_id)url = topic_lookup[:url]@@ -919,14 +959,14 @@ class ImportScripts::VBulletin < ImportScripts::Baseenddef create_permalink_file- puts '', 'Creating Permalink File...', ''+ puts "", "Creating Permalink File...", ""id_mapping = []Topic.listable_topics.find_each do |topic|pcf = topic.first_post.custom_fieldsif pcf && pcf["import_id"]- id = pcf["import_id"].split('-').last+ id = pcf["import_id"].split("-").lastid_mapping.push("XXX#{id} YYY#{topic.id}")endend@@ -940,24 +980,21 @@ class ImportScripts::VBulletin < ImportScripts::Base# endCSV.open(File.expand_path("../vb_map.csv", __FILE__), "w") do |csv|- id_mapping.each do |value|- csv << [value]- end+ id_mapping.each { |value| csv << [value] }end-enddef suspend_users- puts '', "updating banned users"+ puts "", "updating banned users"banned = 0failed = 0- total = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}userban").first['count']+ total = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}userban").first["count"]system_user = Discourse.system_usermysql_query("SELECT userid, bandate FROM #{TABLE_PREFIX}userban").each do |b|- user = User.find_by_id(user_id_from_imported_user_id(b['userid']))+ user = User.find_by_id(user_id_from_imported_user_id(b["userid"]))if useruser.suspended_at = parse_timestamp(user["bandate"])user.suspended_till = 200.years.from_now@@ -970,7 +1007,7 @@ class ImportScripts::VBulletin < ImportScripts::Basefailed += 1endelse- puts "Not found: #{b['userid']}"+ puts "Not found: #{b["userid"]}"failed += 1end@@ -985,7 +1022,6 @@ class ImportScripts::VBulletin < ImportScripts::Basedef mysql_query(sql)@client.query(sql, cache_rows: true)end-endImportScripts::VBulletin.new.performdiff --git a/script/import_scripts/vbulletin5.rb b/script/import_scripts/vbulletin5.rbindex 5e5696e4f0f..af62c0a6bb2 100644--- a/script/import_scripts/vbulletin5.rb+++ b/script/import_scripts/vbulletin5.rb@@ -1,8 +1,8 @@# frozen_string_literal: true-require 'mysql2'+require "mysql2"require File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'htmlentities'+require "htmlentities"class ImportScripts::VBulletin < ImportScripts::BaseBATCH_SIZE = 1000@@ -11,14 +11,14 @@ class ImportScripts::VBulletin < ImportScripts::Base# override these using environment vars- URL_PREFIX ||= ENV['URL_PREFIX'] || "forum/"- DB_PREFIX ||= ENV['DB_PREFIX'] || "vb_"- DB_HOST ||= ENV['DB_HOST'] || "localhost"- DB_NAME ||= ENV['DB_NAME'] || "vbulletin"- DB_PASS ||= ENV['DB_PASS'] || "password"- DB_USER ||= ENV['DB_USER'] || "username"- ATTACH_DIR ||= ENV['ATTACH_DIR'] || "/home/discourse/vbulletin/attach"- AVATAR_DIR ||= ENV['AVATAR_DIR'] || "/home/discourse/vbulletin/avatars"+ URL_PREFIX ||= ENV["URL_PREFIX"] || "forum/"+ DB_PREFIX ||= ENV["DB_PREFIX"] || "vb_"+ DB_HOST ||= ENV["DB_HOST"] || "localhost"+ DB_NAME ||= ENV["DB_NAME"] || "vbulletin"+ DB_PASS ||= ENV["DB_PASS"] || "password"+ DB_USER ||= ENV["DB_USER"] || "username"+ ATTACH_DIR ||= ENV["ATTACH_DIR"] || "/home/discourse/vbulletin/attach"+ AVATAR_DIR ||= ENV["AVATAR_DIR"] || "/home/discourse/vbulletin/avatars"def initializesuper@@ -29,16 +29,21 @@ class ImportScripts::VBulletin < ImportScripts::Base@htmlentities = HTMLEntities.new- @client = Mysql2::Client.new(- host: DB_HOST,- username: DB_USER,- database: DB_NAME,- password: DB_PASS- )-- @forum_typeid = mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Forum'").first['contenttypeid']- @channel_typeid = mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Channel'").first['contenttypeid']- @text_typeid = mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Text'").first['contenttypeid']+ @client =+ Mysql2::Client.new(host: DB_HOST, username: DB_USER, database: DB_NAME, password: DB_PASS)++ @forum_typeid =+ mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Forum'").first[+ "contenttypeid"+ ]+ @channel_typeid =+ mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Channel'").first[+ "contenttypeid"+ ]+ @text_typeid =+ mysql_query("SELECT contenttypeid FROM #{DB_PREFIX}contenttype WHERE class='Text'").first[+ "contenttypeid"+ ]enddef execute@@ -64,10 +69,7 @@ class ImportScripts::VBulletin < ImportScripts::BaseSQLcreate_groups(groups) do |group|- {- id: group["usergroupid"],- name: @htmlentities.decode(group["title"]).strip- }+ { id: group["usergroupid"], name: @htmlentities.decode(group["title"]).strip }endend@@ -102,17 +104,18 @@ class ImportScripts::VBulletin < ImportScripts::Basename: username,username: username,email: user["email"].presence || fake_email,- admin: user['admin'] == 1,+ admin: user["admin"] == 1,password: user["password"],website: user["homepage"].strip,title: @htmlentities.decode(user["usertitle"]).strip,primary_group_id: group_id_from_imported_group_id(user["usergroupid"]),created_at: parse_timestamp(user["joindate"]),- post_create_action: proc do |u|- @old_username_to_new_usernames[user["username"]] = u.username- import_profile_picture(user, u)- # import_profile_background(user, u)- end+ post_create_action:+ proc do |u|+ @old_username_to_new_usernames[user["username"]] = u.username+ import_profile_picture(user, u)+ # import_profile_background(user, u)+ end,}endend@@ -131,18 +134,18 @@ class ImportScripts::VBulletin < ImportScripts::Basereturn if picture.nil?- if picture['filedata']+ if picture["filedata"]file = Tempfile.new("profile-picture")file.write(picture["filedata"].encode("ASCII-8BIT").force_encoding("UTF-8"))file.rewindupload = UploadCreator.new(file, picture["filename"]).create_for(imported_user.id)else- filename = File.join(AVATAR_DIR, picture['filename'])+ filename = File.join(AVATAR_DIR, picture["filename"])unless File.exist?(filename)puts "Avatar file doesn't exist: #{filename}"return nilend- upload = create_upload(imported_user.id, filename, picture['filename'])+ upload = create_upload(imported_user.id, filename, picture["filename"])endreturn if !upload.persisted?@@ -151,8 +154,16 @@ class ImportScripts::VBulletin < ImportScripts::Baseimported_user.user_avatar.update(custom_upload_id: upload.id)imported_user.update(uploaded_avatar_id: upload.id)ensure- file.close rescue nil- file.unlind rescue nil+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlind+ rescue StandardError+ nil+ endenddef import_profile_background(old_user, imported_user)@@ -178,21 +189,32 @@ class ImportScripts::VBulletin < ImportScripts::Baseimported_user.user_profile.upload_profile_background(upload)ensure- file.close rescue nil- file.unlink rescue nil+ begin+ file.close+ rescue StandardError+ nil+ end+ begin+ file.unlink+ rescue StandardError+ nil+ endenddef import_categoriesputs "", "importing top level categories..."- categories = mysql_query("SELECT nodeid AS forumid, title, description, displayorder, parentid+ categories =+ mysql_query(+ "SELECT nodeid AS forumid, title, description, displayorder, parentidFROM #{DB_PREFIX}nodeWHERE parentid=#{ROOT_NODE}UNIONSELECT nodeid, title, description, displayorder, parentidFROM #{DB_PREFIX}nodeWHERE contenttypeid = #{@channel_typeid}- AND parentid IN (SELECT nodeid FROM #{DB_PREFIX}node WHERE parentid=#{ROOT_NODE})").to_a+ AND parentid IN (SELECT nodeid FROM #{DB_PREFIX}node WHERE parentid=#{ROOT_NODE})",+ ).to_atop_level_categories = categories.select { |c| c["parentid"] == ROOT_NODE }@@ -201,7 +223,7 @@ class ImportScripts::VBulletin < ImportScripts::Baseid: category["forumid"],name: @htmlentities.decode(category["title"]).strip,position: category["displayorder"],- description: @htmlentities.decode(category["description"]).strip+ description: @htmlentities.decode(category["description"]).strip,}end@@ -223,7 +245,7 @@ class ImportScripts::VBulletin < ImportScripts::Basename: @htmlentities.decode(category["title"]).strip,position: category["displayorder"],description: @htmlentities.decode(category["description"]).strip,- parent_category_id: category_id_from_imported_category_id(category["parentid"])+ parent_category_id: category_id_from_imported_category_id(category["parentid"]),}endend@@ -234,13 +256,17 @@ class ImportScripts::VBulletin < ImportScripts::Base# keep track of closed topics@closed_topic_ids = []- topic_count = mysql_query("SELECT COUNT(nodeid) cnt+ topic_count =+ mysql_query(+ "SELECT COUNT(nodeid) cntFROM #{DB_PREFIX}nodeWHERE (unpublishdate = 0 OR unpublishdate IS NULL)AND (approved = 1 AND showapproved = 1)AND parentid IN (- SELECT nodeid FROM #{DB_PREFIX}node WHERE contenttypeid=#{@channel_typeid} ) AND contenttypeid=#{@text_typeid};"- ).first["cnt"]+ SELECT nodeid FROM #{DB_PREFIX}node WHERE contenttypeid=#{@channel_typeid} ) AND contenttypeid=#{@text_typeid};",+ ).first[+ "cnt"+ ]batches(BATCH_SIZE) do |offset|topics = mysql_query <<-SQL@@ -265,7 +291,12 @@ class ImportScripts::VBulletin < ImportScripts::Base# next if all_records_exist? :posts, topics.map {|t| "thread-#{topic["threadid"]}" }create_posts(topics, total: topic_count, offset: offset) do |topic|- raw = preprocess_post_raw(topic["raw"]) rescue nil+ raw =+ begin+ preprocess_post_raw(topic["raw"])+ rescue StandardError+ nil+ endnext if raw.blank?topic_id = "thread-#{topic["threadid"]}"@closed_topic_ids << topic_id if topic["open"] == "0"@@ -291,11 +322,16 @@ class ImportScripts::VBulletin < ImportScripts::Base# make sure `firstpostid` is indexedbeginmysql_query("CREATE INDEX firstpostid_index ON thread (firstpostid)")- rescue+ rescue StandardErrorend- post_count = mysql_query("SELECT COUNT(nodeid) cnt FROM #{DB_PREFIX}node WHERE parentid NOT IN (- SELECT nodeid FROM #{DB_PREFIX}node WHERE contenttypeid=#{@channel_typeid} ) AND contenttypeid=#{@text_typeid};").first["cnt"]+ post_count =+ mysql_query(+ "SELECT COUNT(nodeid) cnt FROM #{DB_PREFIX}node WHERE parentid NOT IN (+ SELECT nodeid FROM #{DB_PREFIX}node WHERE contenttypeid=#{@channel_typeid} ) AND contenttypeid=#{@text_typeid};",+ ).first[+ "cnt"+ ]batches(BATCH_SIZE) do |offset|posts = mysql_query <<-SQL@@ -338,10 +374,14 @@ class ImportScripts::VBulletin < ImportScripts::Baseenddef import_attachments- puts '', 'importing attachments...'+ puts "", "importing attachments..."- ext = mysql_query("SELECT GROUP_CONCAT(DISTINCT(extension)) exts FROM #{DB_PREFIX}filedata").first['exts'].split(',')- SiteSetting.authorized_extensions = (SiteSetting.authorized_extensions.split("|") + ext).uniq.join("|")+ ext =+ mysql_query("SELECT GROUP_CONCAT(DISTINCT(extension)) exts FROM #{DB_PREFIX}filedata").first[+ "exts"+ ].split(",")+ SiteSetting.authorized_extensions =+ (SiteSetting.authorized_extensions.split("|") + ext).uniq.join("|")uploads = mysql_query <<-SQLSELECT n.parentid nodeid, a.filename, fd.userid, LENGTH(fd.filedata) AS dbsize, filedata, fd.filedataid@@ -354,32 +394,43 @@ class ImportScripts::VBulletin < ImportScripts::Basetotal_count = uploads.countuploads.each do |upload|- post_id = PostCustomField.where(name: 'import_id').where(value: upload['nodeid']).first&.post_id- post_id = PostCustomField.where(name: 'import_id').where(value: "thread-#{upload['nodeid']}").first&.post_id unless post_id+ post_id =+ PostCustomField.where(name: "import_id").where(value: upload["nodeid"]).first&.post_id+ post_id =+ PostCustomField+ .where(name: "import_id")+ .where(value: "thread-#{upload["nodeid"]}")+ .first+ &.post_id unless post_idif post_id.nil?- puts "Post for #{upload['nodeid']} not found"+ puts "Post for #{upload["nodeid"]} not found"nextendpost = Post.find(post_id)- filename = File.join(ATTACH_DIR, upload['userid'].to_s.split('').join('/'), "#{upload['filedataid']}.attach")- real_filename = upload['filename']- real_filename.prepend SecureRandom.hex if real_filename[0] == '.'+ filename =+ File.join(+ ATTACH_DIR,+ upload["userid"].to_s.split("").join("/"),+ "#{upload["filedataid"]}.attach",+ )+ real_filename = upload["filename"]+ real_filename.prepend SecureRandom.hex if real_filename[0] == "."unless File.exist?(filename)# attachments can be on filesystem or in database# try to retrieve from database if the file did not exist on filesystem- if upload['dbsize'].to_i == 0- puts "Attachment file #{upload['filedataid']} doesn't exist"+ if upload["dbsize"].to_i == 0+ puts "Attachment file #{upload["filedataid"]} doesn't exist"nextend- tmpfile = 'attach_' + upload['filedataid'].to_s- filename = File.join('/tmp/', tmpfile)- File.open(filename, 'wb') { |f|+ tmpfile = "attach_" + upload["filedataid"].to_s+ filename = File.join("/tmp/", tmpfile)+ File.open(filename, "wb") do |f|#f.write(PG::Connection.unescape_bytea(row['filedata']))- f.write(upload['filedata'])- }+ f.write(upload["filedata"])+ endendupl_obj = create_upload(post.user.id, filename, real_filename)@@ -388,7 +439,9 @@ class ImportScripts::VBulletin < ImportScripts::Baseif !post.raw[html]post.raw += "\n\n#{html}\n\n"post.save!- PostUpload.create!(post: post, upload: upl_obj) unless PostUpload.where(post: post, upload: upl_obj).exists?+ unless PostUpload.where(post: post, upload: upl_obj).exists?+ PostUpload.create!(post: post, upload: upl_obj)+ endendelseputs "Fail"@@ -447,170 +500,177 @@ class ImportScripts::VBulletin < ImportScripts::Baseraw = @htmlentities.decode(raw)# fix whitespaces- raw = raw.gsub(/(\\r)?\\n/, "\n")- .gsub("\\t", "\t")+ raw = raw.gsub(/(\\r)?\\n/, "\n").gsub("\\t", "\t")# [HTML]...[/HTML]- raw = raw.gsub(/\[html\]/i, "\n```html\n")- .gsub(/\[\/html\]/i, "\n```\n")+ raw = raw.gsub(/\[html\]/i, "\n```html\n").gsub(%r{\[/html\]}i, "\n```\n")# [PHP]...[/PHP]- raw = raw.gsub(/\[php\]/i, "\n```php\n")- .gsub(/\[\/php\]/i, "\n```\n")+ raw = raw.gsub(/\[php\]/i, "\n```php\n").gsub(%r{\[/php\]}i, "\n```\n")# [HIGHLIGHT="..."]raw = raw.gsub(/\[highlight="?(\w+)"?\]/i) { "\n```#{$1.downcase}\n" }# [CODE]...[/CODE]# [HIGHLIGHT]...[/HIGHLIGHT]- raw = raw.gsub(/\[\/?code\]/i, "\n```\n")- .gsub(/\[\/?highlight\]/i, "\n```\n")+ raw = raw.gsub(%r{\[/?code\]}i, "\n```\n").gsub(%r{\[/?highlight\]}i, "\n```\n")# [SAMP]...[/SAMP]- raw = raw.gsub(/\[\/?samp\]/i, "`")+ raw = raw.gsub(%r{\[/?samp\]}i, "`")# replace all chevrons with HTML entities# NOTE: must be done# - AFTER all the "code" processing# - BEFORE the "quote" processing- raw = raw.gsub(/`([^`]+)`/im) { "`" + $1.gsub("<", "\u2603") + "`" }- .gsub("<", "<")- .gsub("\u2603", "<")-- raw = raw.gsub(/`([^`]+)`/im) { "`" + $1.gsub(">", "\u2603") + "`" }- .gsub(">", ">")- .gsub("\u2603", ">")+ raw =+ raw+ .gsub(/`([^`]+)`/im) { "`" + $1.gsub("<", "\u2603") + "`" }+ .gsub("<", "<")+ .gsub("\u2603", "<")++ raw =+ raw+ .gsub(/`([^`]+)`/im) { "`" + $1.gsub(">", "\u2603") + "`" }+ .gsub(">", ">")+ .gsub("\u2603", ">")# [URL=...]...[/URL]- raw.gsub!(/\[url="?(.+?)"?\](.+?)\[\/url\]/i) { "<a href=\"#{$1}\">#{$2}</a>" }+ raw.gsub!(%r{\[url="?(.+?)"?\](.+?)\[/url\]}i) { "<a href=\"#{$1}\">#{$2}</a>" }# [URL]...[/URL]# [MP3]...[/MP3]- raw = raw.gsub(/\[\/?url\]/i, "")- .gsub(/\[\/?mp3\]/i, "")+ raw = raw.gsub(%r{\[/?url\]}i, "").gsub(%r{\[/?mp3\]}i, "")# [MENTION]<username>[/MENTION]- raw = raw.gsub(/\[mention\](.+?)\[\/mention\]/i) do- old_username = $1- if @old_username_to_new_usernames.has_key?(old_username)- old_username = @old_username_to_new_usernames[old_username]+ raw =+ raw.gsub(%r{\[mention\](.+?)\[/mention\]}i) do+ old_username = $1+ if @old_username_to_new_usernames.has_key?(old_username)+ old_username = @old_username_to_new_usernames[old_username]+ end+ "@#{old_username}"end- "@#{old_username}"- end# [USER=<user_id>]<username>[/USER]- raw = raw.gsub(/\[user="?(\d+)"?\](.+?)\[\/user\]/i) do- user_id, old_username = $1, $2- if @old_username_to_new_usernames.has_key?(old_username)- new_username = @old_username_to_new_usernames[old_username]- else- new_username = old_username+ raw =+ raw.gsub(%r{\[user="?(\d+)"?\](.+?)\[/user\]}i) do+ user_id, old_username = $1, $2+ if @old_username_to_new_usernames.has_key?(old_username)+ new_username = @old_username_to_new_usernames[old_username]+ else+ new_username = old_username+ end+ "@#{new_username}"end- "@#{new_username}"- end# [FONT=blah] and [COLOR=blah]# no idea why the /i is not matching case insensitive..- raw.gsub! /\[color=.*?\](.*?)\[\/color\]/im, '\1'- raw.gsub! /\[COLOR=.*?\](.*?)\[\/COLOR\]/im, '\1'- raw.gsub! /\[font=.*?\](.*?)\[\/font\]/im, '\1'- raw.gsub! /\[FONT=.*?\](.*?)\[\/FONT\]/im, '\1'+ raw.gsub! %r{\[color=.*?\](.*?)\[/color\]}im, '\1'+ raw.gsub! %r{\[COLOR=.*?\](.*?)\[/COLOR\]}im, '\1'+ raw.gsub! %r{\[font=.*?\](.*?)\[/font\]}im, '\1'+ raw.gsub! %r{\[FONT=.*?\](.*?)\[/FONT\]}im, '\1'# [CENTER]...[/CENTER]- raw.gsub! /\[CENTER\](.*?)\[\/CENTER\]/im, '\1'+ raw.gsub! %r{\[CENTER\](.*?)\[/CENTER\]}im, '\1'# fix LIST- raw.gsub! /\[LIST\](.*?)\[\/LIST\]/im, '<ul>\1</ul>'- raw.gsub! /\[\*\]/im, '<li>'+ raw.gsub! %r{\[LIST\](.*?)\[/LIST\]}im, '<ul>\1</ul>'+ raw.gsub! /\[\*\]/im, "<li>"# [QUOTE]...[/QUOTE]- raw = raw.gsub(/\[quote\](.+?)\[\/quote\]/im) { "\n> #{$1}\n" }+ raw = raw.gsub(%r{\[quote\](.+?)\[/quote\]}im) { "\n> #{$1}\n" }# [QUOTE=<username>]...[/QUOTE]- raw = raw.gsub(/\[quote=([^;\]]+)\](.+?)\[\/quote\]/im) do- old_username, quote = $1, $2+ raw =+ raw.gsub(%r{\[quote=([^;\]]+)\](.+?)\[/quote\]}im) do+ old_username, quote = $1, $2- if @old_username_to_new_usernames.has_key?(old_username)- old_username = @old_username_to_new_usernames[old_username]+ if @old_username_to_new_usernames.has_key?(old_username)+ old_username = @old_username_to_new_usernames[old_username]+ end+ "\n[quote=\"#{old_username}\"]\n#{quote}\n[/quote]\n"end- "\n[quote=\"#{old_username}\"]\n#{quote}\n[/quote]\n"- end# [YOUTUBE]<id>[/YOUTUBE]- raw = raw.gsub(/\[youtube\](.+?)\[\/youtube\]/i) { "\n//youtu.be/#{$1}\n" }+ raw = raw.gsub(%r{\[youtube\](.+?)\[/youtube\]}i) { "\n//youtu.be/#{$1}\n" }# [VIDEO=youtube;<id>]...[/VIDEO]- raw = raw.gsub(/\[video=youtube;([^\]]+)\].*?\[\/video\]/i) { "\n//youtu.be/#{$1}\n" }+ raw = raw.gsub(%r{\[video=youtube;([^\]]+)\].*?\[/video\]}i) { "\n//youtu.be/#{$1}\n" }rawenddef postprocess_post_raw(raw)# [QUOTE=<username>;<post_id>]...[/QUOTE]- raw = raw.gsub(/\[quote=([^;]+);n(\d+)\](.+?)\[\/quote\]/im) do- old_username, post_id, quote = $1, $2, $3+ raw =+ raw.gsub(%r{\[quote=([^;]+);n(\d+)\](.+?)\[/quote\]}im) do+ old_username, post_id, quote = $1, $2, $3- if @old_username_to_new_usernames.has_key?(old_username)- old_username = @old_username_to_new_usernames[old_username]- end+ if @old_username_to_new_usernames.has_key?(old_username)+ old_username = @old_username_to_new_usernames[old_username]+ end- if topic_lookup = topic_lookup_from_imported_post_id(post_id)- post_number = topic_lookup[:post_number]- topic_id = topic_lookup[:topic_id]- "\n[quote=\"#{old_username},post:#{post_number},topic:#{topic_id}\"]\n#{quote}\n[/quote]\n"- else- "\n[quote=\"#{old_username}\"]\n#{quote}\n[/quote]\n"+ if topic_lookup = topic_lookup_from_imported_post_id(post_id)+ post_number = topic_lookup[:post_number]+ topic_id = topic_lookup[:topic_id]+ "\n[quote=\"#{old_username},post:#{post_number},topic:#{topic_id}\"]\n#{quote}\n[/quote]\n"+ else+ "\n[quote=\"#{old_username}\"]\n#{quote}\n[/quote]\n"+ endend- end# remove attachments- raw = raw.gsub(/\[attach[^\]]*\]\d+\[\/attach\]/i, "")+ raw = raw.gsub(%r{\[attach[^\]]*\]\d+\[/attach\]}i, "")# [THREAD]<thread_id>[/THREAD]# ==> http://my.discourse.org/t/slug/<topic_id>- raw = raw.gsub(/\[thread\](\d+)\[\/thread\]/i) do- thread_id = $1- if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")- topic_lookup[:url]- else- $&+ raw =+ raw.gsub(%r{\[thread\](\d+)\[/thread\]}i) do+ thread_id = $1+ if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")+ topic_lookup[:url]+ else+ $&+ endend- end# [THREAD=<thread_id>]...[/THREAD]# ==> [...](http://my.discourse.org/t/slug/<topic_id>)- raw = raw.gsub(/\[thread=(\d+)\](.+?)\[\/thread\]/i) do- thread_id, link = $1, $2- if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")- url = topic_lookup[:url]- "[#{link}](#{url})"- else- $&+ raw =+ raw.gsub(%r{\[thread=(\d+)\](.+?)\[/thread\]}i) do+ thread_id, link = $1, $2+ if topic_lookup = topic_lookup_from_imported_post_id("thread-#{thread_id}")+ url = topic_lookup[:url]+ "[#{link}](#{url})"+ else+ $&+ endend- end# [POST]<post_id>[/POST]# ==> http://my.discourse.org/t/slug/<topic_id>/<post_number>- raw = raw.gsub(/\[post\](\d+)\[\/post\]/i) do- post_id = $1- if topic_lookup = topic_lookup_from_imported_post_id(post_id)- topic_lookup[:url]- else- $&+ raw =+ raw.gsub(%r{\[post\](\d+)\[/post\]}i) do+ post_id = $1+ if topic_lookup = topic_lookup_from_imported_post_id(post_id)+ topic_lookup[:url]+ else+ $&+ endend- end# [POST=<post_id>]...[/POST]# ==> [...](http://my.discourse.org/t/<topic_slug>/<topic_id>/<post_number>)- raw = raw.gsub(/\[post=(\d+)\](.+?)\[\/post\]/i) do- post_id, link = $1, $2- if topic_lookup = topic_lookup_from_imported_post_id(post_id)- url = topic_lookup[:url]- "[#{link}](#{url})"- else- $&+ raw =+ raw.gsub(%r{\[post=(\d+)\](.+?)\[/post\]}i) do+ post_id, link = $1, $2+ if topic_lookup = topic_lookup_from_imported_post_id(post_id)+ url = topic_lookup[:url]+ "[#{link}](#{url})"+ else+ $&+ endend- endrawend@@ -619,13 +679,17 @@ class ImportScripts::VBulletin < ImportScripts::Baseputs "", "creating permalinks..."current_count = 0- total_count = mysql_query("SELECT COUNT(nodeid) cnt+ total_count =+ mysql_query(+ "SELECT COUNT(nodeid) cntFROM #{DB_PREFIX}nodeWHERE (unpublishdate = 0 OR unpublishdate IS NULL)AND (approved = 1 AND showapproved = 1)AND parentid IN (- SELECT nodeid FROM #{DB_PREFIX}node WHERE contenttypeid=#{@channel_typeid} ) AND contenttypeid=#{@text_typeid};"- ).first["cnt"]+ SELECT nodeid FROM #{DB_PREFIX}node WHERE contenttypeid=#{@channel_typeid} ) AND contenttypeid=#{@text_typeid};",+ ).first[+ "cnt"+ ]batches(BATCH_SIZE) do |offset|topics = mysql_query <<-SQL@@ -647,12 +711,16 @@ class ImportScripts::VBulletin < ImportScripts::Basetopics.each do |topic|current_count += 1print_status current_count, total_count- disc_topic = topic_lookup_from_imported_post_id("thread-#{topic['nodeid']}")-- Permalink.create(- url: "#{URL_PREFIX}#{topic['p1']}/#{topic['p2']}/#{topic['nodeid']}-#{topic['p3']}",- topic_id: disc_topic[:topic_id]- ) rescue nil+ disc_topic = topic_lookup_from_imported_post_id("thread-#{topic["nodeid"]}")++ begin+ Permalink.create(+ url: "#{URL_PREFIX}#{topic["p1"]}/#{topic["p2"]}/#{topic["nodeid"]}-#{topic["p3"]}",+ topic_id: disc_topic[:topic_id],+ )+ rescue StandardError+ nil+ endendend@@ -664,8 +732,13 @@ class ImportScripts::VBulletin < ImportScripts::BaseAND parentid=#{ROOT_NODE};SQLcats.each do |c|- category_id = CategoryCustomField.where(name: 'import_id').where(value: c['nodeid']).first.category_id- Permalink.create(url: "#{URL_PREFIX}#{c['urlident']}", category_id: category_id) rescue nil+ category_id =+ CategoryCustomField.where(name: "import_id").where(value: c["nodeid"]).first.category_id+ begin+ Permalink.create(url: "#{URL_PREFIX}#{c["urlident"]}", category_id: category_id)+ rescue StandardError+ nil+ endend# subcats@@ -677,8 +750,13 @@ class ImportScripts::VBulletin < ImportScripts::BaseAND n1.contenttypeid=#{@channel_typeid};SQLsubcats.each do |sc|- category_id = CategoryCustomField.where(name: 'import_id').where(value: sc['nodeid']).first.category_id- Permalink.create(url: "#{URL_PREFIX}#{sc['p1']}/#{sc['p2']}", category_id: category_id) rescue nil+ category_id =+ CategoryCustomField.where(name: "import_id").where(value: sc["nodeid"]).first.category_id+ begin+ Permalink.create(url: "#{URL_PREFIX}#{sc["p1"]}/#{sc["p2"]}", category_id: category_id)+ rescue StandardError+ nil+ endendend@@ -689,7 +767,7 @@ class ImportScripts::VBulletin < ImportScripts::BaseSiteSetting.max_tags_per_topic = 100staff_guardian = Guardian.new(Discourse.system_user)- records = mysql_query(<<~SQL+ records = mysql_query(<<~SQL).to_aSELECT nodeid, GROUP_CONCAT(tagtext) tagsFROM #{DB_PREFIX}tag tLEFT JOIN #{DB_PREFIX}tagnode tn ON tn.tagid = t.tagid@@ -697,7 +775,6 @@ class ImportScripts::VBulletin < ImportScripts::BaseAND tn.nodeid IS NOT NULLGROUP BY nodeidSQL- ).to_acurrent_count = 0total_count = records.count@@ -705,11 +782,11 @@ class ImportScripts::VBulletin < ImportScripts::Baserecords.each do |rec|current_count += 1print_status current_count, total_count- tl = topic_lookup_from_imported_post_id("thread-#{rec['nodeid']}")- next if tl.nil? # topic might have been deleted+ tl = topic_lookup_from_imported_post_id("thread-#{rec["nodeid"]}")+ next if tl.nil? # topic might have been deletedtopic = Topic.find(tl[:topic_id])- tag_names = rec['tags'].force_encoding("UTF-8").split(',')+ tag_names = rec["tags"].force_encoding("UTF-8").split(",")DiscourseTagging.tag_topic_by_names(topic, staff_guardian, tag_names)endenddiff --git a/script/import_scripts/xenforo.rb b/script/import_scripts/xenforo.rbindex 38e45342c65..1c9aaaeb774 100755--- a/script/import_scripts/xenforo.rb+++ b/script/import_scripts/xenforo.rb@@ -3,11 +3,11 @@require "mysql2"begin- require 'php_serialize' # https://github.com/jqr/php-serialize+ require "php_serialize" # https://github.com/jqr/php-serializerescue LoadErrorputs- puts 'php_serialize not found.'- puts 'Add to Gemfile, like this: '+ puts "php_serialize not found."+ puts "Add to Gemfile, like this: "putsputs "echo gem \\'php-serialize\\' >> Gemfile"puts "bundle install"@@ -19,20 +19,20 @@ require File.expand_path(File.dirname(__FILE__) + "/base.rb")# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/xenforo.rbclass ImportScripts::XenForo < ImportScripts::Base-XENFORO_DB = "xenforo_db"TABLE_PREFIX = "xf_"BATCH_SIZE = 1000- ATTACHMENT_DIR = '/tmp/attachments'+ ATTACHMENT_DIR = "/tmp/attachments"def initializesuper- @client = Mysql2::Client.new(- host: "localhost",- username: "root",- password: "pa$$word",- database: XENFORO_DB- )+ @client =+ Mysql2::Client.new(+ host: "localhost",+ username: "root",+ password: "pa$$word",+ database: XENFORO_DB,+ )@category_mappings = {}@prefix_as_category = false@@ -47,10 +47,8 @@ class ImportScripts::XenForo < ImportScripts::Baseenddef import_avatar(id, imported_user)- filename = File.join(AVATAR_DIR, 'l', (id / 1000).to_s, "#{id}.jpg")- unless File.exist?(filename)- return nil- end+ filename = File.join(AVATAR_DIR, "l", (id / 1000).to_s, "#{id}.jpg")+ return nil unless File.exist?(filename)upload = create_upload(imported_user.id, filename, "avatar_#{id}")return if !upload.persisted?imported_user.create_user_avatar@@ -59,36 +57,42 @@ class ImportScripts::XenForo < ImportScripts::Baseenddef import_users- puts '', "creating users"+ puts "", "creating users"- total_count = mysql_query("SELECT count(*) count FROM #{TABLE_PREFIX}user WHERE user_state = 'valid' AND is_banned = 0;").first['count']+ total_count =+ mysql_query(+ "SELECT count(*) count FROM #{TABLE_PREFIX}user WHERE user_state = 'valid' AND is_banned = 0;",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT user_id id, username, email, custom_title title, register_date created_at,+ results =+ mysql_query(+ "SELECT user_id id, username, email, custom_title title, register_date created_at,last_activity last_visit_time, user_group_id, is_moderator, is_admin, is_staffFROM #{TABLE_PREFIX}userWHERE user_state = 'valid' AND is_banned = 0LIMIT #{BATCH_SIZE}- OFFSET #{offset};")+ OFFSET #{offset};",+ )break if results.size < 1next if all_records_exist? :users, results.map { |u| u["id"].to_i }create_users(results, total: total_count, offset: offset) do |user|- next if user['username'].blank?- { id: user['id'],- email: user['email'],- username: user['username'],- title: user['title'],- created_at: Time.zone.at(user['created_at']),- last_seen_at: Time.zone.at(user['last_visit_time']),- moderator: user['is_moderator'] == 1 || user['is_staff'] == 1,- admin: user['is_admin'] == 1,- post_create_action: proc do |u|- import_avatar(user['id'], u)- end+ next if user["username"].blank?+ {+ id: user["id"],+ email: user["email"],+ username: user["username"],+ title: user["title"],+ created_at: Time.zone.at(user["created_at"]),+ last_seen_at: Time.zone.at(user["last_visit_time"]),+ moderator: user["is_moderator"] == 1 || user["is_staff"] == 1,+ admin: user["is_admin"] == 1,+ post_create_action: proc { |u| import_avatar(user["id"], u) },}endend@@ -97,7 +101,9 @@ class ImportScripts::XenForo < ImportScripts::Basedef import_categoriesputs "", "importing categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT node_id id,title,description,@@ -106,20 +112,22 @@ class ImportScripts::XenForo < ImportScripts::Basedisplay_orderFROM #{TABLE_PREFIX}nodeORDER BY parent_node_id, display_order- ").to_a+ ",+ ).to_atop_level_categories = categories.select { |c| c["parent_node_id"] == 0 }create_categories(top_level_categories) do |c|{- id: c['id'],- name: c['title'],- description: c['description'],- position: c['display_order'],- post_create_action: proc do |category|- url = "board/#{c['node_name']}"- Permalink.find_or_create_by(url: url, category_id: category.id)- end+ id: c["id"],+ name: c["title"],+ description: c["description"],+ position: c["display_order"],+ post_create_action:+ proc do |category|+ url = "board/#{c["node_name"]}"+ Permalink.find_or_create_by(url: url, category_id: category.id)+ end,}end@@ -129,40 +137,41 @@ class ImportScripts::XenForo < ImportScripts::Basecreate_categories(subcategories) do |c|{- id: c['id'],- name: c['title'],- description: c['description'],- position: c['display_order'],- parent_category_id: category_id_from_imported_category_id(c['parent_node_id']),- post_create_action: proc do |category|- url = "board/#{c['node_name']}"- Permalink.find_or_create_by(url: url, category_id: category.id)- end+ id: c["id"],+ name: c["title"],+ description: c["description"],+ position: c["display_order"],+ parent_category_id: category_id_from_imported_category_id(c["parent_node_id"]),+ post_create_action:+ proc do |category|+ url = "board/#{c["node_name"]}"+ Permalink.find_or_create_by(url: url, category_id: category.id)+ end,}end- subcategory_ids = Set.new(subcategories.map { |c| c['id'] })+ subcategory_ids = Set.new(subcategories.map { |c| c["id"] })# deeper categories need to be tagscategories.each do |c|- next if c['parent_node_id'] == 0- next if top_level_category_ids.include?(c['id'])- next if subcategory_ids.include?(c['id'])+ next if c["parent_node_id"] == 0+ next if top_level_category_ids.include?(c["id"])+ next if subcategory_ids.include?(c["id"])# Find a subcategory for topics in this categoryparent = c- while !parent.nil? && !subcategory_ids.include?(parent['id'])- parent = categories.find { |subcat| subcat['id'] == parent['parent_node_id'] }+ while !parent.nil? && !subcategory_ids.include?(parent["id"])+ parent = categories.find { |subcat| subcat["id"] == parent["parent_node_id"] }endif parent- tag_name = DiscourseTagging.clean_tag(c['title'])- @category_mappings[c['id']] = {- category_id: category_id_from_imported_category_id(parent['id']),- tag: Tag.find_by_name(tag_name) || Tag.create(name: tag_name)+ tag_name = DiscourseTagging.clean_tag(c["title"])+ @category_mappings[c["id"]] = {+ category_id: category_id_from_imported_category_id(parent["id"]),+ tag: Tag.find_by_name(tag_name) || Tag.create(name: tag_name),}else- puts '', "Couldn't find a category for #{c['id']} '#{c['title']}'!"+ puts "", "Couldn't find a category for #{c["id"]} '#{c["title"]}'!"endendend@@ -172,40 +181,46 @@ class ImportScripts::XenForo < ImportScripts::Basedef import_categories_from_thread_prefixesputs "", "importing categories..."- categories = mysql_query("+ categories =+ mysql_query(+ "SELECT prefix_id idFROM #{TABLE_PREFIX}thread_prefixORDER BY prefix_id ASC- ").to_a+ ",+ ).to_acreate_categories(categories) do |category|- {- id: category["id"],- name: "Category-#{category["id"]}"- }+ { id: category["id"], name: "Category-#{category["id"]}" }end@prefix_as_category = trueenddef import_likes- puts '', 'importing likes'- total_count = mysql_query("SELECT COUNT(*) AS count FROM #{TABLE_PREFIX}liked_content WHERE content_type = 'post'").first["count"]+ puts "", "importing likes"+ total_count =+ mysql_query(+ "SELECT COUNT(*) AS count FROM #{TABLE_PREFIX}liked_content WHERE content_type = 'post'",+ ).first[+ "count"+ ]batches(BATCH_SIZE) do |offset|- results = mysql_query(- "SELECT like_id, content_id, like_user_id, like_date+ results =+ mysql_query(+ "SELECT like_id, content_id, like_user_id, like_dateFROM #{TABLE_PREFIX}liked_contentWHERE content_type = 'post'ORDER BY like_idLIMIT #{BATCH_SIZE}- OFFSET #{offset};"- )+ OFFSET #{offset};",+ )break if results.size < 1create_likes(results, total: total_count, offset: offset) do |row|{- post_id: row['content_id'],- user_id: row['like_user_id'],- created_at: Time.zone.at(row['like_date'])+ post_id: row["content_id"],+ user_id: row["like_user_id"],+ created_at: Time.zone.at(row["like_date"]),}endend@@ -216,10 +231,11 @@ class ImportScripts::XenForo < ImportScripts::Basetotal_count = mysql_query("SELECT count(*) count from #{TABLE_PREFIX}post").first["count"]- posts_sql = "+ posts_sql =+ "SELECT p.post_id id,t.thread_id topic_id,- #{@prefix_as_category ? 't.prefix_id' : 't.node_id'} category_id,+ #{@prefix_as_category ? "t.prefix_id" : "t.node_id"} category_id,t.title title,t.first_post_id first_post_id,t.view_count,@@ -238,35 +254,35 @@ class ImportScripts::XenForo < ImportScripts::Baseresults = mysql_query("#{posts_sql} OFFSET #{offset};").to_abreak if results.size < 1- next if all_records_exist? :posts, results.map { |p| p['id'] }+ next if all_records_exist? :posts, results.map { |p| p["id"] }create_posts(results, total: total_count, offset: offset) do |m|skip = falsemapped = {}- mapped[:id] = m['id']- mapped[:user_id] = user_id_from_imported_user_id(m['user_id']) || -1- mapped[:raw] = process_xenforo_post(m['raw'], m['id'])- mapped[:created_at] = Time.zone.at(m['created_at'])+ mapped[:id] = m["id"]+ mapped[:user_id] = user_id_from_imported_user_id(m["user_id"]) || -1+ mapped[:raw] = process_xenforo_post(m["raw"], m["id"])+ mapped[:created_at] = Time.zone.at(m["created_at"])- if m['id'] == m['first_post_id']- if m['category_id'].to_i == 0 || m['category_id'].nil?+ if m["id"] == m["first_post_id"]+ if m["category_id"].to_i == 0 || m["category_id"].nil?mapped[:category] = SiteSetting.uncategorized_category_idelse- mapped[:category] = category_id_from_imported_category_id(m['category_id'].to_i) ||- @category_mappings[m['category_id']].try(:[], :category_id)+ mapped[:category] = category_id_from_imported_category_id(m["category_id"].to_i) ||+ @category_mappings[m["category_id"]].try(:[], :category_id)end- mapped[:title] = CGI.unescapeHTML(m['title'])- mapped[:views] = m['view_count']+ mapped[:title] = CGI.unescapeHTML(m["title"])+ mapped[:views] = m["view_count"]mapped[:post_create_action] = proc do |pp|- Permalink.find_or_create_by(url: "threads/#{m['topic_id']}", topic_id: pp.topic_id)+ Permalink.find_or_create_by(url: "threads/#{m["topic_id"]}", topic_id: pp.topic_id)endelse- parent = topic_lookup_from_imported_post_id(m['first_post_id'])+ parent = topic_lookup_from_imported_post_id(m["first_post_id"])if parentmapped[:topic_id] = parent[:topic_id]else- puts "Parent post #{m['first_post_id']} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"+ puts "Parent post #{m["first_post_id"]} doesn't exist. Skipping #{m["id"]}: #{m["title"][0..40]}"skip = trueendend@@ -281,16 +297,15 @@ class ImportScripts::XenForo < ImportScripts::Basebreak if results.size < 1results.each do |m|- next unless m['id'] == m['first_post_id'] && m['category_id'].to_i > 0- next unless tag = @category_mappings[m['category_id']].try(:[], :tag)- next unless topic_mapping = topic_lookup_from_imported_post_id(m['id'])+ next unless m["id"] == m["first_post_id"] && m["category_id"].to_i > 0+ next unless tag = @category_mappings[m["category_id"]].try(:[], :tag)+ next unless topic_mapping = topic_lookup_from_imported_post_id(m["id"])topic = Topic.find_by_id(topic_mapping[:topic_id])topic.tags = [tag] if topicendend-enddef import_private_messages@@ -318,29 +333,29 @@ class ImportScripts::XenForo < ImportScripts::Baseuser_id: user_id,raw: raw,created_at: Time.zone.at(post["message_date"].to_i),- import_mode: true+ import_mode: true,}unless post["topic_id"] > 0msg[:title] = post["title"]msg[:archetype] = Archetype.private_message- to_user_array = PHP.unserialize(post['recipients'])+ to_user_array = PHP.unserialize(post["recipients"])if to_user_array.size > 0discourse_user_ids = to_user_array.keys.map { |id| user_id_from_imported_user_id(id) }usernames = User.where(id: [discourse_user_ids]).pluck(:username)- msg[:target_usernames] = usernames.join(',')+ msg[:target_usernames] = usernames.join(",")endelsetopic_id = post["topic_id"]if t = topic_lookup_from_imported_post_id("pm_#{topic_id}")msg[:topic_id] = t[:topic_id]else- puts "Topic ID #{topic_id} not found, skipping post #{post['message_id']} from #{post['user_id']}"+ puts "Topic ID #{topic_id} not found, skipping post #{post["message_id"]} from #{post["user_id"]}"nextendendmsgelse- puts "Empty message, skipping post #{post['message_id']}"+ puts "Empty message, skipping post #{post["message_id"]}"nextendend@@ -351,18 +366,18 @@ class ImportScripts::XenForo < ImportScripts::Bases = raw.dup# :) is encoded as <!-- s:) --><img src="{SMILIES_PATH}/icon_e_smile.gif" alt=":)" title="Smile" /><!-- s:) -->- s.gsub!(/<!-- s(\S+) --><img (?:[^>]+) \/><!-- s(?:\S+) -->/, '\1')+ s.gsub!(%r{<!-- s(\S+) --><img (?:[^>]+) /><!-- s(?:\S+) -->}, '\1')# Some links look like this: <!-- m --><a class="postlink" href="http://www.onegameamonth.com">http://www.onegameamonth.com</a><!-- m -->- s.gsub!(/<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)<\/a><!-- \w -->/, '[\2](\1)')+ s.gsub!(%r{<!-- \w --><a(?:.+)href="(\S+)"(?:.*)>(.+)</a><!-- \w -->}, '[\2](\1)')# Many phpbb bbcode tags have a hash attached to them. Examples:# [url=https://google.com:1qh1i7ky]click here[/url:1qh1i7ky]# [quote="cybereality":b0wtlzex]Some text.[/quote:b0wtlzex]- s.gsub!(/:(?:\w{8})\]/, ']')+ s.gsub!(/:(?:\w{8})\]/, "]")# Remove mybb video tags.- s.gsub!(/(^\[video=.*?\])|(\[\/video\]$)/, '')+ s.gsub!(%r{(^\[video=.*?\])|(\[/video\]$)}, "")s = CGI.unescapeHTML(s)@@ -370,18 +385,16 @@ class ImportScripts::XenForo < ImportScripts::Base# [http://answers.yahoo.com/question/index ... 223AAkkPli](http://answers.yahoo.com/question/index?qid=20070920134223AAkkPli)##Fix for the error: xenforo.rb: 160: in `gsub!': invalid byte sequence in UTF-8 (ArgumentError)- if ! s.valid_encoding?- s = s.encode("UTF-16be", invalid: :replace, replace: "?").encode('UTF-8')- end+ s = s.encode("UTF-16be", invalid: :replace, replace: "?").encode("UTF-8") if !s.valid_encoding?# Work around it for now:- s.gsub!(/\[http(s)?:\/\/(www\.)?/, '[')+ s.gsub!(%r{\[http(s)?://(www\.)?}, "[")# [QUOTE]...[/QUOTE]- s.gsub!(/\[quote\](.+?)\[\/quote\]/im) { "\n> #{$1}\n" }+ s.gsub!(%r{\[quote\](.+?)\[/quote\]}im) { "\n> #{$1}\n" }# Nested Quotes- s.gsub!(/(\[\/?QUOTE.*?\])/mi) { |q| "\n#{q}\n" }+ s.gsub!(%r{(\[/?QUOTE.*?\])}mi) { |q| "\n#{q}\n" }# [QUOTE="username, post: 28662, member: 1283"]s.gsub!(/\[quote="(\w+), post: (\d*), member: (\d*)"\]/i) do@@ -397,48 +410,52 @@ class ImportScripts::XenForo < ImportScripts::Baseend# [URL=...]...[/URL]- s.gsub!(/\[url="?(.+?)"?\](.+?)\[\/url\]/i) { "[#{$2}](#{$1})" }+ s.gsub!(%r{\[url="?(.+?)"?\](.+?)\[/url\]}i) { "[#{$2}](#{$1})" }# [URL]...[/URL]- s.gsub!(/\[url\](.+?)\[\/url\]/i) { " #{$1} " }+ s.gsub!(%r{\[url\](.+?)\[/url\]}i) { " #{$1} " }# [IMG]...[/IMG]- s.gsub!(/\[\/?img\]/i, "")+ s.gsub!(%r{\[/?img\]}i, "")# convert list tags to ul and list=1 tags to ol# (basically, we're only missing list=a here...)- s.gsub!(/\[list\](.*?)\[\/list\]/im, '[ul]\1[/ul]')- s.gsub!(/\[list=1\](.*?)\[\/list\]/im, '[ol]\1[/ol]')- s.gsub!(/\[list\](.*?)\[\/list:u\]/im, '[ul]\1[/ul]')- s.gsub!(/\[list=1\](.*?)\[\/list:o\]/im, '[ol]\1[/ol]')+ s.gsub!(%r{\[list\](.*?)\[/list\]}im, '[ul]\1[/ul]')+ s.gsub!(%r{\[list=1\](.*?)\[/list\]}im, '[ol]\1[/ol]')+ s.gsub!(%r{\[list\](.*?)\[/list:u\]}im, '[ul]\1[/ul]')+ s.gsub!(%r{\[list=1\](.*?)\[/list:o\]}im, '[ol]\1[/ol]')# convert *-tags to li-tags so bbcode-to-md can do its magic on phpBB's lists:- s.gsub!(/\[\*\]\n/, '')- s.gsub!(/\[\*\](.*?)\[\/\*:m\]/, '[li]\1[/li]')+ s.gsub!(/\[\*\]\n/, "")+ s.gsub!(%r{\[\*\](.*?)\[/\*:m\]}, '[li]\1[/li]')s.gsub!(/\[\*\](.*?)\n/, '[li]\1[/li]')- s.gsub!(/\[\*=1\]/, '')+ s.gsub!(/\[\*=1\]/, "")# [YOUTUBE]<id>[/YOUTUBE]- s.gsub!(/\[youtube\](.+?)\[\/youtube\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ s.gsub!(%r{\[youtube\](.+?)\[/youtube\]}i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }# [youtube=425,350]id[/youtube]- s.gsub!(/\[youtube="?(.+?)"?\](.+?)\[\/youtube\]/i) { "\nhttps://www.youtube.com/watch?v=#{$2}\n" }+ s.gsub!(%r{\[youtube="?(.+?)"?\](.+?)\[/youtube\]}i) do+ "\nhttps://www.youtube.com/watch?v=#{$2}\n"+ end# [MEDIA=youtube]id[/MEDIA]- s.gsub!(/\[MEDIA=youtube\](.+?)\[\/MEDIA\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ s.gsub!(%r{\[MEDIA=youtube\](.+?)\[/MEDIA\]}i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }# [ame="youtube_link"]title[/ame]- s.gsub!(/\[ame="?(.+?)"?\](.+?)\[\/ame\]/i) { "\n#{$1}\n" }+ s.gsub!(%r{\[ame="?(.+?)"?\](.+?)\[/ame\]}i) { "\n#{$1}\n" }# [VIDEO=youtube;<id>]...[/VIDEO]- s.gsub!(/\[video=youtube;([^\]]+)\].*?\[\/video\]/i) { "\nhttps://www.youtube.com/watch?v=#{$1}\n" }+ s.gsub!(%r{\[video=youtube;([^\]]+)\].*?\[/video\]}i) do+ "\nhttps://www.youtube.com/watch?v=#{$1}\n"+ end# [USER=706]@username[/USER]- s.gsub!(/\[user="?(.+?)"?\](.+?)\[\/user\]/i) { $2 }+ s.gsub!(%r{\[user="?(.+?)"?\](.+?)\[/user\]}i) { $2 }# Remove the color tags.gsub!(/\[color=[#a-z0-9]+\]/i, "")- s.gsub!(/\[\/color\]/i, "")+ s.gsub!(%r{\[/color\]}i, "")if Dir.exist? ATTACHMENT_DIRs = process_xf_attachments(:gallery, s, import_id)@@ -454,7 +471,8 @@ class ImportScripts::XenForo < ImportScripts::Base# not all attachments have an [ATTACH=] tag so we need to get the other ID's from the xf_attachment tableif xf_type == :attachment && import_id > 0- sql = "SELECT attachment_id FROM #{TABLE_PREFIX}attachment WHERE content_id=#{import_id} and content_type='post';"+ sql =+ "SELECT attachment_id FROM #{TABLE_PREFIX}attachment WHERE content_id=#{import_id} and content_type='post';"ids.merge(mysql_query(sql).to_a.map { |v| v["attachment_id"].to_i })end@@ -464,18 +482,22 @@ class ImportScripts::XenForo < ImportScripts::Baseresults = mysql_query(sql)if results.size < 1# Strip attachment- s.gsub!(get_xf_regexp(xf_type, id), '')+ s.gsub!(get_xf_regexp(xf_type, id), "")STDERR.puts "#{xf_type.capitalize} id #{id} not found in source database. Stripping."nextend- original_filename = results.first['filename']+ original_filename = results.first["filename"]result = results.first- upload = import_xf_attachment(result['data_id'], result['file_hash'], result['user_id'], original_filename)+ upload =+ import_xf_attachment(+ result["data_id"],+ result["file_hash"],+ result["user_id"],+ original_filename,+ )if upload && upload.present? && upload.persisted?html = @uploader.html_for_upload(upload, original_filename)- unless s.gsub!(get_xf_regexp(xf_type, id), html)- s = s + "\n\n#{html}\n\n"- end+ s = s + "\n\n#{html}\n\n" unless s.gsub!(get_xf_regexp(xf_type, id), html)elseSTDERR.puts "Could not process upload: #{original_filename}. Skipping attachment id #{id}"end@@ -503,7 +525,7 @@ class ImportScripts::XenForo < ImportScripts::Basewhen :galleryRegexp.new(/\[GALLERY=media,\s#{id ? id : '(\d+)'}\].+?\]/i)when :attachment- Regexp.new(/\[ATTACH(?>=\w+)?\]#{id ? id : '(\d+)'}\[\/ATTACH\]/i)+ Regexp.new(%r{\[ATTACH(?>=\w+)?\]#{id ? id : '(\d+)'}\[/ATTACH\]}i)endenddiff --git a/script/import_scripts/yahoogroup.rb b/script/import_scripts/yahoogroup.rbindex 93651e5d7f9..4c307f506e6 100644--- a/script/import_scripts/yahoogroup.rb+++ b/script/import_scripts/yahoogroup.rb@@ -1,7 +1,7 @@# frozen_string_literal: truerequire File.expand_path(File.dirname(__FILE__) + "/base.rb")-require 'mongo'+require "mongo"# Import YahooGroups data as exported into MongoDB by:# https://github.com/jonbartlett/yahoo-groups-export@@ -13,14 +13,13 @@ require 'mongo'# =endclass ImportScripts::YahooGroup < ImportScripts::Base-- MONGODB_HOST = '192.168.10.1:27017'- MONGODB_DB = 'syncro'+ MONGODB_HOST = "192.168.10.1:27017"+ MONGODB_DB = "syncro"def initializesuper- client = Mongo::Client.new([ MONGODB_HOST ], database: MONGODB_DB)+ client = Mongo::Client.new([MONGODB_HOST], database: MONGODB_DB)db = client.databaseMongo::Logger.logger.level = Logger::FATALputs "connected to db...."@@ -28,7 +27,6 @@ class ImportScripts::YahooGroup < ImportScripts::Base@collection = client[:posts]@user_profile_map = {}-enddef execute@@ -41,43 +39,42 @@ class ImportScripts::YahooGroup < ImportScripts::Baseenddef import_users-- puts '', "Importing users"+ puts "", "Importing users"# fetch distinct list of Yahoo "profile" names- profiles = @collection.aggregate(- [- { "$group": { "_id": { profile: "$ygData.profile" } } }- ]- )+ profiles = @collection.aggregate([{ "$group": { _id: { profile: "$ygData.profile" } } }])user_id = 0create_users(profiles.to_a) do |u|-user_id = user_id + 1# fetch last message for profile to pickup latest user info as this may have changed- user_info = @collection.find("ygData.profile": u["_id"]["profile"]).sort("ygData.msgId": -1).limit(1).to_a[0]+ user_info =+ @collection+ .find("ygData.profile": u["_id"]["profile"])+ .sort("ygData.msgId": -1)+ .limit(1)+ .to_a[+ 0+ ]# Store user_id to profile lookup@user_profile_map.store(user_info["ygData"]["profile"], user_id)puts "User created: #{user_info["ygData"]["profile"]}"- user =- {- id: user_id, # yahoo "userId" sequence appears to have changed mid forum life so generate this+ user = {+ id: user_id, # yahoo "userId" sequence appears to have changed mid forum life so generate thisusername: user_info["ygData"]["profile"],name: user_info["ygData"]["authorName"],email: user_info["ygData"]["from"], # mandatory- created_at: Time.now+ created_at: Time.now,}userendputs "#{user_id} users created"-enddef import_discussions@@ -86,21 +83,16 @@ class ImportScripts::YahooGroup < ImportScripts::Basetopics_count = 0posts_count = 0- topics = @collection.aggregate(- [- { "$group": { "_id": { topicId: "$ygData.topicId" } } }- ]- ).to_a+ topics = @collection.aggregate([{ "$group": { _id: { topicId: "$ygData.topicId" } } }]).to_a# for each distinct topicId foundtopics.each_with_index do |t, tidx|-# create "topic" post first.# fetch topic documenttopic_post = @collection.find("ygData.msgId": t["_id"]["topicId"]).to_a[0]next if topic_post.nil?- puts "Topic: #{tidx + 1} / #{topics.count()} (#{sprintf('%.2f', ((tidx + 1).to_f / topics.count().to_f) * 100)}%) Subject: #{topic_post["ygData"]["subject"]}"+ puts "Topic: #{tidx + 1} / #{topics.count()} (#{sprintf("%.2f", ((tidx + 1).to_f / topics.count().to_f) * 100)}%) Subject: #{topic_post["ygData"]["subject"]}"if topic_post["ygData"]["subject"].to_s.empty?topic_title = "No Subject"@@ -115,8 +107,10 @@ class ImportScripts::YahooGroup < ImportScripts::Basecreated_at: Time.at(topic_post["ygData"]["postDate"].to_i),cook_method: Post.cook_methods[:raw_html],title: topic_title,- category: ENV['CATEGORY_ID'],- custom_fields: { import_id: topic_post["ygData"]["msgId"] }+ category: ENV["CATEGORY_ID"],+ custom_fields: {+ import_id: topic_post["ygData"]["msgId"],+ },}topics_count += 1@@ -128,34 +122,31 @@ class ImportScripts::YahooGroup < ImportScripts::Baseposts = @collection.find("ygData.topicId": topic_post["ygData"]["topicId"]).to_aposts.each_with_index do |p, pidx|-# skip over first post as this is created by topic abovenext if p["ygData"]["msgId"] == topic_post["ygData"]["topicId"]puts " Post: #{pidx + 1} / #{posts.count()}"post = {- id: pidx + 1,- topic_id: parent_post[:topic_id],- user_id: @user_profile_map[p["ygData"]["profile"]] || -1,- raw: p["ygData"]["messageBody"],- created_at: Time.at(p["ygData"]["postDate"].to_i),- cook_method: Post.cook_methods[:raw_html],- custom_fields: { import_id: p["ygData"]["msgId"] }+ id: pidx + 1,+ topic_id: parent_post[:topic_id],+ user_id: @user_profile_map[p["ygData"]["profile"]] || -1,+ raw: p["ygData"]["messageBody"],+ created_at: Time.at(p["ygData"]["postDate"].to_i),+ cook_method: Post.cook_methods[:raw_html],+ custom_fields: {+ import_id: p["ygData"]["msgId"],+ },}child_post = create_post(post, post[:id])posts_count += 1-end-endputs "", "Imported #{topics_count} topics with #{topics_count + posts_count} posts."-end-endImportScripts::YahooGroup.new.performdiff --git a/script/import_scripts/zendesk.rb b/script/import_scripts/zendesk.rbindex a8e44f5ffd8..a8b5ef59ac5 100644--- a/script/import_scripts/zendesk.rb+++ b/script/import_scripts/zendesk.rb@@ -9,10 +9,10 @@# - posts.csv (posts in Zendesk are topics in Discourse)# - comments.csv (comments in Zendesk are posts in Discourse)-require 'csv'-require 'reverse_markdown'-require_relative 'base'-require_relative 'base/generic_database'+require "csv"+require "reverse_markdown"+require_relative "base"+require_relative "base/generic_database"# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/zendesk.rb DIRNAME@@ -45,7 +45,7 @@ class ImportScripts::Zendesk < ImportScripts::Basename: row[:name],description: row[:description],position: row[:position],- url: row[:htmlurl]+ url: row[:htmlurl],)end@@ -56,7 +56,7 @@ class ImportScripts::Zendesk < ImportScripts::Basename: row[:name],created_at: parse_datetime(row[:createdat]),last_seen_at: parse_datetime(row[:lastloginat]),- active: true+ active: true,)end@@ -69,7 +69,7 @@ class ImportScripts::Zendesk < ImportScripts::Baseclosed: row[:closed] == "TRUE",user_id: row[:authorid],created_at: parse_datetime(row[:createdat]),- url: row[:htmlurl]+ url: row[:htmlurl],)end@@ -80,7 +80,7 @@ class ImportScripts::Zendesk < ImportScripts::Basetopic_id: row[:postid],user_id: row[:authorid],created_at: parse_datetime(row[:createdat]),- url: row[:htmlurl]+ url: row[:htmlurl],)end@@ -99,14 +99,15 @@ class ImportScripts::Zendesk < ImportScripts::Basecreate_categories(rows) do |row|{- id: row['id'],- name: row['name'],- description: row['description'],- position: row['position'],- post_create_action: proc do |category|- url = remove_domain(row['url'])- Permalink.create(url: url, category_id: category.id) unless permalink_exists?(url)- end+ id: row["id"],+ name: row["name"],+ description: row["description"],+ position: row["position"],+ post_create_action:+ proc do |category|+ url = remove_domain(row["url"])+ Permalink.create(url: url, category_id: category.id) unless permalink_exists?(url)+ end,}endend@@ -118,22 +119,22 @@ class ImportScripts::Zendesk < ImportScripts::Basedef import_usersputs "", "creating users"total_count = @db.count_users- last_id = ''+ last_id = ""batches do |offset|rows, last_id = @db.fetch_users(last_id)break if rows.empty?- next if all_records_exist?(:users, rows.map { |row| row['id'] })+ next if all_records_exist?(:users, rows.map { |row| row["id"] })create_users(rows, total: total_count, offset: offset) do |row|{- id: row['id'],- email: row['email'],- name: row['name'],- created_at: row['created_at'],- last_seen_at: row['last_seen_at'],- active: row['active'] == 1+ id: row["id"],+ email: row["email"],+ name: row["name"],+ created_at: row["created_at"],+ last_seen_at: row["last_seen_at"],+ active: row["active"] == 1,}endend@@ -142,27 +143,28 @@ class ImportScripts::Zendesk < ImportScripts::Basedef import_topicsputs "", "creating topics"total_count = @db.count_topics- last_id = ''+ last_id = ""batches do |offset|rows, last_id = @db.fetch_topics(last_id)break if rows.empty?- next if all_records_exist?(:posts, rows.map { |row| import_topic_id(row['id']) })+ next if all_records_exist?(:posts, rows.map { |row| import_topic_id(row["id"]) })create_posts(rows, total: total_count, offset: offset) do |row|{- id: import_topic_id(row['id']),- title: row['title'].present? ? row['title'].strip[0...255] : "Topic title missing",- raw: normalize_raw(row['raw']),- category: category_id_from_imported_category_id(row['category_id']),- user_id: user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id,- created_at: row['created_at'],- closed: row['closed'] == 1,- post_create_action: proc do |post|- url = remove_domain(row['url'])- Permalink.create(url: url, topic_id: post.topic.id) unless permalink_exists?(url)- end+ id: import_topic_id(row["id"]),+ title: row["title"].present? ? row["title"].strip[0...255] : "Topic title missing",+ raw: normalize_raw(row["raw"]),+ category: category_id_from_imported_category_id(row["category_id"]),+ user_id: user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id,+ created_at: row["created_at"],+ closed: row["closed"] == 1,+ post_create_action:+ proc do |post|+ url = remove_domain(row["url"])+ Permalink.create(url: url, topic_id: post.topic.id) unless permalink_exists?(url)+ end,}endend@@ -181,34 +183,35 @@ class ImportScripts::Zendesk < ImportScripts::Baserows, last_row_id = @db.fetch_sorted_posts(last_row_id)break if rows.empty?- next if all_records_exist?(:posts, rows.map { |row| row['id'] })+ next if all_records_exist?(:posts, rows.map { |row| row["id"] })create_posts(rows, total: total_count, offset: offset) do |row|- topic = topic_lookup_from_imported_post_id(import_topic_id(row['topic_id']))+ topic = topic_lookup_from_imported_post_id(import_topic_id(row["topic_id"]))if topic.nil?- p "MISSING TOPIC #{row['topic_id']}"+ p "MISSING TOPIC #{row["topic_id"]}"p rownextend{- id: row['id'],- raw: normalize_raw(row['raw']),- user_id: user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id,+ id: row["id"],+ raw: normalize_raw(row["raw"]),+ user_id: user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id,topic_id: topic[:topic_id],- created_at: row['created_at'],- post_create_action: proc do |post|- url = remove_domain(row['url'])- Permalink.create(url: url, post_id: post.id) unless permalink_exists?(url)- end+ created_at: row["created_at"],+ post_create_action:+ proc do |post|+ url = remove_domain(row["url"])+ Permalink.create(url: url, post_id: post.id) unless permalink_exists?(url)+ end,}endendenddef normalize_raw(raw)- raw = raw.gsub('\n', '')+ raw = raw.gsub('\n', "")raw = ReverseMarkdown.convert(raw)rawend@@ -222,11 +225,13 @@ class ImportScripts::Zendesk < ImportScripts::Baseenddef csv_parse(table_name)- CSV.foreach(File.join(@path, "#{table_name}.csv"),- headers: true,- header_converters: :symbol,- skip_blanks: true,- encoding: 'bom|utf-8') { |row| yield row }+ CSV.foreach(+ File.join(@path, "#{table_name}.csv"),+ headers: true,+ header_converters: :symbol,+ skip_blanks: true,+ encoding: "bom|utf-8",+ ) { |row| yield row }endenddiff --git a/script/import_scripts/zendesk_api.rb b/script/import_scripts/zendesk_api.rbindex 9237a764423..d76ff1652dc 100644--- a/script/import_scripts/zendesk_api.rb+++ b/script/import_scripts/zendesk_api.rb@@ -4,10 +4,10 @@## This one uses their API.-require 'open-uri'-require 'reverse_markdown'-require_relative 'base'-require_relative 'base/generic_database'+require "open-uri"+require "reverse_markdown"+require_relative "base"+require_relative "base/generic_database"# Call it like this:# RAILS_ENV=production bundle exec ruby script/import_scripts/zendesk_api.rb SOURCE_URL DIRNAME AUTH_EMAIL AUTH_TOKEN@@ -23,7 +23,7 @@ class ImportScripts::ZendeskApi < ImportScripts::BaseNet::ProtocolError,Timeout::Error,OpenURI::HTTPError,- OpenSSL::SSL::SSLError+ OpenSSL::SSL::SSLError,]MAX_RETRIES = 5@@ -62,66 +62,72 @@ class ImportScripts::ZendeskApi < ImportScripts::Baseenddef fetch_categories- puts '', 'fetching categories...'+ puts "", "fetching categories..."- get_from_api('/api/v2/community/topics.json', 'topics', show_status: true) do |row|+ get_from_api("/api/v2/community/topics.json", "topics", show_status: true) do |row|@db.insert_category(- id: row['id'],- name: row['name'],- description: row['description'],- position: row['position'],- url: row['html_url']+ id: row["id"],+ name: row["name"],+ description: row["description"],+ position: row["position"],+ url: row["html_url"],)endenddef fetch_topics- puts '', 'fetching topics...'+ puts "", "fetching topics..."- get_from_api('/api/v2/community/posts.json', 'posts', show_status: true) do |row|- if row['vote_count'] > 0- like_user_ids = fetch_likes("/api/v2/community/posts/#{row['id']}/votes.json")+ get_from_api("/api/v2/community/posts.json", "posts", show_status: true) do |row|+ if row["vote_count"] > 0+ like_user_ids = fetch_likes("/api/v2/community/posts/#{row["id"]}/votes.json")end@db.insert_topic(- id: row['id'],- title: row['title'],- raw: row['details'],- category_id: row['topic_id'],- closed: row['closed'],- user_id: row['author_id'],- created_at: row['created_at'],- url: row['html_url'],- like_user_ids: like_user_ids+ id: row["id"],+ title: row["title"],+ raw: row["details"],+ category_id: row["topic_id"],+ closed: row["closed"],+ user_id: row["author_id"],+ created_at: row["created_at"],+ url: row["html_url"],+ like_user_ids: like_user_ids,)endenddef fetch_posts- puts '', 'fetching posts...'+ puts "", "fetching posts..."current_count = 0total_count = @db.count_topicsstart_time = Time.now- last_id = ''+ last_id = ""batches do |offset|rows, last_id = @db.fetch_topics(last_id)break if rows.empty?rows.each do |topic_row|- get_from_api("/api/v2/community/posts/#{topic_row['id']}/comments.json", 'comments') do |row|- if row['vote_count'] > 0- like_user_ids = fetch_likes("/api/v2/community/posts/#{topic_row['id']}/comments/#{row['id']}/votes.json")+ get_from_api(+ "/api/v2/community/posts/#{topic_row["id"]}/comments.json",+ "comments",+ ) do |row|+ if row["vote_count"] > 0+ like_user_ids =+ fetch_likes(+ "/api/v2/community/posts/#{topic_row["id"]}/comments/#{row["id"]}/votes.json",+ )end@db.insert_post(- id: row['id'],- raw: row['body'],- topic_id: topic_row['id'],- user_id: row['author_id'],- created_at: row['created_at'],- url: row['html_url'],- like_user_ids: like_user_ids+ id: row["id"],+ raw: row["body"],+ topic_id: topic_row["id"],+ user_id: row["author_id"],+ created_at: row["created_at"],+ url: row["html_url"],+ like_user_ids: like_user_ids,)end@@ -132,9 +138,9 @@ class ImportScripts::ZendeskApi < ImportScripts::Baseenddef fetch_users- puts '', 'fetching users...'+ puts "", "fetching users..."- user_ids = @db.execute_sql(<<~SQL).map { |row| row['user_id'] }+ user_ids = @db.execute_sql(<<~SQL).map { |row| row["user_id"] }SELECT user_id FROM topicUNIONSELECT user_id FROM post@@ -147,15 +153,18 @@ class ImportScripts::ZendeskApi < ImportScripts::Basestart_time = Time.nowwhile !user_ids.empty?- get_from_api("/api/v2/users/show_many.json?ids=#{user_ids.shift(50).join(',')}", 'users') do |row|+ get_from_api(+ "/api/v2/users/show_many.json?ids=#{user_ids.shift(50).join(",")}",+ "users",+ ) do |row|@db.insert_user(- id: row['id'],- email: row['email'],- name: row['name'],- created_at: row['created_at'],- last_seen_at: row['last_login_at'],- active: row['active'],- avatar_path: row['photo'].present? ? row['photo']['content_url'] : nil+ id: row["id"],+ email: row["email"],+ name: row["name"],+ created_at: row["created_at"],+ last_seen_at: row["last_login_at"],+ active: row["active"],+ avatar_path: row["photo"].present? ? row["photo"]["content_url"] : nil,)current_count += 1@@ -167,10 +176,8 @@ class ImportScripts::ZendeskApi < ImportScripts::Basedef fetch_likes(url)user_ids = []- get_from_api(url, 'votes') do |row|- if row['id'].present? && row['value'] == 1- user_ids << row['user_id']- end+ get_from_api(url, "votes") do |row|+ user_ids << row["user_id"] if row["id"].present? && row["value"] == 1enduser_ids@@ -182,14 +189,15 @@ class ImportScripts::ZendeskApi < ImportScripts::Basecreate_categories(rows) do |row|{- id: row['id'],- name: row['name'],- description: row['description'],- position: row['position'],- post_create_action: proc do |category|- url = remove_domain(row['url'])- Permalink.create(url: url, category_id: category.id) unless permalink_exists?(url)- end+ id: row["id"],+ name: row["name"],+ description: row["description"],+ position: row["position"],+ post_create_action:+ proc do |category|+ url = remove_domain(row["url"])+ Permalink.create(url: url, category_id: category.id) unless permalink_exists?(url)+ end,}endend@@ -197,27 +205,32 @@ class ImportScripts::ZendeskApi < ImportScripts::Basedef import_usersputs "", "creating users"total_count = @db.count_users- last_id = ''+ last_id = ""batches do |offset|rows, last_id = @db.fetch_users(last_id)break if rows.empty?- next if all_records_exist?(:users, rows.map { |row| row['id'] })+ next if all_records_exist?(:users, rows.map { |row| row["id"] })create_users(rows, total: total_count, offset: offset) do |row|{- id: row['id'],- email: row['email'],- name: row['name'],- created_at: row['created_at'],- last_seen_at: row['last_seen_at'],- active: row['active'] == 1,- post_create_action: proc do |user|- if row['avatar_path'].present?- UserAvatar.import_url_for_user(row['avatar_path'], user) rescue nil- end- end+ id: row["id"],+ email: row["email"],+ name: row["name"],+ created_at: row["created_at"],+ last_seen_at: row["last_seen_at"],+ active: row["active"] == 1,+ post_create_action:+ proc do |user|+ if row["avatar_path"].present?+ begin+ UserAvatar.import_url_for_user(row["avatar_path"], user)+ rescue StandardError+ nil+ end+ end+ end,}endend@@ -226,27 +239,32 @@ class ImportScripts::ZendeskApi < ImportScripts::Basedef import_topicsputs "", "creating topics"total_count = @db.count_topics- last_id = ''+ last_id = ""batches do |offset|rows, last_id = @db.fetch_topics(last_id)break if rows.empty?- next if all_records_exist?(:posts, rows.map { |row| import_topic_id(row['id']) })+ next if all_records_exist?(:posts, rows.map { |row| import_topic_id(row["id"]) })create_posts(rows, total: total_count, offset: offset) do |row|{- id: import_topic_id(row['id']),- title: row['title'].present? ? row['title'].strip[0...255] : "Topic title missing",- raw: normalize_raw(row['raw'], user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id),- category: category_id_from_imported_category_id(row['category_id']),- user_id: user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id,- created_at: row['created_at'],- closed: row['closed'] == 1,- post_create_action: proc do |post|- url = remove_domain(row['url'])- Permalink.create(url: url, topic_id: post.topic.id) unless permalink_exists?(url)- end+ id: import_topic_id(row["id"]),+ title: row["title"].present? ? row["title"].strip[0...255] : "Topic title missing",+ raw:+ normalize_raw(+ row["raw"],+ user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id,+ ),+ category: category_id_from_imported_category_id(row["category_id"]),+ user_id: user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id,+ created_at: row["created_at"],+ closed: row["closed"] == 1,+ post_create_action:+ proc do |post|+ url = remove_domain(row["url"])+ Permalink.create(url: url, topic_id: post.topic.id) unless permalink_exists?(url)+ end,}endend@@ -266,24 +284,29 @@ class ImportScripts::ZendeskApi < ImportScripts::Basebreak if rows.empty?create_posts(rows, total: total_count, offset: offset) do |row|- topic = topic_lookup_from_imported_post_id(import_topic_id(row['topic_id']))+ topic = topic_lookup_from_imported_post_id(import_topic_id(row["topic_id"]))if topic.nil?- p "MISSING TOPIC #{row['topic_id']}"+ p "MISSING TOPIC #{row["topic_id"]}"p rownextend{- id: row['id'],- raw: normalize_raw(row['raw'], user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id),- user_id: user_id_from_imported_user_id(row['user_id']) || Discourse.system_user.id,+ id: row["id"],+ raw:+ normalize_raw(+ row["raw"],+ user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id,+ ),+ user_id: user_id_from_imported_user_id(row["user_id"]) || Discourse.system_user.id,topic_id: topic[:topic_id],- created_at: row['created_at'],- post_create_action: proc do |post|- url = remove_domain(row['url'])- Permalink.create(url: url, post_id: post.id) unless permalink_exists?(url)- end+ created_at: row["created_at"],+ post_create_action:+ proc do |post|+ url = remove_domain(row["url"])+ Permalink.create(url: url, post_id: post.id) unless permalink_exists?(url)+ end,}endend@@ -301,9 +324,9 @@ class ImportScripts::ZendeskApi < ImportScripts::Basebreak if rows.empty?rows.each do |row|- import_id = row['topic_id'] ? import_topic_id(row['topic_id']) : row['post_id']+ import_id = row["topic_id"] ? import_topic_id(row["topic_id"]) : row["post_id"]post = Post.find_by(id: post_id_from_imported_post_id(import_id)) if import_id- user = User.find_by(id: user_id_from_imported_user_id(row['user_id']))+ user = User.find_by(id: user_id_from_imported_user_id(row["user_id"]))if post && userbegin@@ -312,7 +335,7 @@ class ImportScripts::ZendeskApi < ImportScripts::Baseputs "error acting on post #{e}"endelse- puts "Skipping Like from #{row['user_id']} on topic #{row['topic_id']} / post #{row['post_id']}"+ puts "Skipping Like from #{row["user_id"]} on topic #{row["topic_id"]} / post #{row["post_id"]}"endcurrent_count += 1@@ -322,23 +345,23 @@ class ImportScripts::ZendeskApi < ImportScripts::Baseenddef normalize_raw(raw, user_id)- raw = raw.gsub('\n', '')+ raw = raw.gsub('\n', "")raw = ReverseMarkdown.convert(raw)# Process images, after the ReverseMarkdown they look like# - raw.gsub!(/!\[\]\((https:\/\/#{SUBDOMAIN}\.zendesk\.com\/hc\/user_images\/([^).]+\.[^)]+))\)/i) do+ raw.gsub!(%r{!\[\]\((https://#{SUBDOMAIN}\.zendesk\.com/hc/user_images/([^).]+\.[^)]+))\)}i) doimage_url = $1filename = $2attempts = 0begin- URI.parse(image_url).open do |image|- # IMAGE_DOWNLOAD_PATH is whatever image, it will be replaced with the downloaded image- File.open(IMAGE_DOWNLOAD_PATH, "wb") do |file|- file.write(image.read)+ URI+ .parse(image_url)+ .open do |image|+ # IMAGE_DOWNLOAD_PATH is whatever image, it will be replaced with the downloaded image+ File.open(IMAGE_DOWNLOAD_PATH, "wb") { |file| file.write(image.read) }end- endrescue *HTTP_ERRORS => eif attempts < MAX_RETRIESattempts += 1@@ -374,23 +397,25 @@ class ImportScripts::ZendeskApi < ImportScripts::Baseenddef connection- @_connection ||= begin- connect_uri = URI.parse(@source_url)+ @_connection ||=+ begin+ connect_uri = URI.parse(@source_url)- http = Net::HTTP.new(connect_uri.host, connect_uri.port)- http.open_timeout = 30- http.read_timeout = 30- http.use_ssl = connect_uri.scheme == "https"+ http = Net::HTTP.new(connect_uri.host, connect_uri.port)+ http.open_timeout = 30+ http.read_timeout = 30+ http.use_ssl = connect_uri.scheme == "https"- http- end+ http+ endenddef authorization- @_authorization ||= begin- auth_str = "#{@auth_email}/token:#{@auth_token}"- "Basic #{Base64.strict_encode64(auth_str)}"- end+ @_authorization ||=+ begin+ auth_str = "#{@auth_email}/token:#{@auth_token}"+ "Basic #{Base64.strict_encode64(auth_str)}"+ endenddef get_from_api(path, array_name, show_status: false)@@ -399,8 +424,8 @@ class ImportScripts::ZendeskApi < ImportScripts::Basewhile urlget = Net::HTTP::Get.new(url)- get['User-Agent'] = 'Discourse Zendesk Importer'- get['Authorization'] = authorization+ get["User-Agent"] = "Discourse Zendesk Importer"+ get["Authorization"] = authorizationretry_count = 0@@ -420,26 +445,27 @@ class ImportScripts::ZendeskApi < ImportScripts::Basejson = JSON.parse(response.body)- json[array_name].each do |row|- yield row- end+ json[array_name].each { |row| yield row }- url = json['next_page']+ url = json["next_page"]if show_status- if json['page'] && json['page_count']- print_status(json['page'], json['page_count'], start_time)+ if json["page"] && json["page_count"]+ print_status(json["page"], json["page_count"], start_time)else- print '.'+ print "."endendendend-endunless ARGV.length == 4 && Dir.exist?(ARGV[1])- puts "", "Usage:", "", "bundle exec ruby script/import_scripts/zendesk_api.rb SOURCE_URL DIRNAME AUTH_EMAIL AUTH_TOKEN", ""+ puts "",+ "Usage:",+ "",+ "bundle exec ruby script/import_scripts/zendesk_api.rb SOURCE_URL DIRNAME AUTH_EMAIL AUTH_TOKEN",+ ""exit 1enddiff --git a/script/import_scripts/zoho.rb b/script/import_scripts/zoho.rbindex e354b79f8dc..b05debeb7e2 100644--- a/script/import_scripts/zoho.rb+++ b/script/import_scripts/zoho.rb@@ -21,14 +21,13 @@# full names instead of usernames. This may cause duplicate users with slightly different# usernames to be created.-require 'csv'+require "csv"require File.expand_path(File.dirname(__FILE__) + "/base.rb")require File.expand_path(File.dirname(__FILE__) + "/base/csv_helper.rb")# Call it like this:# bundle exec ruby script/import_scripts/zoho.rb <path-to-csv-files>class ImportScripts::Zoho < ImportScripts::Base-include ImportScripts::CsvHelperBATCH_SIZE = 1000@@ -50,19 +49,14 @@ class ImportScripts::Zoho < ImportScripts::Baseenddef cleanup_zoho_username(s)- s.strip.gsub(/[^A-Za-z0-9_\.\-]/, '')+ s.strip.gsub(/[^A-Za-z0-9_\.\-]/, "")enddef import_usersputs "", "Importing users"- create_users(CSV.parse(File.read(File.join(@path, 'users.csv')))) do |u|+ create_users(CSV.parse(File.read(File.join(@path, "users.csv")))) do |u|username = cleanup_zoho_username(u[0])- {- id: username,- username: username,- email: u[1],- created_at: Time.zone.now- }+ { id: username, username: username, email: u[1], created_at: Time.zone.now }endend@@ -83,9 +77,7 @@ class ImportScripts::Zoho < ImportScripts::Basecsv_parse(File.join(@path, "posts.csv")) do |row|@all_posts << row.dup- if @categories[row.forum_name].nil?- @categories[row.forum_name] = []- end+ @categories[row.forum_name] = [] if @categories[row.forum_name].nil?unless @categories[row.forum_name].include?(row.category_name)@categories[row.forum_name] << row.category_name@@ -105,56 +97,61 @@ class ImportScripts::Zoho < ImportScripts::Baseputs "", "Creating topics and posts"- created, skipped = create_posts(@all_posts, total: @all_posts.size) do |row|- @current_row = row-- # fetch user- username = cleanup_zoho_username(row.author)-- next if username.blank? # no author for this post, so skip-- user_id = user_id_from_imported_user_id(username)-- if user_id.nil?- # user CSV file didn't have a user with this username. create it now with an invalid email address.- u = create_user(- { id: username,- username: username,- email: "#{username}@example.com",- created_at: Time.zone.parse(row.posted_time) },- username- )- user_id = u.id- end+ created, skipped =+ create_posts(@all_posts, total: @all_posts.size) do |row|+ @current_row = row++ # fetch user+ username = cleanup_zoho_username(row.author)++ next if username.blank? # no author for this post, so skip++ user_id = user_id_from_imported_user_id(username)++ if user_id.nil?+ # user CSV file didn't have a user with this username. create it now with an invalid email address.+ u =+ create_user(+ {+ id: username,+ username: username,+ email: "#{username}@example.com",+ created_at: Time.zone.parse(row.posted_time),+ },+ username,+ )+ user_id = u.id+ end- if @topic_mapping[row.permalink].nil?- category_id = nil- if row.category_name != "Uncategorized" && row.category_name != "Uncategorised"- category_id = category_id_from_imported_category_id("#{row.forum_name}:#{row.category_name}")+ if @topic_mapping[row.permalink].nil?+ category_id = nil+ if row.category_name != "Uncategorized" && row.category_name != "Uncategorised"+ category_id =+ category_id_from_imported_category_id("#{row.forum_name}:#{row.category_name}")+ else+ category_id = category_id_from_imported_category_id(row.forum_name)+ end++ # create topic+ {+ id: import_post_id(row),+ user_id: user_id,+ category: category_id,+ title: CGI.unescapeHTML(row.topic_title),+ raw: cleanup_post(row.content),+ created_at: Time.zone.parse(row.posted_time),+ }+ # created_post callback will be calledelse- category_id = category_id_from_imported_category_id(row.forum_name)+ {+ id: import_post_id(row),+ user_id: user_id,+ raw: cleanup_post(row.content),+ created_at: Time.zone.parse(row.posted_time),+ topic_id: @topic_mapping[row.permalink],+ }end-- # create topic- {- id: import_post_id(row),- user_id: user_id,- category: category_id,- title: CGI.unescapeHTML(row.topic_title),- raw: cleanup_post(row.content),- created_at: Time.zone.parse(row.posted_time)- }- # created_post callback will be called- else- {- id: import_post_id(row),- user_id: user_id,- raw: cleanup_post(row.content),- created_at: Time.zone.parse(row.posted_time),- topic_id: @topic_mapping[row.permalink]- }end- endputs ""puts "Created: #{created}"@@ -176,31 +173,30 @@ class ImportScripts::Zoho < ImportScripts::BaseSTYLE_ATTR = /(\s)*style="(.)*"/def cleanup_post(raw)-# Check if Zoho's most common form of a code block is present.# If so, don't clean up the post as much because we can't tell which markup# is inside the code block. These posts will look worse than others.has_code_block = !!(raw =~ ZOHO_CODE_BLOCK_START)- x = raw.gsub(STYLE_ATTR, '')+ x = raw.gsub(STYLE_ATTR, "")if has_code_block# We have to assume all lists in this post are meant to be code blocks# to make it somewhat readable.x.gsub!(/( )*<ol>(\s)*/, "")- x.gsub!(/( )*<\/ol>/, "")- x.gsub!('<li>', '')- x.gsub!('</li>', '')+ x.gsub!(%r{( )*</ol>}, "")+ x.gsub!("<li>", "")+ x.gsub!("</li>", "")else# No code block (probably...) so clean up more aggressively.x.gsub!("\n", " ")- x.gsub!('<div>', "\n\n")- x.gsub('</div>', ' ')+ x.gsub!("<div>", "\n\n")+ x.gsub("</div>", " ")x.gsub!("<br />", "\n")- x.gsub!('<span>', '')- x.gsub!('</span>', '')- x.gsub!(/<font ([^>]*)>/, '')- x.gsub!('</font>', '')+ x.gsub!("<span>", "")+ x.gsub!("</span>", "")+ x.gsub!(/<font ([^>]*)>/, "")+ x.gsub!("</font>", "")endx.gsub!(TOO_MANY_LINE_BREAKS, "\n\n")@@ -213,13 +209,10 @@ class ImportScripts::Zoho < ImportScripts::Base# The posted_time seems to be the same for all posts in a topic, so we can't use that.Digest::SHA1.hexdigest "#{row.permalink}:#{row.content}"end-endunless ARGV[0] && Dir.exist?(ARGV[0])- if ARGV[0] && !Dir.exist?(ARGV[0])- puts "", "ERROR! Dir #{ARGV[0]} not found.", ""- end+ puts "", "ERROR! Dir #{ARGV[0]} not found.", "" if ARGV[0] && !Dir.exist?(ARGV[0])puts "", "Usage:", "", " bundle exec ruby script/import_scripts/zoho.rb DIRNAME", ""exit 1diff --git a/script/measure.rb b/script/measure.rbindex 9711206ae62..1dc391735be 100644--- a/script/measure.rb+++ b/script/measure.rb@@ -1,38 +1,36 @@# frozen_string_literal: true# using this script to try figure out why Ruby 2 is slower than 1.9-require 'flamegraph'+require "flamegraph"-Flamegraph.generate('test.html', fidelity: 2) do+Flamegraph.generate("test.html", fidelity: 2) dorequire File.expand_path("../../config/environment", __FILE__)endexit-require 'memory_profiler'+require "memory_profiler"-result = MemoryProfiler.report do- require File.expand_path("../../config/environment", __FILE__)-end+result = MemoryProfiler.report { require File.expand_path("../../config/environment", __FILE__) }result.pretty_printexit-require 'benchmark'+require "benchmark"def profile_allocations(name)GC.disableinitial_size = ObjectSpace.count_objectsyieldchanges = ObjectSpace.count_objects- changes.each do |k, _|- changes[k] -= initial_size[k]- end+ changes.each { |k, _| changes[k] -= initial_size[k] }puts "#{name} changes"- changes.sort { |a, b| b[1] <=> a[1] }.each do |a, b|- next if b <= 0- # 1 extra hash for tracking- puts "#{a} #{a == :T_HASH ? b - 1 : b}"- end+ changes+ .sort { |a, b| b[1] <=> a[1] }+ .each do |a, b|+ next if b <= 0+ # 1 extra hash for tracking+ puts "#{a} #{a == :T_HASH ? b - 1 : b}"+ endGC.enableend@@ -47,9 +45,7 @@ def profile(name, &block)ObjectSpace.trace_object_allocations doblock.call- ObjectSpace.each_object do |o|- objs << o- end+ ObjectSpace.each_object { |o| objs << o }objs.each do |o|g = ObjectSpace.allocation_generation(o)@@ -63,9 +59,10 @@ def profile(name, &block)endend- items.group_by { |x| x }.sort { |a, b| b[1].length <=> a[1].length }.each do |row, group|- puts "#{row} x #{group.length}"- end+ items+ .group_by { |x| x }+ .sort { |a, b| b[1].length <=> a[1].length }+ .each { |row, group| puts "#{row} x #{group.length}" }GC.enableprofile_allocations(name, &block)diff --git a/script/memstats.rb b/script/memstats.rbindex 998d8d525f7..4ca1f531dc7 100755--- a/script/memstats.rb+++ b/script/memstats.rb@@ -28,7 +28,7 @@#------------------------------------------------------------------------------class Mapping- FIELDS = %w[ size rss shared_clean shared_dirty private_clean private_dirty swap pss ]+ FIELDS = %w[size rss shared_clean shared_dirty private_clean private_dirty swap pss]attr_reader :address_startattr_reader :address_endattr_reader :perms@@ -48,15 +48,10 @@ class Mappingattr_accessor :pssdef initialize(lines)-- FIELDS.each do |field|- self.public_send("#{field}=", 0)- end+ FIELDS.each { |field| self.public_send("#{field}=", 0) }parse_first_line(lines.shift)- lines.each do |l|- parse_field_line(l)- end+ lines.each { |l| parse_field_line(l) }enddef parse_first_line(line)@@ -71,7 +66,7 @@ class Mappingdef parse_field_line(line)parts = line.strip.split- field = parts[0].downcase.sub(':', '')+ field = parts[0].downcase.sub(":", "")if respond_to? "#{field}="value = Float(parts[1]).to_iself.public_send("#{field}=", value)@@ -82,26 +77,21 @@ enddef consume_mapping(map_lines, totals)m = Mapping.new(map_lines)- Mapping::FIELDS.each do |field|- totals[field] += m.public_send(field)- end+ Mapping::FIELDS.each { |field| totals[field] += m.public_send(field) }menddef create_memstats_not_available(totals)- Mapping::FIELDS.each do |field|- totals[field] += Float::NAN- end+ Mapping::FIELDS.each { |field| totals[field] += Float::NAN }end-abort 'usage: memstats [pid]' unless ARGV.first+abort "usage: memstats [pid]" unless ARGV.firstpid = ARGV.shift.to_itotals = Hash.new(0)mappings = []beginFile.open("/proc/#{pid}/smaps") do |smaps|-map_lines = []loop do@@ -111,9 +101,7 @@ beginwhen /\w+:\s+/map_lines << linewhen /[0-9a-f]+:[0-9a-f]+\s+/- if map_lines.size > 0 then- mappings << consume_mapping(map_lines, totals)- end+ mappings << consume_mapping(map_lines, totals) if map_lines.size > 0map_lines.clearmap_lines << lineelse@@ -121,7 +109,7 @@ beginendendend-rescue+rescue StandardErrorcreate_memstats_not_available(totals)end@@ -132,23 +120,19 @@ enddef get_commandline(pid)commandline = File.read("/proc/#{pid}/cmdline").split("\0")- if commandline.first =~ /java$/ then+ if commandline.first =~ /java$/loop { break if commandline.shift == "-jar" }return "[java] #{commandline.shift}"end- commandline.join(' ')+ commandline.join(" ")end-if ARGV.include? '--yaml'- require 'yaml'- puts Hash[*totals.map do |k, v|- [k + '_kb', v]- end.flatten].to_yaml+if ARGV.include? "--yaml"+ require "yaml"+ puts Hash[*totals.map do |k, v| [k + "_kb", v] end.flatten].to_yamlelseputs "#{"Process:".ljust(20)} #{pid}"puts "#{"Command Line:".ljust(20)} #{get_commandline(pid)}"puts "Memory Summary:"- totals.keys.sort.each do |k|- puts " #{k.ljust(20)} #{format_number(totals[k]).rjust(12)} kB"- end+ totals.keys.sort.each { |k| puts " #{k.ljust(20)} #{format_number(totals[k]).rjust(12)} kB" }enddiff --git a/script/micro_bench.rb b/script/micro_bench.rbindex 51ea6c89128..7ba5dceffe8 100644--- a/script/micro_bench.rb+++ b/script/micro_bench.rb@@ -1,32 +1,20 @@# frozen_string_literal: true-require 'benchmark/ips'+require "benchmark/ips"require File.expand_path("../../config/environment", __FILE__)conn = ActiveRecord::Base.connection.raw_connectionBenchmark.ips do |b|- b.report("simple") do- User.first.name- end+ b.report("simple") { User.first.name }- b.report("simple with select") do- User.select("name").first.name- end+ b.report("simple with select") { User.select("name").first.name }- b.report("pluck with first") do- User.pluck(:name).first- end+ b.report("pluck with first") { User.pluck(:name).first }- b.report("pluck with limit") do- User.limit(1).pluck(:name).first- end+ b.report("pluck with limit") { User.limit(1).pluck(:name).first }- b.report("pluck with pluck_first") do- User.pluck_first(:name)- end+ b.report("pluck with pluck_first") { User.pluck_first(:name) }- b.report("raw") do- conn.exec("SELECT name FROM users LIMIT 1").getvalue(0, 0)- end+ b.report("raw") { conn.exec("SELECT name FROM users LIMIT 1").getvalue(0, 0) }enddiff --git a/script/profile_db_generator.rb b/script/profile_db_generator.rbindex c49ef6f6278..8222c008096 100644--- a/script/profile_db_generator.rb+++ b/script/profile_db_generator.rb@@ -5,7 +5,7 @@# we want our script to generate a consistent output, to do so# we monkey patch array sample so it always uses the same rngclass Array- RNG = Random.new(1098109928029800)+ RNG = Random.new(1_098_109_928_029_800)def sampleself[RNG.rand(size)]@@ -16,9 +16,7 @@ enddef unbundled_require(gem)if defined?(::Bundler)spec_path = Dir.glob("#{Gem.dir}/specifications/#{gem}-*.gemspec").last- if spec_path.nil?- raise LoadError- end+ raise LoadError if spec_path.nil?spec = Gem::Specification.load spec_pathspec.activate@@ -30,13 +28,14 @@ def unbundled_require(gem)enddef sentence- @gabbler ||= Gabbler.new.tap do |gabbler|- story = File.read(File.dirname(__FILE__) + "/alice.txt")- gabbler.learn(story)- end+ @gabbler ||=+ Gabbler.new.tap do |gabbler|+ story = File.read(File.dirname(__FILE__) + "/alice.txt")+ gabbler.learn(story)+ endsentence = +""- until sentence.length > 800 do+ until sentence.length > 800sentence << @gabbler.sentencesentence << "\n"end@@ -74,13 +73,13 @@ if User.count > 2exitend-require 'optparse'+require "optparse"begin- unbundled_require 'gabbler'+ unbundled_require "gabbler"rescue LoadErrorputs "installing gabbler gem"puts `gem install gabbler`- unbundled_require 'gabbler'+ unbundled_require "gabbler"endnumber_of_users = 100@@ -98,41 +97,61 @@ users = User.human_users.allputsputs "Creating 10 categories"-categories = 10.times.map do |i|- putc "."- Category.create(name: "category#{i}", text_color: "ffffff", color: "000000", user: admin_user)-end+categories =+ 10.times.map do |i|+ putc "."+ Category.create(name: "category#{i}", text_color: "ffffff", color: "000000", user: admin_user)+ endputsputs "Creating 100 topics"-topic_ids = 100.times.map do- post = PostCreator.create(admin_user, raw: sentence, title: sentence[0..50].strip, category: categories.sample.id, skip_validations: true)- putc "."- post.topic_id-end+topic_ids =+ 100.times.map do+ post =+ PostCreator.create(+ admin_user,+ raw: sentence,+ title: sentence[0..50].strip,+ category: categories.sample.id,+ skip_validations: true,+ )+ putc "."+ post.topic_id+ endputsputs "Creating 2000 replies"2000.times doputc "."- PostCreator.create(users.sample, raw: sentence, topic_id: topic_ids.sample, skip_validations: true)+ PostCreator.create(+ users.sample,+ raw: sentence,+ topic_id: topic_ids.sample,+ skip_validations: true,+ )endputsputs "creating perf test topic"-first_post = PostCreator.create(- users.sample,- raw: sentence,- title: "I am a topic used for perf tests",- category: categories.sample.id,- skip_validations: true-)+first_post =+ PostCreator.create(+ users.sample,+ raw: sentence,+ title: "I am a topic used for perf tests",+ category: categories.sample.id,+ skip_validations: true,+ )putsputs "Creating 100 replies for perf test topic"100.times doputc "."- PostCreator.create(users.sample, raw: sentence, topic_id: first_post.topic_id, skip_validations: true)+ PostCreator.create(+ users.sample,+ raw: sentence,+ topic_id: first_post.topic_id,+ skip_validations: true,+ )end# no sidekiq so update some stuffdiff --git a/script/redis_memory.rb b/script/redis_memory.rbindex 442463bc415..b191112cefb 100644--- a/script/redis_memory.rb+++ b/script/redis_memory.rb@@ -24,7 +24,10 @@ stats = {}endputs "Top 100 keys"-stats.sort { |a, b| b[1][0] <=> a[1][0] }.first(50).each do |k, (len, type, elems)|- elems = " [#{elems}]" if elems- puts "#{k} #{type} #{len}#{elems}"-end+stats+ .sort { |a, b| b[1][0] <=> a[1][0] }+ .first(50)+ .each do |k, (len, type, elems)|+ elems = " [#{elems}]" if elems+ puts "#{k} #{type} #{len}#{elems}"+ enddiff --git a/script/require_profiler.rb b/script/require_profiler.rbindex a0135d08b75..b8f3437efb6 100644--- a/script/require_profiler.rb+++ b/script/require_profiler.rb@@ -5,12 +5,11 @@# This is a rudimentary script that allows us to# quickly determine if any gems are slowing down startup-require 'benchmark'-require 'fileutils'+require "benchmark"+require "fileutils"module RequireProfilerclass << self-attr_accessor :statsdef profiling_enabled?@@ -25,10 +24,19 @@ module RequireProfilerdef start(tmp_options = {})@start_time = Time.now- [ ::Kernel, (class << ::Kernel; self; end) ].each do |klass|+ [+ ::Kernel,+ (+ class << ::Kernel+ self+ end+ ),+ ].each do |klass|klass.class_eval dodef require_with_profiling(path, *args)- RequireProfiler.measure(path, caller, :require) { require_without_profiling(path, *args) }+ RequireProfiler.measure(path, caller, :require) do+ require_without_profiling(path, *args)+ endendalias require_without_profiling requirealias require require_with_profiling@@ -47,7 +55,14 @@ module RequireProfilerdef stop@stop_time = Time.now- [ ::Kernel, (class << ::Kernel; self; end) ].each do |klass|+ [+ ::Kernel,+ (+ class << ::Kernel+ self+ end+ ),+ ].each do |klass|klass.class_eval doalias require require_without_profilingalias load load_without_profiling@@ -63,21 +78,20 @@ module RequireProfiler@stack ||= []self.stats ||= {}- stat = self.stats.fetch(path) { |key| self.stats[key] = { calls: 0, time: 0, parent_time: 0 } }+ stat =+ self.stats.fetch(path) { |key| self.stats[key] = { calls: 0, time: 0, parent_time: 0 } }@stack << stattime = Time.nowbegin- output = yield # do the require or load here+ output = yield # do the require or load hereensuredelta = Time.now - timestat[:time] += deltastat[:calls] += 1@stack.pop- @stack.each do |frame|- frame[:parent_time] += delta- end+ @stack.each { |frame| frame[:parent_time] += delta }endoutput@@ -102,7 +116,6 @@ module RequireProfilerputs "GC duration: #{gc_duration_finish}"puts "GC impact: #{gc_duration_finish - gc_duration_start}"end-endend@@ -122,8 +135,9 @@ RequireProfiler.profile doendend-sorted = RequireProfiler.stats.to_a.sort { |a, b| b[1][:time] - b[1][:parent_time] <=> a[1][:time] - a[1][:parent_time] }+sorted =+ RequireProfiler.stats.to_a.sort do |a, b|+ b[1][:time] - b[1][:parent_time] <=> a[1][:time] - a[1][:parent_time]+ end-sorted[0..120].each do |k, v|- puts "#{k} : time #{v[:time] - v[:parent_time]} "-end+sorted[0..120].each { |k, v| puts "#{k} : time #{v[:time] - v[:parent_time]} " }diff --git a/script/spawn_backup_restore.rb b/script/spawn_backup_restore.rbindex 4af4f667c63..7ab3721d5db 100644--- a/script/spawn_backup_restore.rb+++ b/script/spawn_backup_restore.rb@@ -15,11 +15,8 @@ fork doBackupRestore::Restorer.new(user_id: user_id,filename: opts[:filename],- factory: BackupRestore::Factory.new(- user_id: user_id,- client_id: opts[:client_id]- ),- disable_emails: opts.fetch(:disable_emails, true)+ factory: BackupRestore::Factory.new(user_id: user_id, client_id: opts[:client_id]),+ disable_emails: opts.fetch(:disable_emails, true),).runenddiff --git a/script/test_email_settings.rb b/script/test_email_settings.rbindex 9ef0fc8b93d..c4c9272e432 100755--- a/script/test_email_settings.rb+++ b/script/test_email_settings.rb@@ -1,16 +1,16 @@#!/usr/bin/env ruby# frozen_string_literal: true-require 'action_mailer'+require "action_mailer"# Make this your email address. Poor example.com gets SO MUCH MAILYOUR_EMAIL = "[email protected]"# Change these to be the same settings as your Discourse environment-DISCOURSE_SMTP_ADDRESS = "smtp.example.com" # (mandatory)-@DISCOURSE_SMTP_PORT = 587 # (optional)-@DISCOURSE_SMTP_USER_NAME = "username" # (optional)-@DISCOURSE_SMTP_PASSWORD = "blah" # (optional)+DISCOURSE_SMTP_ADDRESS = "smtp.example.com" # (mandatory)+@DISCOURSE_SMTP_PORT = 587 # (optional)+@DISCOURSE_SMTP_USER_NAME = "username" # (optional)+@DISCOURSE_SMTP_PASSWORD = "blah" # (optional)#@DISCOURSE_SMTP_OPENSSL_VERIFY_MODE = "none" # (optional) none|peer|client_once|fail_if_no_peer_cert# Note that DISCOURSE_SMTP_ADDRESS should NOT BE ALLOWED to relay mail to@@ -24,16 +24,18 @@ $delivery_options = {password: @DISCOURSE_SMTP_PASSWORD || nil,address: DISCOURSE_SMTP_ADDRESS,port: @DISCOURSE_SMTP_PORT || nil,- openssl_verify_mode: @DISCOURSE_SMTP_OPENSSL_VERIFY_MODE || nil+ openssl_verify_mode: @DISCOURSE_SMTP_OPENSSL_VERIFY_MODE || nil,}class EmailTestMailer < ActionMailer::Basedef email_test(mailfrom, mailto)- mail(from: mailfrom,- to: mailto,- body: "Testing email settings",- subject: "Discourse email settings test",- delivery_method_options: $delivery_options)+ mail(+ from: mailfrom,+ to: mailto,+ body: "Testing email settings",+ subject: "Discourse email settings test",+ delivery_method_options: $delivery_options,+ )endenddiff --git a/script/test_mem.rb b/script/test_mem.rbindex dd64ea2de37..284e99993f3 100644--- a/script/test_mem.rb+++ b/script/test_mem.rb@@ -1,7 +1,7 @@# frozen_string_literal: truestart = Time.now-require 'objspace'+require "objspace"require File.expand_path("../../config/environment", __FILE__)# preload stuff@@ -9,11 +9,19 @@ I18n.t(:posts)# load up all models and schema(ActiveRecord::Base.connection.tables - %w[schema_migrations]).each do |table|- table.classify.constantize.first rescue nil+ begin+ table.classify.constantize.first+ rescue StandardError+ nil+ endend# router warm up-Rails.application.routes.recognize_path('abc') rescue nil+begin+ Rails.application.routes.recognize_path("abc")+rescue StandardError+ nil+endputs "Ruby version #{RUBY_VERSION} p#{RUBY_PATCHLEVEL}"@@ -23,8 +31,11 @@ GC.startputs "RSS: #{`ps -o rss -p #{$$}`.chomp.split("\n").last.to_i} KB"-s = ObjectSpace.each_object(String).map do |o|- ObjectSpace.memsize_of(o) + 40 # rvalue size on x64-end+s =+ ObjectSpace+ .each_object(String)+ .map do |o|+ ObjectSpace.memsize_of(o) + 40 # rvalue size on x64+ endputs "Total strings: #{s.count} space used: #{s.sum} bytes"diff --git a/script/test_memory_leak.rb b/script/test_memory_leak.rbindex 3ecf01c39e4..a426d367841 100644--- a/script/test_memory_leak.rb+++ b/script/test_memory_leak.rb@@ -5,25 +5,21 @@# this performs a trivial operation walking all multisites and grabbing first topic / localizing# the expectation is that RSS will remain static no matter how many iterations run-if ENV['RAILS_ENV'] != "production"- exec "RAILS_ENV=production ruby #{__FILE__}"-end+exec "RAILS_ENV=production ruby #{__FILE__}" if ENV["RAILS_ENV"] != "production"-if !ENV['LD_PRELOAD']- exec "LD_PRELOAD=/usr/lib/libjemalloc.so.1 ruby #{__FILE__}"-end+exec "LD_PRELOAD=/usr/lib/libjemalloc.so.1 ruby #{__FILE__}" if !ENV["LD_PRELOAD"]-if ENV['LD_PRELOAD'].include?("jemalloc")+if ENV["LD_PRELOAD"].include?("jemalloc")# for 3.6.0 we need a patch jemal 1.1.0 gem (1.1.1 does not support 3.6.0)# however ffi is a problem so we need to patch the gem- require 'jemal'+ require "jemal"$jemalloc = trueend-if ENV['LD_PRELOAD'].include?("mwrap")+if ENV["LD_PRELOAD"].include?("mwrap")$mwrap = true- require 'mwrap'+ require "mwrap"enddef bin_diff(current)@@ -39,7 +35,11 @@ endrequire File.expand_path("../../config/environment", __FILE__)-Rails.application.routes.recognize_path('abc') rescue nil+begin+ Rails.application.routes.recognize_path("abc")+rescue StandardError+ nil+endI18n.t(:posts)def rss@@ -47,9 +47,7 @@ def rssenddef loop_sites- RailsMultisite::ConnectionManagement.each_connection do- yield- end+ RailsMultisite::ConnectionManagement.each_connection { yield }enddef biggest_klass(klass)@@ -57,7 +55,10 @@ def biggest_klass(klass)enddef iter(warmup: false)- loop_sites { Topic.first; I18n.t('too_late_to_edit') }+ loop_sites do+ Topic.first+ I18n.t("too_late_to_edit")+ endif !warmupGC.start(full_mark: true, immediate_sweep: true)@@ -75,24 +76,17 @@ def iter(warmup: false)array_delta = biggest_klass(Array).length - $biggest_array_lengthputs "rss: #{rss} (#{rss_delta}) #{mwrap_delta}#{jedelta} heap_delta: #{GC.stat[:heap_live_slots] - $baseline_slots} array_delta: #{array_delta}"- if $jemalloc- bin_diff(jemal_stats)- end+ bin_diff(jemal_stats) if $jemallocend-enditer(warmup: true)-4.times do- GC.start(full_mark: true, immediate_sweep: true)-end+4.times { GC.start(full_mark: true, immediate_sweep: true) }if $jemalloc$baseline = Jemal.stats$baseline_jemalloc_active = $baseline[:active]- 4.times do- GC.start(full_mark: true, immediate_sweep: true)- end+ 4.times { GC.start(full_mark: true, immediate_sweep: true) }enddef render_table(array)@@ -102,33 +96,33 @@ def render_table(array)cols = array[0].lengtharray.each do |row|- row.each_with_index do |val, i|- width[i] = [width[i].to_i, val.to_s.length].max- end+ row.each_with_index { |val, i| width[i] = [width[i].to_i, val.to_s.length].max }endarray[0].each_with_index do |col, i|- buffer << col.to_s.ljust(width[i], ' ')+ buffer << col.to_s.ljust(width[i], " ")if i == cols - 1buffer << "\n"else- buffer << ' | '+ buffer << " | "endendbuffer << ("-" * (width.sum + width.length))buffer << "\n"- array.drop(1).each do |row|- row.each_with_index do |val, i|- buffer << val.to_s.ljust(width[i], ' ')- if i == cols - 1- buffer << "\n"- else- buffer << ' | '+ array+ .drop(1)+ .each do |row|+ row.each_with_index do |val, i|+ buffer << val.to_s.ljust(width[i], " ")+ if i == cols - 1+ buffer << "\n"+ else+ buffer << " | "+ endendend- endbufferend@@ -141,14 +135,20 @@ def mwrap_logreport << "\n"table = []- Mwrap.each(200000) do |loc, total, allocations, frees, age_sum, max_life|- table << [total, allocations - frees, frees == 0 ? -1 : (age_sum / frees.to_f).round(2), max_life, loc]+ Mwrap.each(200_000) do |loc, total, allocations, frees, age_sum, max_life|+ table << [+ total,+ allocations - frees,+ frees == 0 ? -1 : (age_sum / frees.to_f).round(2),+ max_life,+ loc,+ ]endtable.sort! { |a, b| b[1] <=> a[1] }table = table[0..50]- table.prepend(["total", "delta", "mean_life", "max_life", "location"])+ table.prepend(%w[total delta mean_life max_life location])report << render_table(table)end@@ -158,15 +158,13 @@ endMwrap.clear-if $mwrap- $mwrap_baseline = Mwrap.total_bytes_allocated - Mwrap.total_bytes_freed-end+$mwrap_baseline = Mwrap.total_bytes_allocated - Mwrap.total_bytes_freed if $mwrap$baseline_slots = GC.stat[:heap_live_slots]$baseline_rss = rss$biggest_array_length = biggest_klass(Array).length-100000.times do+100_000.times doiterif $mwrapputs mwrap_logdiff --git a/script/test_pretty_text.rb b/script/test_pretty_text.rbindex 29839d96293..02e8644a9eb 100644--- a/script/test_pretty_text.rb+++ b/script/test_pretty_text.rb@@ -9,7 +9,7 @@ puts PrettyText.cook "test"# JSPrettyText.cook "test"- PrettyText.v8.eval('gc()')+ PrettyText.v8.eval("gc()")# if i % 500 == 0#p PrettyText.v8.heap_statsdiff --git a/script/thread_detective.rb b/script/thread_detective.rbindex c654158edef..83e886d085c 100644--- a/script/thread_detective.rb+++ b/script/thread_detective.rb@@ -9,13 +9,9 @@ class ThreadDetectiveThread.new { sleep 1 }enddef self.start(max_threads)- @thread ||= Thread.new do- self.new.monitor(max_threads)- end+ @thread ||= Thread.new { self.new.monitor(max_threads) }- @trace = TracePoint.new(:thread_begin) do |tp|- Thread.current.origin = Thread.current.inspect- end+ @trace = TracePoint.new(:thread_begin) { |tp| Thread.current.origin = Thread.current.inspect }@trace.enableend@@ -52,5 +48,4 @@ class ThreadDetectivesleep 1endend-enddiff --git a/script/user_simulator.rb b/script/user_simulator.rbindex fb7853ac71c..562c559ed1c 100644--- a/script/user_simulator.rb+++ b/script/user_simulator.rb@@ -4,31 +4,32 @@## by default 1 new topic every 30 sec, 1 reply to last topic every 30 secs-require 'optparse'-require 'gabbler'+require "optparse"+require "gabbler"user_id = nildef sentence- @gabbler ||= Gabbler.new.tap do |gabbler|- story = File.read(File.dirname(__FILE__) + "/alice.txt")- gabbler.learn(story)- end+ @gabbler ||=+ Gabbler.new.tap do |gabbler|+ story = File.read(File.dirname(__FILE__) + "/alice.txt")+ gabbler.learn(story)+ endsentence = +""- until sentence.length > 800 do+ until sentence.length > 800sentence << @gabbler.sentencesentence << "\n"endsentenceend-OptionParser.new do |opts|- opts.banner = "Usage: ruby user_simulator.rb [options]"- opts.on("-u", "--user NUMBER", "user id") do |u|- user_id = u.to_i+OptionParser+ .new do |opts|+ opts.banner = "Usage: ruby user_simulator.rb [options]"+ opts.on("-u", "--user NUMBER", "user id") { |u| user_id = u.to_i }end-end.parse!+ .parse!unless user_idputs "user must be specified"@@ -37,19 +38,19 @@ endrequire File.expand_path(File.dirname(__FILE__) + "/../config/environment")-unless ["profile", "development"].include? Rails.env+unless %w[profile development].include? Rails.envputs "Bad idea to run a script that inserts random posts in any non development environment"exitenduser = User.find(user_id)-last_topics = Topic.order('id desc').limit(10).pluck(:id)+last_topics = Topic.order("id desc").limit(10).pluck(:id)puts "Simulating activity for user id #{user.id}: #{user.name}"while trueputs "Creating a random topic"- category = Category.where(read_restricted: false).order('random()').first+ category = Category.where(read_restricted: false).order("random()").firstPostCreator.create(user, raw: sentence, title: sentence[0..50].strip, category: category.id)puts "creating random reply"