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/"
28 # FeedBlogを設置したディレクトリのURL
29 HOMEBASE = "https://lunardial.sakura.ne.jp/"
30 # 入力されたフルパスURL(HOMEBASE)を置換する文字列
33 LISTXMLPATH = "#{XMLPATH}loglist.xml"
34 # FeedBlog上の表示ページからログ格納ディレクトリまでのパス
38 # ファイルマネージャー機能を使用するならtrue
40 # ファイルマネージャー機能スクリプト(filemanager.rb)のパス
41 FILEMANAGER = "./filemanager.rb"
42 # XMLに書き込む際、改行部分を<br>のまま保持するか、改行記号に直すか
44 # ファイルの書き込み時にENTRYのIDおよびURLを、FEEDオブジェクトから自動生成した値に置換するか否か
45 REPLACEENTRYIDANDURL = false
47 # EXPERIMENTAL AREA START
48 TO_HTML_ENTRYTEMPLATE = 'htmltemp/diary.html.erb'
49 TO_HTML_MAINTEMPLATE = 'htmltemp/main.html.erb'
50 # EXPERIMENTAL AREA END
53 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>)"
55 APPTITLE = "FeedGenerator for Ruby version 2.0.0.0"
63 # ruby-1.9.x以降ではファイルを開いた際、エンコードの指定を行わないとエラーの原因になります。
64 # ただしruby-1.8.6以前はエンコードの指定に対応していないため、独自メソッドを定義してファイルの入出力を行います。
66 # _arg[0]_ :: 入出力を行うファイルのパス
67 # _arg[1]_ :: モードの指定。例 : w:utf-8(書き込みモード・UTF-8エンコードでファイルを開く)
73 arg[1] = mode[/[^:]+/] if RUBY_VERSION < "1.8.7" && mode.include?(':')
74 rdonly_p = /\A[^:]*[wa+]/ !~ mode
76 rdonly_p = !(mode & (IO::WRONY | IO::RDWR))
79 f.flock(rdonly_p ? File::LOCK_SH : File::LOCK_EX)
103 # = Feed/Entryのスーパークラス
105 # 入出力用のメソッドなど、共通する機能を提供します
109 # _hash_ :: 値を格納したhash配列。superfeed.new(CGI::Session.new(new CGI).params)のようにして使う。
115 @paramlist.each do |key|
116 val = hash[key.to_sym] || hash[key.to_s]
119 val.gsub!(/\r\n|\r/, "\n")
120 @attr[key.to_sym] = CGI.escapeHTML(val)
123 @attr[key.to_sym] = ""
127 # 可視・不可視を示すハッシュキーを格納する配列です
130 # ハッシュキーの日本語説明を格納する配列です
135 attr_reader :attr, :paramlist, :name, :display
137 # 内部の@attrハッシュにアクセスする手段を提供するメソッドです
139 # AbstractEntry.attr[:title]にアクセスしたい場合はAbstractEntry.titleで可能になります。
140 # AbstractEntry.send("title")という方法でもアクセス可能です。
141 def method_missing(methname, *args)
142 methname = methname.to_s
144 if methname[-1] == ?=
146 raise ArgumentError, "wrong number of arguments (#{args.length} for 1)" unless args.length == 1
148 methname = @paramlist.find{|par|par == methname}
149 return @attr[methname.to_sym] = args[0] if methname
152 raise ArgumentError, "wrong number of arguments (#{args.length} for 0)" unless args.empty?
153 return @attr[methname.to_sym] if @attr.key?(methname.to_sym)
155 # attr上にキーがない値を入れようとした場合はNoMethodError
164 @attr[key.to_sym] = value
170 # Feedの基礎情報を保有するクラスです
171 class Feed < AbstractEntry
174 # _hash_ :: 値を格納したhash配列。feed.new(CGI::Session.new(new CGI).params)のようにして使います。
180 @paramlist = ["feedattr", "title", "subtitle", "self", "url", "updated", "feedid", "rights", "aname", "amail", "others"]
182 # AbstractEntryのinitializeメソッドを呼び出し、値を@attr配列に格納します
185 # 可視・不可視を示すハッシュキーを格納する配列です
186 @display = {"feedattr" => "none", "title" => "", "subtitle" => "",
187 "self" => "", "url" => "",
188 "updated" => "none", "feedid" => "",
189 "rights" => "", "aname" => "",
190 "amail" => "", "others" => "none"}
192 # デバッグモードの場合、全ての入力要素を表示します
194 @display.each do |key, val|
199 # ハッシュキーの日本語説明を格納する配列です
200 @name = {"feedattr" => "feedの保持している属性", "title" => "ウェブページのタイトル", "subtitle" => "ウェブページの簡単な説明",
201 "self" => "このXMLファイルのURL", "url" => "ウェブページのURL",
202 "updated" => "XMLファイルの最終更新日", "feedid" => "あなたのページ独自のID",
203 "rights" => "ページの著作権表記", "aname" => "ページの製作者",
204 "amail" => "ページ製作者のメールアドレス", "others" => "その他の要素"}
208 # Atom XMLファイルを読み込んで解析し、等価なFeedオブジェクトを返却するメソッドです
210 # _path_ :: Atom XMLファイルのパス
211 def self.readxml(path)
214 doc = REXML::Document.new(myopen(path, "r:utf-8"){|f|f.read})
220 doc.elements["feed"].attributes.each_attribute do |attr|
221 xmlattr.push("#{attr.to_string} ")
223 xml[:feedattr] = xmlattr.join("\n").gsub(/"/, "'")
225 # XML解析部分です。各element毎に判定を行います
226 doc.elements.each("feed") do |elm|
227 elm.elements.each { |child|
231 xml[:feedid] = child.text
232 when "title", "subtitle", "updated", "rights"
233 xml[child.name.to_sym] = child.text
235 child.elements.each do |gchild|
238 xml[:aname] = gchild.text
240 xml[:amail] = gchild.text
244 child.attributes.each do |k, v|
247 xml[:self] = child.attributes["href"]
248 elsif v == "alternate"
249 xml[:url] = child.attributes["href"]
256 # 上記判定以外の全要素は配列に格納します
257 others.push(child.to_s)
266 xml[:others] = others.join("\n")
271 # 内部に保持している情報を、Atom Feed1.0形式の文字列に出力するメソッドです
275 # buf.push("<feed #{@attr[:feedattr]}>")
276 buf.push("<feed xml:lang='ja-jp' xmlns='http://www.w3.org/2005/Atom'>");
277 buf.push("<title type=\"text\">#{@attr[:title]}</title>")
278 buf.push("<subtitle type=\"text\">#{@attr[:subtitle]}</subtitle>")
279 buf.push("<link rel=\"self\" type=\"application/atom+xml\" href=\"#{@attr[:self]}\" />")
280 buf.push("<link rel=\"alternate\" type=\"text/html\" href=\"#{@attr[:url]}\" />")
281 buf.push("<updated>#{Time.now.iso8601}</updated>")
282 buf.push("<id>#{@attr[:feedid]}</id>")
283 buf.push("<rights type=\"text\">#{@attr[:rights]}</rights>")
285 buf.push("\t<name>#{@attr[:aname]}</name>")
286 buf.push("\t<email>#{@attr[:amail]}</email>")
287 buf.push("</author>")
288 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
290 return buf.join("\n")
294 def self.update(path, feed)
295 entrylist = Entry.readxml(path)
296 Feed.to_xml(path, feed, entrylist)
303 # _feed_ :: Feedオブジェクト
304 # _entry_ :: Entryオブジェクトの配列
305 def self.to_xml(path, feed, entrylist_tmp)
307 entrylist = entrylist_tmp.dup
308 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
309 buf.push("#{feed.to_s}\n")
310 entrylist.each { |entry|
311 if REPLACEENTRYIDANDURL
312 entry.entryid.gsub!(/^[^\?]*\?/, "")
313 entry.entryid = feed.url + "?" + entry.entryid
314 entry.url = feed.url + "#" + entry.entryid
316 buf.push("#{entry.to_s}\n")
320 myopen(path, "w") do |f|
321 f.print buf.join("\n")
327 # _feed_ :: Feedオブジェクト
328 # _entry_ :: Entryオブジェクトの配列
329 def self.to_xml_plain(path, feed, entrylist)
331 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
332 buf.push("#{feed.to_s}\n")
333 entrylist.each { |entry|
334 buf.push("#{entry.to_s}\n")
338 myopen(path, "w") do |f|
339 f.print buf.join("\n")
347 # Entryの基礎情報を保有するクラスです
348 class Entry < AbstractEntry
351 # _hash_ :: 値を格納したhash配列。entry.new(CGI::Session.new(new CGI).params)のようにして使います。
357 @paramlist = ["entryid", "title", "summary", "published", "updated", "url", "content", "others"]
359 # AbstractEntryのinitializeメソッドを呼び出し、値を@attr配列に格納します
362 # 可視・不可視を示すハッシュキーを格納する配列です
363 @display = {"entryid" => "none", "title" => "",
364 "summary" => "", "published" => "none",
365 "updated" => "none", "url" => "",
366 "content" => "", "others"=>"none"}
368 # デバッグモードの場合、全ての入力要素を表示します
370 @display.each do |key, val|
375 # ハッシュキーの日本語説明を格納する配列です
376 @name = {"entryid" => "記事固有のID", "title" => "記事のタイトル",
377 "summary" => "記事の簡単な説明", "published" => "記事の出版時刻",
378 "updated" => "記事の更新時刻", "url" => "記事へのURLアドレス",
379 "content" => "記事の本文", "others"=>"その他の項目"}
382 # Atom XMLファイルを読み込んで解析し、等価なEntryオブジェクト配列を返却するメソッドです
384 # _path_ :: Atom XMLファイルのパス
385 def self.readxml(path)
388 doc = REXML::Document.new(myopen(path, "r:utf-8"){|f|f.read})
392 # XML解析部分です。各element毎に判定を行います
393 doc.elements.each("feed/entry") do |elm|
396 elm.elements.each do |child|
400 xml[:entryid] = child.text
402 xml[:url] = child.attributes["href"]
403 when "title", "summary", "summary", "published", "updated", "content"
404 xml[child.name.to_sym] = child.text
406 # 上記判定以外の全要素は配列に格納します
407 others.push(child.to_s)
413 xml[:others] = others.join("\n")
414 entrylist.push(Entry.new(xml))
420 # Atom XMLファイルを読み込んで解析し、テンプレートファイルにしたがってHTMLに変換するメソッドです
421 def self.to_html(xmlpath, destpath, entry_temppath, html_temppath)
423 if xmlpath.empty? or destpath.empty? or entry_temppath.empty? or html_temppath.empty?
428 unless File.exist?(xmlpath) and File.exist?(entry_temppath) and File.exist?(html_temppath)
433 entrylist = Entry.readxml(xmlpath)
438 body << e.to_template(entry_temppath)
442 html_temp = HtmlWriter.new(html_temppath, binding)
445 myopen(destpath, 'w:utf-8') { |f|
446 f.write(CGI.pretty(html_temp.to_code))
450 # Entryをテンプレートに沿って変形するメソッド
451 def to_template(temppath)
452 erb = HtmlWriter.new(temppath, binding)
453 title = CGI.unescapeHTML(@attr[:title])
454 date = @attr[:published]
455 content = CGI.unescapeHTML(@attr[:content])
460 def self.insert(path, entry)
461 feed = Feed.readxml(path)
462 entrylist = Entry.readxml(path)
463 entrylist.unshift entry
465 Feed.to_xml(path, feed, entrylist)
471 def self.update(path, entry)
472 feed = Feed.readxml(path)
473 entrylist = Entry.readxml(path)
476 entrylist.each_with_index { |e, i|
477 if e.entryid == entry.entryid
482 Feed.to_xml(path, feed, entrylist) if successed
488 def self.select(path, entryid)
489 feed = Feed.readxml(path)
490 entrylist = Entry.readxml(path)
493 entrylist.each_with_index { |e, i|
494 entry = entrylist[i].dup if e.entryid == entryid
501 def self.delete(path, entryid)
502 feed = Feed.readxml(path)
503 entrylist = Entry.readxml(path)
507 entrylist.each_with_index { |e, i|
508 if e.entryid == entryid
515 entrylist.delete_at delete_index
516 Feed.to_xml(path, feed, entrylist)
522 # データソースから読み取ったHTMLを、エディタで編集可能な形式に変換するメソッドです
523 def content_for_generator
524 str = @attr[:content].dup
526 str.gsub!(/(<\/(?:p|h\d|div)(?:>|>))\n/i, '\1')
527 str.gsub!(/\n/, '<br>') if REPLACEBRTAG
528 str.gsub!(/(<(?:(?!>).)*?)#{Regexp.escape(RELAYPATH)}/) { "#$1#{HOMEBASE}" }
532 # エディタで編集されたCONTENT要素を、データソースに書き込める形式に変換するメソッドです
534 str = @attr[:content].dup
535 str = CGI.unescapeHTML(str)
537 str.gsub!(/(\r\n|\n)/, "")
538 str.gsub!(/<br>|<br[ ]*\/>/i, "\n") if REPLACEBRTAG
539 str.gsub!(/(<br>|<br[ ]*\/>|<\/p>|<\/h\d>|<\/div>)(?=[^\n])/i) { "#$1\n" } unless REPLACEBRTAG
540 str.gsub!(/(<[^>]*?)#{Regexp.escape(HOMEBASE)}/) { "#$1#{RELAYPATH}" }
544 # 確認画面で表示されるCONTENT要素を生成するメソッドです
546 str = @attr[:content].dup
547 str = CGI.unescapeHTML(str)
549 str.gsub!(/<br>|<br[ ]*\/>/i, "\n") if REPLACEBRTAG
550 str.gsub!(/(<[^>]*?)#{Regexp.escape(RELAYPATH)}/) { "#$1#{HOMEBASE}" }
554 # 内部に保持している情報を、Atom Feed1.0形式の文字列に出力するメソッドです
558 buf.push("<id>#{@attr[:entryid]}</id>")
559 buf.push("<title>#{@attr[:title]}</title>")
560 buf.push("<summary>#{@attr[:summary]}</summary>")
561 buf.push("<published>#{@attr[:published]}</published>")
562 buf.push("<updated>#{@attr[:updated]}</updated>")
563 buf.push("<link href=\"#{@attr[:url]}\" />")
564 buf.push("<content type=\"html\">#{@attr[:content]}</content>")
565 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
568 return buf.join("\n")
574 # テンプレートファイル(*.erb)を読み込み、管理するクラスです
578 # _template_ :: テンプレートファイル(*.erb)のパス
579 # _binding_ :: binding変数
580 def initialize(template, binding)
581 @erb = ERB.new(myopen(template, "r:utf-8") {|f| f.read}, nil, "-")
585 # テンプレートファイルの文字列を返却するメソッドです
587 @erb.result(@binding)
593 # loglist.xmlにかかわる入出力を行います
597 # _display_ :: 画面表示用文字の配列
598 # _path_ :: XMLファイルパスの配列
599 # _logpath_ :: loglist.xmlのパス
600 def initialize(display, path, logpath)
606 attr_accessor :display, :path, :logpath
608 # loglist.xmlファイルを読み込んで解析し、LogListオブジェクトを返却するメソッドです
610 # _logpath_ :: loglist.xmlへのパス
611 def LogList.readxml(logpath)
615 myopen(logpath, "r:utf-8") { |f|
619 doc = REXML::Document.new(lines.join("\n"))
623 doc.elements.each("list/file") { |elm|
624 elm.elements.each {|child|
627 @display.push(child.text)
629 @path.push(child.text)
636 return LogList.new(@display, @path, logpath)
639 # loglist.xmlにオブジェクトの内容を反映するメソッドです
643 path.each_with_index do |path, i|
645 buf.push("<display>#{@display[i]}</display>")
646 buf.push("<path>#{@path[i]}</path>")
651 myopen(@logpath, "w") do |f|
652 f.print buf.join("\n")
666 # ファイルの一覧を取得し、ファイル名称を格納した配列を返却します
668 arr = Dir::entries(XMLPATH).sort
677 # _name_ :: 消去するファイル名
679 File.delete(XMLPATH + name.match(/[^\/]*?$/).to_a[0])
684 # _name_ :: アップロードファイルの名称
685 # _img_ :: アップロードファイル
686 def upload(name, img)
687 open(XMLPATH + File.basename(name), "w") do |f|
696 # コントローラ部分に相当する処理を受け持つクラスです
698 def Controller.NormalForm(cgi, session, params, db)
700 # modeとactionの相関図は以下のようになります。
708 session["filepath"] = params["logpath"]
709 db["loglist"] = LogList.readxml(LISTXMLPATH)
710 # 初期状態で選択されるログは「loglist.xml」の最上に位置するログになります
711 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
712 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
713 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
717 case params["action"]
720 session["target_filepath"] = params["target_filepath"]
721 db["newentry"] = Entry.new(params)
722 db["newentry"].content = db["newentry"].content_for_blog
725 session["target_filepath"] = params["target_filepath"]
726 successed = Entry.insert(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
728 db["error"] = "日記の新規追加に失敗しました。"
729 params["mode"] = "error"
733 session["target_filepath"] = params["target_filepath"]
734 db["newentry"] = Entry.new(params)
736 # New Diary - Default
737 session["target_filepath"] = session["filepath"]
738 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
739 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
744 case params["action"]
747 session["target_filepath"] = params["target_filepath"]
748 session["editid"] = cgi["editid"].to_s
749 db["editentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["editid"])
752 session["target_filepath"] = params["target_filepath"]
753 session["editid"] = cgi["editid"].to_s
754 db["editentry"] = Entry.new(params)
755 db["editentry"].content = db["editentry"].content_for_blog
758 session["target_filepath"] = params["target_filepath"]
759 successed = Entry.update(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
761 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
762 params["mode"] = "error"
765 session["target_filepath"] = params["target_filepath"]
766 db["editentry"] = Entry.new(params)
768 # Edit Diary - Default
769 session["target_filepath"] = session["filepath"]
770 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
771 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
776 case params["action"]
779 session["target_filepath"] = params["target_filepath"]
780 session["delid"] = cgi["delid"].to_s
781 db["delentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["delid"])
784 session["target_filepath"] = params["target_filepath"]
785 successed = Entry.delete(XMLPATH + File.basename(params["target_filepath"]), cgi["delid"].to_s)
787 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
788 params["mode"] = "error"
791 session["target_filepath"] = params["target_filepath"]
792 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["target_filepath"]))
793 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["target_filepath"]))
795 # Delete Diary - Default
796 session["target_filepath"] = session["filepath"]
797 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
798 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
803 case params["action"]
806 session["target_filepath"] = params["target_filepath"]
807 db["feed"] = Feed.new(params)
808 # 実際にFeed情報の変更をファイルに反映
810 session["target_filepath"] = params["target_filepath"]
811 db["feed"] = Feed.new(params)
813 session["target_filepath"] = params["target_filepath"]
814 Feed.update(XMLPATH + File.basename(params["target_filepath"]), Feed.new(params))
816 session["target_filepath"] = session["filepath"]
817 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
823 db["loglist"] = LogList.readxml(LISTXMLPATH)
824 case params["action"]
825 # ログファイルの編集を実際にファイルに反映
827 # エラーチェック。この段階のエラーは強度のエラーを発する。
828 db["loglist"].path.each do |val|
829 if val == cgi["logpath"]
830 # 重複していた場合エラーメッセージを表示し、処理を行わない
831 params["action"] = ""
832 params["mode"] = "error"
833 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。<br>環境を見直してください。"
839 db["loglist"].path[1, 0] = cgi["logpath"]
840 db["loglist"].display[1, 0] = cgi["logdisplay"]
842 # 既存のdiary.xmlを指定された名称でコピーして保存
843 FileUtils.copy_file(XMLPATH + File.basename(db["loglist"].path[0]), XMLPATH + File.basename(db["logpath"]), true)
845 db["loglist"] = LogList.readxml(LISTXMLPATH)
847 # 新たなdiary.xmlを生成。この際保持する情報は同一のFeedオブジェクトnew()
848 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), db["feed"], [])
852 db["loglist"].path.each do |val|
853 if val == cgi["logpath"]
854 # 重複していた場合エラーメッセージを表示し、処理を行わない
855 params["action"] = ""
856 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
861 db["logpath"] = cgi["logpath"]
862 db["logdisplay"] = cgi["logdisplay"]
864 if db["logpath"].blank? || db["logdisplay"].blank?
865 params["action"] = ""
871 db["logdelindex"] = params["logdelindex"].to_i
873 if db["logdelindex"] < 1
874 db["error"] = "<span style='color: #ff0000'>ログファイルの削除パラメタが不正です。</span><br>"
875 params["action"] = ""
879 if cgi["logdelindex"].to_i < 1
880 params["action"] = ""
881 params["mode"] = "error"
882 db["error"] = "ログファイルの削除中に重大なエラーが発生しました。<br>環境を見直してください。"
886 File.delete(XMLPATH + File.basename(db["loglist"].path[db["logdelindex"]]))
888 db["loglist"].path.delete_at(cgi["logdelindex"].to_i)
889 db["loglist"].display.delete_at(cgi["logdelindex"].to_i)
892 db["loglist"] = LogList.readxml(LISTXMLPATH)
898 db["logeditindex"] = params["logdelindex"].to_i
900 db["logpath"] = db["loglist"].path[db["logeditindex"]]
901 db["logdisplay"] = db["loglist"].display[db["logeditindex"]]
903 if db["logeditindex"] == 0
904 db["error"] = "<span style='color: #ff0000'>ログファイルの編集パラメタが不正です。</span><br>"
905 params["action"] = ""
910 db["loglist"].path.each_with_index do |val, i|
911 if db["logeditindex"] != i
912 if params["logpath"].to_s == db["loglist"].path[i].to_s
918 if checkflag == false
919 params["action"] = "edit"
920 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
922 db["loginsertindex"] = params["loginsertindex"].to_i
924 db["logpath"] = params["logpath"].to_s
925 db["logdisplay"] = params["logdisplay"].to_s
930 db["loglist"].path.each_with_index do |val, i|
931 if db["logeditindex"] != i
932 if params["logpath"].to_s == db["loglist"].path[i].to_s
938 if checkflag == false
939 params["action"] = ""
940 params["mode"] = "error"
941 db["error"] = "ログファイルの編集中に重大なエラーが発生しました。<br>環境を見直してください。"
944 db["loginsertindex"] = params["loginsertindex"].to_i
946 db["logpath"] = params["logpath"].to_s
947 db["logdisplay"] = params["logdisplay"].to_s
950 if XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]) != XMLPATH + File.basename(db["logpath"])
951 FileUtils.move(XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]), XMLPATH + File.basename(db["logpath"]))
953 db["loglist"].path.delete_at(db["logeditindex"])
954 db["loglist"].display.delete_at(db["logeditindex"])
955 db["loglist"].path.insert(db["loginsertindex"] + 1, db["logpath"])
956 db["loglist"].display.insert(db["loginsertindex"] + 1, db["logdisplay"])
963 # 現在編集中のデータを強制的に最上のファイルパスに変更
964 session["filepath"] = db["loglist"].path[0]
967 prevmonth = (DateTime.now << 1)
969 # 前月の時刻を元に、ディフォルト書式を生成します
970 db["logpath"] = FEEDXMLDIR + prevmonth.strftime("%Y%m") + ".xml"
971 db["logdisplay"] = prevmonth.strftime("%Y年%m月").gsub("年0", "年")
976 db["loglist"] = LogList.readxml(LISTXMLPATH)
980 case params["action"]
983 file = FileUploader.new
984 file.filelist().each { |fname|
985 file.delete(fname) if File.ftype(XMLPATH + fname) == "file"
990 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}diary.xml"], LISTXMLPATH)
993 db["loglist"] = LogList.readxml(LISTXMLPATH)
996 Feed.to_xml(XMLPATH + db["loglist"].path[0].match(/[^\/]*?$/).to_a[0], Feed.new({}), [])
998 # 初期の編集ファイルはloglist.xml上の最も上のファイル
999 session["filepath"] = db["loglist"].path[0]
1000 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1001 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1005 params["action"] = ""
1009 filelist = FileUploader.new.filelist()
1011 # タイプがファイルのみリストとして取得する
1013 filelist.each { |fname| db["filelist"] << fname if File.ftype(XMLPATH + fname) == "file"}
1018 # loglist.xmlが存在するかチェック
1019 if File.exist?(LISTXMLPATH) == false
1020 # なかった場合はloglist.xmlを自動生成
1021 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}diary.xml"], LISTXMLPATH)
1023 Feed.to_xml(XMLPATH + File.basename(loglist.path[0]), Feed.new({}), [])
1026 db["loglist"] = LogList.readxml(LISTXMLPATH)
1028 # diary.xmlが存在するかチェック
1029 if File.exist?(XMLPATH + File.basename(db["loglist"].path[0])) == false
1030 # なかった場合はdiary.xmlを自動生成
1031 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), Feed.new({}), [])
1034 # 初期の編集ファイルはloglist.xml上の最も上のファイル
1035 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1036 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1037 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1042 # マルチパートフォームの場合の処理です
1043 def Controller.MultiForm(cgi, session, params, db)
1045 # loglist.xmlをロードします
1046 db["loglist"] = LogList.readxml(LISTXMLPATH)
1050 case params["action"]
1052 # この段階のエラーに対しては強度のエラーを発する
1054 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1055 db["loglist"].path.each do |val|
1056 if val == db["logpath"]
1057 # 重複していた場合エラーメッセージを表示し、処理を行わない
1059 params["action"] = ""
1060 params["mode"] = "error"
1061 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1066 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1067 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1070 if db["loginsertindex"] == 0
1071 params["action"] = ""
1072 params["mode"] = "error"
1073 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1077 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank?
1078 params["action"] = ""
1079 params["mode"] = "error"
1080 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1085 file = FileUploader.new
1086 file.upload(db["logpath"], db["importxml"])
1089 db["loglist"].path[db["loginsertindex"], 0] = db["logpath"]
1090 db["loglist"].display[db["loginsertindex"], 0] = db["logdisplay"]
1091 db["loglist"].to_xml
1094 db["loglist"] = LogList.readxml(LISTXMLPATH)
1095 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1096 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1097 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1100 # 入力されたログファイルパスが既に存在するかを確認
1102 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1103 db["loglist"].path.each do |val|
1104 if val == db["logpath"]
1105 # 重複していた場合エラーメッセージを表示し、処理を行わない
1107 params["action"] = ""
1108 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1115 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1116 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1117 db["importxml"] = cgi["updata"].read
1121 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1123 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1124 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1125 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1126 db["error"] << "</div>"
1127 params["action"] = ""
1133 if db["loginsertindex"] == 0
1134 params["action"] = ""
1135 db["error"] = "<br><span style='color: #ff0000'>ラジオボックスでログの挿入位置を選択してください!</span><br>"
1139 if db["logpath"] == FEEDXMLDIR || db["logdisplay"].blank?
1140 params["action"] = ""
1141 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名は空欄にできません。</span><br>"
1150 case params["action"]
1152 # この段階のエラーに対しては強度のエラーを発する
1154 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1155 db["loglist"].path.each do |val|
1156 if val == db["logpath"]
1157 # 重複していた場合エラーメッセージを表示し、処理を行わない
1158 params["action"] = ""
1159 params["mode"] = "error"
1160 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1165 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1167 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank? || db["importxml"].blank?
1168 params["action"] = ""
1169 params["mode"] = "error"
1170 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1175 FileUtils.move(XMLPATH + "diary.xml", XMLPATH + File.basename(db["logpath"]))
1177 file = FileUploader.new
1178 file.upload("diary.xml", db["importxml"])
1181 db["loglist"].path[1, 0] = db["logpath"]
1182 db["loglist"].display[1, 0] = db["logdisplay"]
1183 db["loglist"].to_xml
1186 db["loglist"] = LogList.readxml(LISTXMLPATH)
1187 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1188 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1189 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1192 # 入力されたログファイルパスが既に存在するかを確認
1194 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1195 db["loglist"].path.each do |val|
1196 if val == db["logpath"]
1197 # 重複していた場合エラーメッセージを表示し、処理を行わない
1198 params["action"] = ""
1199 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1205 if checkflag == true
1206 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1207 db["importxml"] = cgi["updata"].read
1211 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1213 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1214 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1215 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1216 db["error"] << "</div>"
1217 params["action"] = ""
1222 if db["logpath"].blank? || db["logdisplay"].blank? || db["importxml"].blank?
1223 params["action"] = ""
1224 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名、ログのパスは空欄にできません。</span><br>"
1236 # Formのenctypeがmultypartだった場合、入力された値をrubyバージョンに左右されずに読み取るメソッドです。
1237 def Controller.get_mpart_value(cgi_param)
1238 if RUBY_VERSION >= "1.9.0"
1239 cgi_param[0..cgi_param.length].to_s
1245 # アップロードされたXMLをバージョンに左右されずに読み取るために、ruby-1.9.1以上ではエンコーディングを強制指定します
1246 def Controller.fix_updata_enc(file_to_s)
1247 if RUBY_VERSION >= "1.9.0"
1248 file_to_s.force_encoding("UTF-8")
1257 # SESSION変数、パラメータなどを取得します
1259 session = CGI::Session.new(cgi)
1260 params = Hash[*cgi.params.to_a.map{|k, v| [k, v[0].to_s]}.flatten]
1264 if session["login"] != "true"
1265 if (cgi["loginid"] == LOGINID && cgi["password"] == PASSWORD)
1266 session["login"] = "true"
1268 # ワークフォルダの中をクリーンアップします
1269 filelist = Dir::entries("./work")
1270 # 削除条件 : 最終変更日時から1日(60*60*24sec)かつ、ファイルタイプがファイルの場合
1271 filelist.each do |file|
1272 File.delete("./work/#{file}") if Time.now - File.ctime("./work/#{file}") > 86400 && File.ftype("./work/#{file}") == "file"
1278 if params["mode"] == "logout"
1279 session["login"] = nil
1280 session["logini"] = nil
1281 session["password"] = nil
1287 # セッションが有効な場合のも実行します
1288 if session["login"] == "true"
1291 db = PStore.new("./work/#{session.session_id}.dat")
1297 File.delete("./work/#{session.session_id}.dat")
1298 # PStoreが破損していた場合はセッション情報を破棄する
1299 session["login"] = nil
1300 session["logini"] = nil
1301 session["password"] = nil
1306 if cgi["mode"].respond_to?(:read) && cgi["action"].respond_to?(:read)
1307 params["mode"] = cgi["mode"].read
1308 params["action"] = cgi["action"].read
1309 Controller.MultiForm(cgi, session, params, db)
1311 Controller.NormalForm(cgi, session, params, db)
1314 # エラー画面移行時はセッション情報を破棄する
1315 if params["mode"] == "error"
1316 session["login"] = nil
1317 session["logini"] = nil
1318 session["password"] = nil
1323 # メニューとして表示されるHTML文字列です
1324 if params["target_filepath"].blank?
1325 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["filepath"]} "
1327 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["target_filepath"]} "
1329 if USEFILEMANAGER == true
1330 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>"
1332 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>"
1336 # modeとactionの相関図は以下のようになります。
1341 if session["login"] != "true"
1342 # セッションが存在しない場合は強制的にトップページに遷移
1343 htmlwriter = HtmlWriter.new("./erbtemp/login.html.erb", binding)
1347 htmlwriter = HtmlWriter.new("./erbtemp/select.html.erb", binding)
1349 htmlwriter = HtmlWriter.new("./erbtemp/newentry.html.erb", binding)
1351 htmlwriter = HtmlWriter.new("./erbtemp/editentry.html.erb", binding)
1353 htmlwriter = HtmlWriter.new("./erbtemp/delentry.html.erb", binding)
1355 htmlwriter = HtmlWriter.new("./erbtemp/editfeed.html.erb", binding)
1357 htmlwriter = HtmlWriter.new("./erbtemp/log.html.erb", binding)
1359 htmlwriter = HtmlWriter.new("./erbtemp/insertfeed.html.erb", binding)
1361 htmlwriter = HtmlWriter.new("./erbtemp/replacefeed.html.erb", binding)
1363 htmlwriter = HtmlWriter.new("./erbtemp/indeximport.html.erb", binding)
1365 htmlwriter = HtmlWriter.new("./erbtemp/reset.html.erb", binding)
1367 htmlwriter = HtmlWriter.new("./erbtemp/error.html.erb", binding)
1369 htmlwriter = HtmlWriter.new("./erbtemp/index.html.erb", binding)
1373 # エラーが発生した場合、それを画面に表示します
1374 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1379 cgi.out{htmlwriter.to_code}
1381 # エラーが発生した場合、それを画面に表示します
1382 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1383 cgi.out{htmlwriter.to_code}
1390 # エラーが発生した場合、それを画面に表示します
1391 detail = ("%s: %s (%s)\n" %
1392 [evar.backtrace[0], evar.message, evar.send('class')]) +
1393 evar.backtrace[1..-1].join("\n")
1394 puts "content-type: text/html\n\n<plaintext>\n" + detail