#!/usr/bin/env ruby SCRIPTNAME = 'html2cgiform.rb' SYNOPTIC = "#{SCRIPTNAME} は HTML 形式のファイルから = の形にデータの内容を変換して返すスクリプトである. (絶対どこかにこういうのあるはずなのに... 見つからなかった...)" USAGE = "#{SCRIPTNAME} [OPTIONS] < HTML_file cat HTML_file | #{SCRIPTNAME} [OPTIONS]" MAINTAINERS = ['Yasuhiro MORIKAWA '] UPDATE = '2007/10/25' VER = '0.2' URL = 'http://epa.scitec.kobe-u.ac.jp/~itpass' # 履歴: # Ver. 0.2, 2007/10/25 森川 靖大 # - エスケープの仕方がまずかったので修正. # # Ver. 0.1, 2007/10/24 森川 靖大 # - 世の中にこういったものがあるはず... と思いながらも見つけられず, # 仕方なく作成する. require 'uri' require 'cgi' # オプション解析 require 'optparse' opt = OptionParser.new('', 20, ' ' * 6) OPTS = Hash.new OPTS[:submit] = 'save' opt.on('-s', '--save', 'Save ボタンを押した際の内容を返す' ) { OPTS[:submit] = 'save' } opt.on('-h', '-H', '--help', 'この, ヘルプメッセージを出力.' ) { OPTS[:help] = true } opt.parse!(ARGV) rescue OPTS[:error] = $!.to_s # [-h, -H, --help] でヘルプを出力して終了 if OPTS[:help] HELP = " #{SCRIPTNAME} SYNOPTIC: #{SYNOPTIC} USAGE: #{USAGE} OPTION: #{opt.help} EXAMPLE: #{SCRIPTNAME} -s < hogehoge.html cat foo.html | #{SCRIPTNAME} --save VERSION: #{SCRIPTNAME} Version #{VER}, Last Update: #{UPDATE}. MAINTAINERS: " print(HELP) MAINTAINERS.each { |v| print "%6s" % ' ', v, "\n" } print "%8s" % ' ', "All Right Reserved.\n\n" exit 0 end all_contents = readlines.join('\n') cgi_hash = {} remain_contents = "#{all_contents}" while remain_contents =~ /(.*?)<\/textarea>/im remain_contents = $~.pre_match remain_contents << $~.post_match name = $1 value = $2 cgi_hash[name] = CGI.escape( CGI.unescapeHTML( value.gsub(/\\n/, "") ) ) end while remain_contents =~ //im remain_contents = $~.pre_match remain_contents << $~.post_match cgi_hash[$2] = CGI.escape( CGI.unescapeHTML($3) ) name = $2 type = $1 if ( type == 'submit' ) && !( OPTS[:submit] == name ) then cgi_hash.delete(name) end end cgi_form_array = [] cgi_hash.each_pair {|key, value| cgi_form_array << "#{key}=#{value}"} print cgi_form_array.join('&')