2 # -*- coding: utf-8 -*-
4 #= Atom Feed 1.0を管理するWEBアプリケーション
6 #Autohr:: Kureha Hisame (http://lunardial.sakura.ne.jp/) & Yui Naruse (http://airemix.com/)
8 #Copyright:: Copyright 2009 FeedBlog Project (http://sourceforge.jp/projects/feedblog/)
14 require "rexml/document"
27 XMLPATH = "./../lunardial/xml/"
29 LISTXMLPATH = "#{XMLPATH}loglist.xml"
30 # FeedBlog上の表示ページからログ格納ディレクトリまでのパス
34 # ファイルマネージャー機能を使用するならtrue
36 # ファイルマネージャー機能スクリプト(filemanager.rb)のパス
37 FILEMANAGER = "./filemanager.rb"
38 # XMLに書き込む際、改行部分を<br>のまま保持するか、改行記号に直すか
40 # ファイルの書き込み時にENTRYのIDおよびURLを、FEEDオブジェクトから自動生成した値に置換するか否か
41 REPLACEENTRYIDANDURL = false
43 # EXPERIMENTAL AREA START
44 TO_HTML_ENTRYTEMPLATE = 'htmltemp/diary.html.erb'
45 TO_HTML_MAINTEMPLATE = 'htmltemp/main.html.erb'
46 # EXPERIMENTAL AREA END
49 APPVERSION = "- FeedGenerator for Ruby version 2.0.0.0 -<br>Copyright(c) 2009 Kureha.H (<a href=\"http://lunardial.sakura.ne.jp/\" target=\"_blank\">http://lunardial.sakura.ne.jp/</a>) & Yui Naruse (<a href=\"http://airemix.com/\" target=\"_blank\">http://airemix.com/</a>)"
51 APPTITLE = "FeedGenerator for Ruby version 2.0.0.0"
59 # ruby-1.9.x以降ではファイルを開いた際、エンコードの指定を行わないとエラーの原因になります。
60 # ただしruby-1.8.6以前はエンコードの指定に対応していないため、独自メソッドを定義してファイルの入出力を行います。
62 # _arg[0]_ :: 入出力を行うファイルのパス
63 # _arg[1]_ :: モードの指定。例 : w:utf-8(書き込みモード・UTF-8エンコードでファイルを開く)
69 arg[1] = mode[/[^:]+/] if RUBY_VERSION < "1.8.7" && mode.include?(':')
70 rdonly_p = /\A[^:]*[wa+]/ !~ mode
72 rdonly_p = !(mode & (IO::WRONY | IO::RDWR))
75 f.flock(rdonly_p ? File::LOCK_SH : File::LOCK_EX)
99 # = Feed/Entryのスーパークラス
101 # 入出力用のメソッドなど、共通する機能を提供します
105 # _hash_ :: 値を格納したhash配列。superfeed.new(CGI::Session.new(new CGI).params)のようにして使う。
111 @paramlist.each do |key|
112 val = hash[key.to_sym] || hash[key.to_s]
115 val.gsub!(/\r\n|\r/, "\n")
116 @attr[key.to_sym] = CGI.escapeHTML(val)
119 @attr[key.to_sym] = ""
123 # 可視・不可視を示すハッシュキーを格納する配列です
126 # ハッシュキーの日本語説明を格納する配列です
131 attr_reader :attr, :paramlist, :name, :display
133 # 内部の@attrハッシュにアクセスする手段を提供するメソッドです
135 # AbstractEntry.attr[:title]にアクセスしたい場合はAbstractEntry.titleで可能になります。
136 # AbstractEntry.send("title")という方法でもアクセス可能です。
137 def method_missing(methname, *args)
138 methname = methname.to_s
140 if methname[-1] == ?=
142 raise ArgumentError, "wrong number of arguments (#{args.length} for 1)" unless args.length == 1
144 methname = @paramlist.find{|par|par == methname}
145 return @attr[methname.to_sym] = args[0] if methname
148 raise ArgumentError, "wrong number of arguments (#{args.length} for 0)" unless args.empty?
149 return @attr[methname.to_sym] if @attr.key?(methname.to_sym)
151 # attr上にキーがない値を入れようとした場合はNoMethodError
160 @attr[key.to_sym] = value
166 # Feedの基礎情報を保有するクラスです
167 class Feed < AbstractEntry
170 # _hash_ :: 値を格納したhash配列。feed.new(CGI::Session.new(new CGI).params)のようにして使います。
176 @paramlist = ["feedattr", "title", "subtitle", "self", "url", "updated", "feedid", "rights", "aname", "amail", "others"]
178 # AbstractEntryのinitializeメソッドを呼び出し、値を@attr配列に格納します
181 # 可視・不可視を示すハッシュキーを格納する配列です
182 @display = {"feedattr" => "none", "title" => "", "subtitle" => "",
183 "self" => "", "url" => "",
184 "updated" => "none", "feedid" => "",
185 "rights" => "", "aname" => "",
186 "amail" => "", "others" => "none"}
188 # デバッグモードの場合、全ての入力要素を表示します
190 @display.each do |key, val|
195 # ハッシュキーの日本語説明を格納する配列です
196 @name = {"feedattr" => "feedの保持している属性", "title" => "ウェブページのタイトル", "subtitle" => "ウェブページの簡単な説明",
197 "self" => "このXMLファイルのURL", "url" => "ウェブページのURL",
198 "updated" => "XMLファイルの最終更新日", "feedid" => "あなたのページ独自のID",
199 "rights" => "ページの著作権表記", "aname" => "ページの製作者",
200 "amail" => "ページ製作者のメールアドレス", "others" => "その他の要素"}
204 # Atom XMLファイルを読み込んで解析し、等価なFeedオブジェクトを返却するメソッドです
206 # _path_ :: Atom XMLファイルのパス
207 def self.readxml(path)
210 doc = REXML::Document.new(myopen(path, "r:utf-8"){|f|f.read})
216 doc.elements["feed"].attributes.each_attribute do |attr|
217 xmlattr.push("#{attr.to_string} ")
219 xml[:feedattr] = xmlattr.join("\n").gsub(/"/, "'")
221 # XML解析部分です。各element毎に判定を行います
222 doc.elements.each("feed") do |elm|
223 elm.elements.each { |child|
227 xml[:feedid] = child.text
228 when "title", "subtitle", "updated", "rights"
229 xml[child.name.to_sym] = child.text
231 child.elements.each do |gchild|
234 xml[:aname] = gchild.text
236 xml[:amail] = gchild.text
240 child.attributes.each do |k, v|
243 xml[:self] = child.attributes["href"]
244 elsif v == "alternate"
245 xml[:url] = child.attributes["href"]
252 # 上記判定以外の全要素は配列に格納します
253 others.push(child.to_s)
262 xml[:others] = others.join("\n")
267 # 内部に保持している情報を、Atom Feed1.0形式の文字列に出力するメソッドです
271 # buf.push("<feed #{@attr[:feedattr]}>")
272 buf.push("<feed xml:lang='ja-jp' xmlns='http://www.w3.org/2005/Atom'>");
273 buf.push("<title type=\"text\">#{@attr[:title]}</title>")
274 buf.push("<subtitle type=\"text\">#{@attr[:subtitle]}</subtitle>")
275 buf.push("<link rel=\"self\" type=\"application/atom+xml\" href=\"#{@attr[:self]}\" />")
276 buf.push("<link rel=\"alternate\" type=\"text/html\" href=\"#{@attr[:url]}\" />")
277 buf.push("<updated>#{Time.now.iso8601}</updated>")
278 buf.push("<id>#{@attr[:feedid]}</id>")
279 buf.push("<rights type=\"text\">#{@attr[:rights]}</rights>")
281 buf.push("\t<name>#{@attr[:aname]}</name>")
282 buf.push("\t<email>#{@attr[:amail]}</email>")
283 buf.push("</author>")
284 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
286 return buf.join("\n")
290 def self.update(path, feed)
291 entrylist = Entry.readxml(path)
292 Feed.to_xml(path, feed, entrylist)
299 # _feed_ :: Feedオブジェクト
300 # _entry_ :: Entryオブジェクトの配列
301 def self.to_xml(path, feed, entrylist_tmp)
303 entrylist = entrylist_tmp.dup
304 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
305 buf.push("#{feed.to_s}\n")
306 entrylist.each { |entry|
307 if REPLACEENTRYIDANDURL
308 entry.entryid.gsub!(/^[^\?]*\?/, "")
309 entry.entryid = feed.url + "?" + entry.entryid
310 entry.url = feed.url + "#" + entry.entryid
312 buf.push("#{entry.to_s}\n")
316 myopen(path, "w") do |f|
317 f.print buf.join("\n")
323 # _feed_ :: Feedオブジェクト
324 # _entry_ :: Entryオブジェクトの配列
325 def self.to_xml_plain(path, feed, entrylist)
327 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
328 buf.push("#{feed.to_s}\n")
329 entrylist.each { |entry|
330 buf.push("#{entry.to_s}\n")
334 myopen(path, "w") do |f|
335 f.print buf.join("\n")
343 # Entryの基礎情報を保有するクラスです
344 class Entry < AbstractEntry
347 # _hash_ :: 値を格納したhash配列。entry.new(CGI::Session.new(new CGI).params)のようにして使います。
353 @paramlist = ["entryid", "title", "summary", "published", "updated", "url", "content", "others"]
355 # AbstractEntryのinitializeメソッドを呼び出し、値を@attr配列に格納します
358 # 可視・不可視を示すハッシュキーを格納する配列です
359 @display = {"entryid" => "none", "title" => "",
360 "summary" => "", "published" => "none",
361 "updated" => "none", "url" => "",
362 "content" => "", "others"=>"none"}
364 # デバッグモードの場合、全ての入力要素を表示します
366 @display.each do |key, val|
371 # ハッシュキーの日本語説明を格納する配列です
372 @name = {"entryid" => "記事固有のID", "title" => "記事のタイトル",
373 "summary" => "記事の簡単な説明", "published" => "記事の出版時刻",
374 "updated" => "記事の更新時刻", "url" => "記事へのURLアドレス",
375 "content" => "記事の本文", "others"=>"その他の項目"}
378 # Atom XMLファイルを読み込んで解析し、等価なEntryオブジェクト配列を返却するメソッドです
380 # _path_ :: Atom XMLファイルのパス
381 def self.readxml(path)
384 doc = REXML::Document.new(myopen(path, "r:utf-8"){|f|f.read})
388 # XML解析部分です。各element毎に判定を行います
389 doc.elements.each("feed/entry") do |elm|
392 elm.elements.each do |child|
396 xml[:entryid] = child.text
398 xml[:url] = child.attributes["href"]
399 when "title", "summary", "summary", "published", "updated", "content"
400 xml[child.name.to_sym] = child.text
402 # 上記判定以外の全要素は配列に格納します
403 others.push(child.to_s)
409 xml[:others] = others.join("\n")
410 entrylist.push(Entry.new(xml))
416 # Atom XMLファイルを読み込んで解析し、テンプレートファイルにしたがってHTMLに変換するメソッドです
417 def self.to_html(xmlpath, destpath, entry_temppath, html_temppath)
419 if xmlpath.empty? or destpath.empty? or entry_temppath.empty? or html_temppath.empty?
424 unless File.exist?(xmlpath) and File.exist?(entry_temppath) and File.exist?(html_temppath)
429 entrylist = Entry.readxml(xmlpath)
434 body << e.to_template(entry_temppath)
438 html_temp = HtmlWriter.new(html_temppath, binding)
441 myopen(destpath, 'w:utf-8') { |f|
442 f.write(CGI.pretty(html_temp.to_code))
446 # Entryをテンプレートに沿って変形するメソッド
447 def to_template(temppath)
448 erb = HtmlWriter.new(temppath, binding)
449 title = CGI.unescapeHTML(@attr[:title])
450 date = @attr[:published]
451 content = CGI.unescapeHTML(@attr[:content])
456 def self.insert(path, entry)
457 feed = Feed.readxml(path)
458 entrylist = Entry.readxml(path)
459 entrylist.unshift entry
461 Feed.to_xml(path, feed, entrylist)
467 def self.update(path, entry)
468 feed = Feed.readxml(path)
469 entrylist = Entry.readxml(path)
472 entrylist.each_with_index { |e, i|
473 if e.entryid == entry.entryid
478 Feed.to_xml(path, feed, entrylist) if successed
484 def self.select(path, entryid)
485 feed = Feed.readxml(path)
486 entrylist = Entry.readxml(path)
489 entrylist.each_with_index { |e, i|
490 entry = entrylist[i].dup if e.entryid == entryid
497 def self.delete(path, entryid)
498 feed = Feed.readxml(path)
499 entrylist = Entry.readxml(path)
503 entrylist.each_with_index { |e, i|
504 if e.entryid == entryid
511 entrylist.delete_at delete_index
512 Feed.to_xml(path, feed, entrylist)
518 # データソースから読み取ったHTMLを、エディタで編集可能な形式に変換するメソッドです
519 def content_for_generator
520 str = @attr[:content].dup
522 str.gsub!(/(<\/(?:p|h\d|div)(?:>|>))\n/i, '\1')
523 str.gsub!(/\n/, '<br>') if REPLACEBRTAG
524 str.gsub!(/(<(?:(?!>).)*?)#{Regexp.escape(FEEDXMLDIR)}/) { "#$1#{XMLPATH}" }
528 # エディタで編集されたCONTENT要素を、データソースに書き込める形式に変換するメソッドです
530 str = @attr[:content].dup
531 str = CGI.unescapeHTML(str)
533 str.gsub!(/(\r\n|\n)/, "")
534 str.gsub!(/<br>|<br[ ]*\/>/i, "\n") if REPLACEBRTAG
535 str.gsub!(/(<br>|<br[ ]*\/>|<\/p>|<\/h\d>|<\/div>)(?=[^\n])/i) { "#$1\n" } unless REPLACEBRTAG
536 str.gsub!(/(<[^>]*?)#{Regexp.escape(XMLPATH)}/) { "#$1#{FEEDXMLDIR}" }
540 # 確認画面で表示されるCONTENT要素を生成するメソッドです
542 str = @attr[:content].dup
543 str = CGI.unescapeHTML(str)
545 str.gsub!(/<br>|<br[ ]*\/>/i, "\n") if REPLACEBRTAG
546 str.gsub!(/(<[^>]*?)#{Regexp.escape(FEEDXMLDIR)}/) { "#$1#{XMLPATH}" }
550 # 内部に保持している情報を、Atom Feed1.0形式の文字列に出力するメソッドです
554 buf.push("<id>#{@attr[:entryid]}</id>")
555 buf.push("<title>#{@attr[:title]}</title>")
556 buf.push("<summary>#{@attr[:summary]}</summary>")
557 buf.push("<published>#{@attr[:published]}</published>")
558 buf.push("<updated>#{@attr[:updated]}</updated>")
559 buf.push("<link href=\"#{@attr[:url]}\" />")
560 buf.push("<content type=\"html\">#{@attr[:content]}</content>")
561 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
564 return buf.join("\n")
570 # テンプレートファイル(*.erb)を読み込み、管理するクラスです
574 # _template_ :: テンプレートファイル(*.erb)のパス
575 # _binding_ :: binding変数
576 def initialize(template, binding)
577 @erb = ERB.new(myopen(template, "r:utf-8") {|f| f.read}, nil, "-")
581 # テンプレートファイルの文字列を返却するメソッドです
583 @erb.result(@binding)
589 # loglist.xmlにかかわる入出力を行います
593 # _display_ :: 画面表示用文字の配列
594 # _path_ :: XMLファイルパスの配列
595 # _logpath_ :: loglist.xmlのパス
596 def initialize(display, path, logpath)
602 attr_accessor :display, :path, :logpath
604 # loglist.xmlファイルを読み込んで解析し、LogListオブジェクトを返却するメソッドです
606 # _logpath_ :: loglist.xmlへのパス
607 def LogList.readxml(logpath)
611 myopen(logpath, "r:utf-8") { |f|
615 doc = REXML::Document.new(lines.join("\n"))
619 doc.elements.each("list/file") { |elm|
620 elm.elements.each {|child|
623 @display.push(child.text)
625 @path.push(child.text)
632 return LogList.new(@display, @path, logpath)
635 # loglist.xmlにオブジェクトの内容を反映するメソッドです
639 path.each_with_index do |path, i|
641 buf.push("<display>#{@display[i]}</display>")
642 buf.push("<path>#{@path[i]}</path>")
647 myopen(@logpath, "w") do |f|
648 f.print buf.join("\n")
662 # ファイルの一覧を取得し、ファイル名称を格納した配列を返却します
664 arr = Dir::entries(XMLPATH).sort
673 # _name_ :: 消去するファイル名
675 File.delete(XMLPATH + name.match(/[^\/]*?$/).to_a[0])
680 # _name_ :: アップロードファイルの名称
681 # _img_ :: アップロードファイル
682 def upload(name, img)
683 open(XMLPATH + File.basename(name), "w") do |f|
692 # コントローラ部分に相当する処理を受け持つクラスです
694 def Controller.NormalForm(cgi, session, params, db)
696 # modeとactionの相関図は以下のようになります。
704 session["filepath"] = params["logpath"]
705 db["loglist"] = LogList.readxml(LISTXMLPATH)
706 # 初期状態で選択されるログは「loglist.xml」の最上に位置するログになります
707 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
708 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
709 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
713 case params["action"]
716 session["target_filepath"] = params["target_filepath"]
717 db["newentry"] = Entry.new(params)
718 db["newentry"].content = db["newentry"].content_for_blog
721 session["target_filepath"] = params["target_filepath"]
722 successed = Entry.insert(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
724 db["error"] = "日記の新規追加に失敗しました。"
725 params["mode"] = "error"
729 session["target_filepath"] = params["target_filepath"]
730 db["newentry"] = Entry.new(params)
732 # New Diary - Default
733 session["target_filepath"] = session["filepath"]
734 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
735 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
740 case params["action"]
743 session["target_filepath"] = params["target_filepath"]
744 session["editid"] = cgi["editid"].to_s
745 db["editentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["editid"])
748 session["target_filepath"] = params["target_filepath"]
749 session["editid"] = cgi["editid"].to_s
750 db["editentry"] = Entry.new(params)
751 db["editentry"].content = db["editentry"].content_for_blog
754 session["target_filepath"] = params["target_filepath"]
755 successed = Entry.update(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
757 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
758 params["mode"] = "error"
761 session["target_filepath"] = params["target_filepath"]
762 db["editentry"] = Entry.new(params)
764 # Edit Diary - Default
765 session["target_filepath"] = session["filepath"]
766 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
767 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
772 case params["action"]
775 session["target_filepath"] = params["target_filepath"]
776 session["delid"] = cgi["delid"].to_s
777 db["delentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["delid"])
780 session["target_filepath"] = params["target_filepath"]
781 successed = Entry.delete(XMLPATH + File.basename(params["target_filepath"]), cgi["delid"].to_s)
783 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
784 params["mode"] = "error"
787 session["target_filepath"] = params["target_filepath"]
788 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["target_filepath"]))
789 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["target_filepath"]))
791 # Delete Diary - Default
792 session["target_filepath"] = session["filepath"]
793 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
794 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
799 case params["action"]
802 session["target_filepath"] = params["target_filepath"]
803 db["feed"] = Feed.new(params)
804 # 実際にFeed情報の変更をファイルに反映
806 session["target_filepath"] = params["target_filepath"]
807 db["feed"] = Feed.new(params)
809 session["target_filepath"] = params["target_filepath"]
810 Feed.update(XMLPATH + File.basename(params["target_filepath"]), Feed.new(params))
812 session["target_filepath"] = session["filepath"]
813 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
819 db["loglist"] = LogList.readxml(LISTXMLPATH)
820 case params["action"]
821 # ログファイルの編集を実際にファイルに反映
823 # エラーチェック。この段階のエラーは強度のエラーを発する。
824 db["loglist"].path.each do |val|
825 if val == cgi["logpath"]
826 # 重複していた場合エラーメッセージを表示し、処理を行わない
827 params["action"] = ""
828 params["mode"] = "error"
829 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。<br>環境を見直してください。"
835 db["loglist"].path[1, 0] = cgi["logpath"]
836 db["loglist"].display[1, 0] = cgi["logdisplay"]
838 # 既存のdiary.xmlを指定された名称でコピーして保存
839 FileUtils.copy_file(XMLPATH + File.basename(db["loglist"].path[0]), XMLPATH + File.basename(db["logpath"]), true)
841 db["loglist"] = LogList.readxml(LISTXMLPATH)
843 # 新たなdiary.xmlを生成。この際保持する情報は同一のFeedオブジェクトnew()
844 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), db["feed"], [])
848 db["loglist"].path.each do |val|
849 if val == cgi["logpath"]
850 # 重複していた場合エラーメッセージを表示し、処理を行わない
851 params["action"] = ""
852 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
857 db["logpath"] = cgi["logpath"]
858 db["logdisplay"] = cgi["logdisplay"]
860 if db["logpath"].blank? || db["logdisplay"].blank?
861 params["action"] = ""
867 db["logdelindex"] = params["logdelindex"].to_i
869 if db["logdelindex"] < 1
870 db["error"] = "<span style='color: #ff0000'>ログファイルの削除パラメタが不正です。</span><br>"
871 params["action"] = ""
875 if cgi["logdelindex"].to_i < 1
876 params["action"] = ""
877 params["mode"] = "error"
878 db["error"] = "ログファイルの削除中に重大なエラーが発生しました。<br>環境を見直してください。"
882 File.delete(XMLPATH + File.basename(db["loglist"].path[db["logdelindex"]]))
884 db["loglist"].path.delete_at(cgi["logdelindex"].to_i)
885 db["loglist"].display.delete_at(cgi["logdelindex"].to_i)
888 db["loglist"] = LogList.readxml(LISTXMLPATH)
894 db["logeditindex"] = params["logdelindex"].to_i
896 db["logpath"] = db["loglist"].path[db["logeditindex"]]
897 db["logdisplay"] = db["loglist"].display[db["logeditindex"]]
899 if db["logeditindex"] == 0
900 db["error"] = "<span style='color: #ff0000'>ログファイルの編集パラメタが不正です。</span><br>"
901 params["action"] = ""
906 db["loglist"].path.each_with_index do |val, i|
907 if db["logeditindex"] != i
908 if params["logpath"].to_s == db["loglist"].path[i].to_s
914 if checkflag == false
915 params["action"] = "edit"
916 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
918 db["loginsertindex"] = params["loginsertindex"].to_i
920 db["logpath"] = params["logpath"].to_s
921 db["logdisplay"] = params["logdisplay"].to_s
926 db["loglist"].path.each_with_index do |val, i|
927 if db["logeditindex"] != i
928 if params["logpath"].to_s == db["loglist"].path[i].to_s
934 if checkflag == false
935 params["action"] = ""
936 params["mode"] = "error"
937 db["error"] = "ログファイルの編集中に重大なエラーが発生しました。<br>環境を見直してください。"
940 db["loginsertindex"] = params["loginsertindex"].to_i
942 db["logpath"] = params["logpath"].to_s
943 db["logdisplay"] = params["logdisplay"].to_s
946 if XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]) != XMLPATH + File.basename(db["logpath"])
947 FileUtils.move(XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]), XMLPATH + File.basename(db["logpath"]))
949 db["loglist"].path.delete_at(db["logeditindex"])
950 db["loglist"].display.delete_at(db["logeditindex"])
951 db["loglist"].path.insert(db["loginsertindex"] + 1, db["logpath"])
952 db["loglist"].display.insert(db["loginsertindex"] + 1, db["logdisplay"])
959 # 現在編集中のデータを強制的に最上のファイルパスに変更
960 session["filepath"] = db["loglist"].path[0]
963 prevmonth = (DateTime.now << 1)
965 # 前月の時刻を元に、ディフォルト書式を生成します
966 db["logpath"] = FEEDXMLDIR + prevmonth.strftime("%Y%m") + ".xml"
967 db["logdisplay"] = prevmonth.strftime("%Y年%m月").gsub("年0", "年")
972 db["loglist"] = LogList.readxml(LISTXMLPATH)
976 case params["action"]
979 file = FileUploader.new
980 file.filelist().each { |fname|
981 file.delete(fname) if File.ftype(XMLPATH + fname) == "file"
986 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}diary.xml"], LISTXMLPATH)
989 db["loglist"] = LogList.readxml(LISTXMLPATH)
992 Feed.to_xml(XMLPATH + db["loglist"].path[0].match(/[^\/]*?$/).to_a[0], Feed.new({}), [])
994 # 初期の編集ファイルはloglist.xml上の最も上のファイル
995 session["filepath"] = db["loglist"].path[0]
996 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
997 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1001 params["action"] = ""
1005 filelist = FileUploader.new.filelist()
1007 # タイプがファイルのみリストとして取得する
1009 filelist.each { |fname| db["filelist"] << fname if File.ftype(XMLPATH + fname) == "file"}
1014 # loglist.xmlが存在するかチェック
1015 if File.exist?(LISTXMLPATH) == false
1016 # なかった場合はloglist.xmlを自動生成
1017 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}diary.xml"], LISTXMLPATH)
1019 Feed.to_xml(XMLPATH + File.basename(loglist.path[0]), Feed.new({}), [])
1022 db["loglist"] = LogList.readxml(LISTXMLPATH)
1024 # diary.xmlが存在するかチェック
1025 if File.exist?(XMLPATH + File.basename(db["loglist"].path[0])) == false
1026 # なかった場合はdiary.xmlを自動生成
1027 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), Feed.new({}), [])
1030 # 初期の編集ファイルはloglist.xml上の最も上のファイル
1031 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1032 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1033 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1038 # マルチパートフォームの場合の処理です
1039 def Controller.MultiForm(cgi, session, params, db)
1041 # loglist.xmlをロードします
1042 db["loglist"] = LogList.readxml(LISTXMLPATH)
1046 case params["action"]
1048 # この段階のエラーに対しては強度のエラーを発する
1050 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1051 db["loglist"].path.each do |val|
1052 if val == db["logpath"]
1053 # 重複していた場合エラーメッセージを表示し、処理を行わない
1055 params["action"] = ""
1056 params["mode"] = "error"
1057 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1062 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1063 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1066 if db["loginsertindex"] == 0
1067 params["action"] = ""
1068 params["mode"] = "error"
1069 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1073 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank?
1074 params["action"] = ""
1075 params["mode"] = "error"
1076 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1081 file = FileUploader.new
1082 file.upload(db["logpath"], db["importxml"])
1085 db["loglist"].path[db["loginsertindex"], 0] = db["logpath"]
1086 db["loglist"].display[db["loginsertindex"], 0] = db["logdisplay"]
1087 db["loglist"].to_xml
1090 db["loglist"] = LogList.readxml(LISTXMLPATH)
1091 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1092 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1093 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1096 # 入力されたログファイルパスが既に存在するかを確認
1098 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1099 db["loglist"].path.each do |val|
1100 if val == db["logpath"]
1101 # 重複していた場合エラーメッセージを表示し、処理を行わない
1103 params["action"] = ""
1104 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1111 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1112 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1113 db["importxml"] = cgi["updata"].read
1117 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1119 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1120 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1121 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1122 db["error"] << "</div>"
1123 params["action"] = ""
1129 if db["loginsertindex"] == 0
1130 params["action"] = ""
1131 db["error"] = "<br><span style='color: #ff0000'>ラジオボックスでログの挿入位置を選択してください!</span><br>"
1135 if db["logpath"] == FEEDXMLDIR || db["logdisplay"].blank?
1136 params["action"] = ""
1137 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名は空欄にできません。</span><br>"
1146 case params["action"]
1148 # この段階のエラーに対しては強度のエラーを発する
1150 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1151 db["loglist"].path.each do |val|
1152 if val == db["logpath"]
1153 # 重複していた場合エラーメッセージを表示し、処理を行わない
1154 params["action"] = ""
1155 params["mode"] = "error"
1156 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1161 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1163 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank? || db["importxml"].blank?
1164 params["action"] = ""
1165 params["mode"] = "error"
1166 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1171 FileUtils.move(XMLPATH + "diary.xml", XMLPATH + File.basename(db["logpath"]))
1173 file = FileUploader.new
1174 file.upload("diary.xml", db["importxml"])
1177 db["loglist"].path[1, 0] = db["logpath"]
1178 db["loglist"].display[1, 0] = db["logdisplay"]
1179 db["loglist"].to_xml
1182 db["loglist"] = LogList.readxml(LISTXMLPATH)
1183 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1184 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1185 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1188 # 入力されたログファイルパスが既に存在するかを確認
1190 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1191 db["loglist"].path.each do |val|
1192 if val == db["logpath"]
1193 # 重複していた場合エラーメッセージを表示し、処理を行わない
1194 params["action"] = ""
1195 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1201 if checkflag == true
1202 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1203 db["importxml"] = cgi["updata"].read
1207 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1209 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1210 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1211 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1212 db["error"] << "</div>"
1213 params["action"] = ""
1218 if db["logpath"].blank? || db["logdisplay"].blank? || db["importxml"].blank?
1219 params["action"] = ""
1220 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名、ログのパスは空欄にできません。</span><br>"
1232 # Formのenctypeがmultypartだった場合、入力された値をrubyバージョンに左右されずに読み取るメソッドです。
1233 def Controller.get_mpart_value(cgi_param)
1234 if RUBY_VERSION >= "1.9.0"
1235 cgi_param[0..cgi_param.length].to_s
1241 # アップロードされたXMLをバージョンに左右されずに読み取るために、ruby-1.9.1以上ではエンコーディングを強制指定します
1242 def Controller.fix_updata_enc(file_to_s)
1243 if RUBY_VERSION >= "1.9.0"
1244 file_to_s.force_encoding("UTF-8")
1253 # SESSION変数、パラメータなどを取得します
1255 session = CGI::Session.new(cgi)
1256 params = Hash[*cgi.params.to_a.map{|k, v| [k, v[0].to_s]}.flatten]
1260 if session["login"] != "true"
1261 if (cgi["loginid"] == LOGINID && cgi["password"] == PASSWORD)
1262 session["login"] = "true"
1264 # ワークフォルダの中をクリーンアップします
1265 filelist = Dir::entries("./work")
1266 # 削除条件 : 最終変更日時から1日(60*60*24sec)かつ、ファイルタイプがファイルの場合
1267 filelist.each do |file|
1268 File.delete("./work/#{file}") if Time.now - File.ctime("./work/#{file}") > 86400 && File.ftype("./work/#{file}") == "file"
1274 if params["mode"] == "logout"
1275 session["login"] = nil
1276 session["logini"] = nil
1277 session["password"] = nil
1283 # セッションが有効な場合のも実行します
1284 if session["login"] == "true"
1287 db = PStore.new("./work/#{session.session_id}.dat")
1293 File.delete("./work/#{session.session_id}.dat")
1294 # PStoreが破損していた場合はセッション情報を破棄する
1295 session["login"] = nil
1296 session["logini"] = nil
1297 session["password"] = nil
1302 if cgi["mode"].respond_to?(:read) && cgi["action"].respond_to?(:read)
1303 params["mode"] = cgi["mode"].read
1304 params["action"] = cgi["action"].read
1305 Controller.MultiForm(cgi, session, params, db)
1307 Controller.NormalForm(cgi, session, params, db)
1310 # エラー画面移行時はセッション情報を破棄する
1311 if params["mode"] == "error"
1312 session["login"] = nil
1313 session["logini"] = nil
1314 session["password"] = nil
1319 # メニューとして表示されるHTML文字列です
1320 if params["target_filepath"].blank?
1321 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["filepath"]} "
1323 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["target_filepath"]} "
1325 if USEFILEMANAGER == true
1326 menu += "[ <a href=\"#{cgi.script_name}?mode=selectlog\">他のファイルを選択</a> ]</div>[ <a href=\"#{cgi.script_name}\">トップページ</a> | 記事管理 ( <a href=\"#{cgi.script_name}?mode=newentry\">作成</a> | <a href=\"#{cgi.script_name}?mode=editentry\">編集</a> | <a href=\"#{cgi.script_name}?mode=delentry\">消去</a> ) | <a href=\"#{cgi.script_name}?mode=editfeed\">XML情報編集</a> | <a href=\"#{cgi.script_name}?mode=log\">ログ管理</a> | <a href=\"#{cgi.script_name}?mode=import\">インポート</a> | <a href=\"#{FILEMANAGER}\" target=\"_blank\">ファイル管理</a> | <a href=\"#{cgi.script_name}?mode=reset\">初期化</a> | <a href=\"#{cgi.script_name}?mode=logout\">ログアウト</a> ]</div>"
1328 menu += "[ <a href=\"#{cgi.script_name}?mode=selectlog\">他のファイルを選択</a> ]</div>[ <a href=\"#{cgi.script_name}\">トップページ</a> | 記事管理 ( <a href=\"#{cgi.script_name}?mode=newentry\">作成</a> | <a href=\"#{cgi.script_name}?mode=editentry\">編集</a> | <a href=\"#{cgi.script_name}?mode=delentry\">消去</a> ) | <a href=\"#{cgi.script_name}?mode=editfeed\">XML情報編集</a> | <a href=\"#{cgi.script_name}?mode=log\">ログ管理</a> | <a href=\"#{cgi.script_name}?mode=import\">インポート</a> | <a href=\"#{cgi.script_name}?mode=reset\">初期化</a> | <a href=\"#{cgi.script_name}?mode=logout\">ログアウト</a> ]</div>"
1332 # modeとactionの相関図は以下のようになります。
1337 if session["login"] != "true"
1338 # セッションが存在しない場合は強制的にトップページに遷移
1339 htmlwriter = HtmlWriter.new("./erbtemp/login.html.erb", binding)
1343 htmlwriter = HtmlWriter.new("./erbtemp/select.html.erb", binding)
1345 htmlwriter = HtmlWriter.new("./erbtemp/newentry.html.erb", binding)
1347 htmlwriter = HtmlWriter.new("./erbtemp/editentry.html.erb", binding)
1349 htmlwriter = HtmlWriter.new("./erbtemp/delentry.html.erb", binding)
1351 htmlwriter = HtmlWriter.new("./erbtemp/editfeed.html.erb", binding)
1353 htmlwriter = HtmlWriter.new("./erbtemp/log.html.erb", binding)
1355 htmlwriter = HtmlWriter.new("./erbtemp/insertfeed.html.erb", binding)
1357 htmlwriter = HtmlWriter.new("./erbtemp/replacefeed.html.erb", binding)
1359 htmlwriter = HtmlWriter.new("./erbtemp/indeximport.html.erb", binding)
1361 htmlwriter = HtmlWriter.new("./erbtemp/reset.html.erb", binding)
1363 htmlwriter = HtmlWriter.new("./erbtemp/error.html.erb", binding)
1365 htmlwriter = HtmlWriter.new("./erbtemp/index.html.erb", binding)
1369 # エラーが発生した場合、それを画面に表示します
1370 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1375 cgi.out{htmlwriter.to_code}
1377 # エラーが発生した場合、それを画面に表示します
1378 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1379 cgi.out{htmlwriter.to_code}
1386 # エラーが発生した場合、それを画面に表示します
1387 detail = ("%s: %s (%s)\n" %
1388 [evar.backtrace[0], evar.message, evar.send('class')]) +
1389 evar.backtrace[1..-1].join("\n")
1390 puts "content-type: text/html\n\n<plaintext>\n" + detail