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("<title type=\"text\">#{@attr[:title]}</title>")
273 buf.push("<subtitle type=\"text\">#{@attr[:subtitle]}</subtitle>")
274 buf.push("<link rel=\"self\" type=\"application/atom+xml\" href=\"#{@attr[:self]}\" />")
275 buf.push("<link rel=\"alternate\" type=\"text/html\" href=\"#{@attr[:url]}\" />")
276 buf.push("<updated>#{Time.now.iso8601}</updated>")
277 buf.push("<id>#{@attr[:feedid]}</id>")
278 buf.push("<rights type=\"text\">#{@attr[:rights]}</rights>")
280 buf.push("\t<name>#{@attr[:aname]}</name>")
281 buf.push("\t<email>#{@attr[:amail]}</email>")
282 buf.push("</author>")
283 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
285 return buf.join("\n")
289 def self.update(path, feed)
290 entrylist = Entry.readxml(path)
291 Feed.to_xml(path, feed, entrylist)
298 # _feed_ :: Feedオブジェクト
299 # _entry_ :: Entryオブジェクトの配列
300 def self.to_xml(path, feed, entrylist_tmp)
302 entrylist = entrylist_tmp.dup
303 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
304 buf.push("#{feed.to_s}\n")
305 entrylist.each { |entry|
306 if REPLACEENTRYIDANDURL
307 entry.entryid.gsub!(/^[^\?]*\?/, "")
308 entry.entryid = feed.url + "?" + entry.entryid
309 entry.url = feed.url + "#" + entry.entryid
311 buf.push("#{entry.to_s}\n")
315 myopen(path, "w") do |f|
316 f.print buf.join("\n")
322 # _feed_ :: Feedオブジェクト
323 # _entry_ :: Entryオブジェクトの配列
324 def self.to_xml_plain(path, feed, entrylist)
326 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
327 buf.push("#{feed.to_s}\n")
328 entrylist.each { |entry|
329 buf.push("#{entry.to_s}\n")
333 myopen(path, "w") do |f|
334 f.print buf.join("\n")
342 # Entryの基礎情報を保有するクラスです
343 class Entry < AbstractEntry
346 # _hash_ :: 値を格納したhash配列。entry.new(CGI::Session.new(new CGI).params)のようにして使います。
352 @paramlist = ["entryid", "title", "summary", "published", "updated", "url", "content", "others"]
354 # AbstractEntryのinitializeメソッドを呼び出し、値を@attr配列に格納します
357 # 可視・不可視を示すハッシュキーを格納する配列です
358 @display = {"entryid" => "none", "title" => "",
359 "summary" => "", "published" => "none",
360 "updated" => "none", "url" => "none",
361 "content" => "", "others"=>"none"}
363 # デバッグモードの場合、全ての入力要素を表示します
365 @display.each do |key, val|
370 # ハッシュキーの日本語説明を格納する配列です
371 @name = {"entryid" => "記事固有のID", "title" => "記事のタイトル",
372 "summary" => "記事の簡単な説明", "published" => "記事の出版時刻",
373 "updated" => "記事の更新時刻", "url" => "記事へのURLアドレス",
374 "content" => "記事の本文", "others"=>"その他の項目"}
377 # Atom XMLファイルを読み込んで解析し、等価なEntryオブジェクト配列を返却するメソッドです
379 # _path_ :: Atom XMLファイルのパス
380 def self.readxml(path)
383 doc = REXML::Document.new(myopen(path, "r:utf-8"){|f|f.read})
387 # XML解析部分です。各element毎に判定を行います
388 doc.elements.each("feed/entry") do |elm|
391 elm.elements.each do |child|
395 xml[:entryid] = child.text
397 xml[:url] = child.attributes["href"]
398 when "title", "summary", "summary", "published", "updated", "content"
399 xml[child.name.to_sym] = child.text
401 # 上記判定以外の全要素は配列に格納します
402 others.push(child.to_s)
408 xml[:others] = others.join("\n")
409 entrylist.push(Entry.new(xml))
415 # Atom XMLファイルを読み込んで解析し、テンプレートファイルにしたがってHTMLに変換するメソッドです
416 def self.to_html(xmlpath, destpath, entry_temppath, html_temppath)
418 if xmlpath.empty? or destpath.empty? or entry_temppath.empty? or html_temppath.empty?
423 unless File.exist?(xmlpath) and File.exist?(entry_temppath) and File.exist?(html_temppath)
428 entrylist = Entry.readxml(xmlpath)
433 body << e.to_template(entry_temppath)
437 html_temp = HtmlWriter.new(html_temppath, binding)
440 myopen(destpath, 'w:utf-8') { |f|
441 f.write(CGI.pretty(html_temp.to_code))
445 # Entryをテンプレートに沿って変形するメソッド
446 def to_template(temppath)
447 erb = HtmlWriter.new(temppath, binding)
448 title = CGI.unescapeHTML(@attr[:title])
449 date = @attr[:published]
450 content = CGI.unescapeHTML(@attr[:content])
455 def self.insert(path, entry)
456 feed = Feed.readxml(path)
457 entrylist = Entry.readxml(path)
458 entrylist.unshift entry
460 Feed.to_xml(path, feed, entrylist)
466 def self.update(path, entry)
467 feed = Feed.readxml(path)
468 entrylist = Entry.readxml(path)
471 entrylist.each_with_index { |e, i|
472 if e.entryid == entry.entryid
477 Feed.to_xml(path, feed, entrylist) if successed
483 def self.select(path, entryid)
484 feed = Feed.readxml(path)
485 entrylist = Entry.readxml(path)
488 entrylist.each_with_index { |e, i|
489 entry = entrylist[i].dup if e.entryid == entryid
496 def self.delete(path, entryid)
497 feed = Feed.readxml(path)
498 entrylist = Entry.readxml(path)
502 entrylist.each_with_index { |e, i|
503 if e.entryid == entryid
510 entrylist.delete_at delete_index
511 Feed.to_xml(path, feed, entrylist)
517 # データソースから読み取ったHTMLを、エディタで編集可能な形式に変換するメソッドです
518 def content_for_generator
519 str = @attr[:content].dup
521 str.gsub!(/(<\/(?:p|h\d|div)(?:>|>))\n/i, '\1')
522 str.gsub!(/\n/, '<br>') if REPLACEBRTAG
523 str.gsub!(/(<(?:(?!>).)*?)#{Regexp.escape(FEEDXMLDIR)}/) { "#$1#{XMLPATH}" }
527 # エディタで編集されたCONTENT要素を、データソースに書き込める形式に変換するメソッドです
529 str = @attr[:content].dup
530 str = CGI.unescapeHTML(str)
532 str.gsub!(/(\r\n|\n)/, "")
533 str.gsub!(/<br>/i, "\n") if REPLACEBRTAG
534 str.gsub!(/(<br>|<\/p>|<\/h\d>|<\/div>)(?=[^\n])/i) { "#$1\n" } unless REPLACEBRTAG
535 str.gsub!(/(<[^>]*?)#{Regexp.escape(XMLPATH)}/) { "#$1#{FEEDXMLDIR}" }
539 # 確認画面で表示されるCONTENT要素を生成するメソッドです
541 str = @attr[:content].dup
542 str = CGI.unescapeHTML(str)
544 str.gsub!(/<br>/i, "\n") if REPLACEBRTAG
545 str.gsub!(/(<[^>]*?)#{Regexp.escape(FEEDXMLDIR)}/) { "#$1#{XMLPATH}" }
549 # 内部に保持している情報を、Atom Feed1.0形式の文字列に出力するメソッドです
553 buf.push("<id>#{@attr[:entryid]}</id>")
554 buf.push("<title>#{@attr[:title]}</title>")
555 buf.push("<summary>#{@attr[:summary]}</summary>")
556 buf.push("<published>#{@attr[:published]}</published>")
557 buf.push("<updated>#{@attr[:updated]}</updated>")
558 buf.push("<link href=\"#{@attr[:url]}\" />")
559 buf.push("<content type=\"html\">#{@attr[:content]}</content>")
560 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
563 return buf.join("\n")
569 # テンプレートファイル(*.erb)を読み込み、管理するクラスです
573 # _template_ :: テンプレートファイル(*.erb)のパス
574 # _binding_ :: binding変数
575 def initialize(template, binding)
576 @erb = ERB.new(myopen(template, "r:utf-8") {|f| f.read}, nil, "-")
580 # テンプレートファイルの文字列を返却するメソッドです
582 @erb.result(@binding)
588 # loglist.xmlにかかわる入出力を行います
592 # _display_ :: 画面表示用文字の配列
593 # _path_ :: XMLファイルパスの配列
594 # _logpath_ :: loglist.xmlのパス
595 def initialize(display, path, logpath)
601 attr_accessor :display, :path, :logpath
603 # loglist.xmlファイルを読み込んで解析し、LogListオブジェクトを返却するメソッドです
605 # _logpath_ :: loglist.xmlへのパス
606 def LogList.readxml(logpath)
610 myopen(logpath, "r:utf-8") { |f|
614 doc = REXML::Document.new(lines.join("\n"))
618 doc.elements.each("list/file") { |elm|
619 elm.elements.each {|child|
622 @display.push(child.text)
624 @path.push(child.text)
631 return LogList.new(@display, @path, logpath)
634 # loglist.xmlにオブジェクトの内容を反映するメソッドです
638 path.each_with_index do |path, i|
640 buf.push("<display>#{@display[i]}</display>")
641 buf.push("<path>#{@path[i]}</path>")
646 myopen(@logpath, "w") do |f|
647 f.print buf.join("\n")
661 # ファイルの一覧を取得し、ファイル名称を格納した配列を返却します
663 arr = Dir::entries(XMLPATH).sort
672 # _name_ :: 消去するファイル名
674 File.delete(XMLPATH + name.match(/[^\/]*?$/).to_a[0])
679 # _name_ :: アップロードファイルの名称
680 # _img_ :: アップロードファイル
681 def upload(name, img)
682 open(XMLPATH + File.basename(name), "w") do |f|
691 # コントローラ部分に相当する処理を受け持つクラスです
693 def Controller.NormalForm(cgi, session, params, db)
695 # modeとactionの相関図は以下のようになります。
703 session["filepath"] = params["logpath"]
704 db["loglist"] = LogList.readxml(LISTXMLPATH)
705 # 初期状態で選択されるログは「loglist.xml」の最上に位置するログになります
706 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
707 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
708 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
712 case params["action"]
715 session["target_filepath"] = params["target_filepath"]
716 db["newentry"] = Entry.new(params)
717 db["newentry"].content = db["newentry"].content_for_blog
720 session["target_filepath"] = params["target_filepath"]
721 successed = Entry.insert(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
723 db["error"] = "日記の新規追加に失敗しました。"
724 params["mode"] = "error"
728 session["target_filepath"] = params["target_filepath"]
729 db["newentry"] = Entry.new(params)
731 # New Diary - Default
732 session["target_filepath"] = session["filepath"]
733 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
734 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
739 case params["action"]
742 session["target_filepath"] = params["target_filepath"]
743 session["editid"] = cgi["editid"].to_s
744 db["editentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["editid"])
747 session["target_filepath"] = params["target_filepath"]
748 session["editid"] = cgi["editid"].to_s
749 db["editentry"] = Entry.new(params)
750 db["editentry"].content = db["editentry"].content_for_blog
753 session["target_filepath"] = params["target_filepath"]
754 successed = Entry.update(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
756 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
757 params["mode"] = "error"
760 session["target_filepath"] = params["target_filepath"]
761 db["editentry"] = Entry.new(params)
763 # Edit Diary - Default
764 session["target_filepath"] = session["filepath"]
765 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
766 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
771 case params["action"]
774 session["target_filepath"] = params["target_filepath"]
775 session["delid"] = cgi["delid"].to_s
776 db["delentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["delid"])
779 session["target_filepath"] = params["target_filepath"]
780 successed = Entry.delete(XMLPATH + File.basename(params["target_filepath"]), cgi["delid"].to_s)
782 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
783 params["mode"] = "error"
786 session["target_filepath"] = params["target_filepath"]
787 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["target_filepath"]))
788 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["target_filepath"]))
790 # Delete Diary - Default
791 session["target_filepath"] = session["filepath"]
792 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
793 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
798 case params["action"]
801 session["target_filepath"] = params["target_filepath"]
802 db["feed"] = Feed.new(params)
803 # 実際にFeed情報の変更をファイルに反映
805 session["target_filepath"] = params["target_filepath"]
806 db["feed"] = Feed.new(params)
808 session["target_filepath"] = params["target_filepath"]
809 Feed.update(XMLPATH + File.basename(params["target_filepath"]), Feed.new(params))
811 session["target_filepath"] = session["filepath"]
812 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
818 db["loglist"] = LogList.readxml(LISTXMLPATH)
819 case params["action"]
820 # ログファイルの編集を実際にファイルに反映
822 # エラーチェック。この段階のエラーは強度のエラーを発する。
823 db["loglist"].path.each do |val|
824 if val == cgi["logpath"]
825 # 重複していた場合エラーメッセージを表示し、処理を行わない
826 params["action"] = ""
827 params["mode"] = "error"
828 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。<br>環境を見直してください。"
834 db["loglist"].path[1, 0] = cgi["logpath"]
835 db["loglist"].display[1, 0] = cgi["logdisplay"]
837 # 既存のdiary.xmlを指定された名称でコピーして保存
838 FileUtils.copy_file(XMLPATH + File.basename(db["loglist"].path[0]), XMLPATH + File.basename(db["logpath"]), true)
840 db["loglist"] = LogList.readxml(LISTXMLPATH)
842 # 新たなdiary.xmlを生成。この際保持する情報は同一のFeedオブジェクトnew()
843 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), db["feed"], [])
847 db["loglist"].path.each do |val|
848 if val == cgi["logpath"]
849 # 重複していた場合エラーメッセージを表示し、処理を行わない
850 params["action"] = ""
851 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
856 db["logpath"] = cgi["logpath"]
857 db["logdisplay"] = cgi["logdisplay"]
859 if db["logpath"].blank? || db["logdisplay"].blank?
860 params["action"] = ""
866 db["logdelindex"] = params["logdelindex"].to_i
868 if db["logdelindex"] < 1
869 db["error"] = "<span style='color: #ff0000'>ログファイルの削除パラメタが不正です。</span><br>"
870 params["action"] = ""
874 if cgi["logdelindex"].to_i < 1
875 params["action"] = ""
876 params["mode"] = "error"
877 db["error"] = "ログファイルの削除中に重大なエラーが発生しました。<br>環境を見直してください。"
881 File.delete(XMLPATH + File.basename(db["loglist"].path[db["logdelindex"]]))
883 db["loglist"].path.delete_at(cgi["logdelindex"].to_i)
884 db["loglist"].display.delete_at(cgi["logdelindex"].to_i)
887 db["loglist"] = LogList.readxml(LISTXMLPATH)
893 db["logeditindex"] = params["logdelindex"].to_i
895 db["logpath"] = db["loglist"].path[db["logeditindex"]]
896 db["logdisplay"] = db["loglist"].display[db["logeditindex"]]
898 if db["logeditindex"] == 0
899 db["error"] = "<span style='color: #ff0000'>ログファイルの編集パラメタが不正です。</span><br>"
900 params["action"] = ""
905 db["loglist"].path.each_with_index do |val, i|
906 if db["logeditindex"] != i
907 if params["logpath"].to_s == db["loglist"].path[i].to_s
913 if checkflag == false
914 params["action"] = "edit"
915 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
917 db["loginsertindex"] = params["loginsertindex"].to_i
919 db["logpath"] = params["logpath"].to_s
920 db["logdisplay"] = params["logdisplay"].to_s
925 db["loglist"].path.each_with_index do |val, i|
926 if db["logeditindex"] != i
927 if params["logpath"].to_s == db["loglist"].path[i].to_s
933 if checkflag == false
934 params["action"] = ""
935 params["mode"] = "error"
936 db["error"] = "ログファイルの編集中に重大なエラーが発生しました。<br>環境を見直してください。"
939 db["loginsertindex"] = params["loginsertindex"].to_i
941 db["logpath"] = params["logpath"].to_s
942 db["logdisplay"] = params["logdisplay"].to_s
945 if XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]) != XMLPATH + File.basename(db["logpath"])
946 FileUtils.move(XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]), XMLPATH + File.basename(db["logpath"]))
948 db["loglist"].path.delete_at(db["logeditindex"])
949 db["loglist"].display.delete_at(db["logeditindex"])
950 db["loglist"].path.insert(db["loginsertindex"] + 1, db["logpath"])
951 db["loglist"].display.insert(db["loginsertindex"] + 1, db["logdisplay"])
958 # 現在編集中のデータを強制的に最上のファイルパスに変更
959 session["filepath"] = db["loglist"].path[0]
962 prevmonth = (DateTime.now << 1)
964 # 前月の時刻を元に、ディフォルト書式を生成します
965 db["logpath"] = FEEDXMLDIR + prevmonth.strftime("%Y%m") + ".xml"
966 db["logdisplay"] = prevmonth.strftime("%Y年%m月").gsub("年0", "年")
971 db["loglist"] = LogList.readxml(LISTXMLPATH)
975 case params["action"]
978 file = FileUploader.new
979 file.filelist().each { |fname|
980 file.delete(fname) if File.ftype(XMLPATH + fname) == "file"
985 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}diary.xml"], LISTXMLPATH)
988 db["loglist"] = LogList.readxml(LISTXMLPATH)
991 Feed.to_xml(XMLPATH + db["loglist"].path[0].match(/[^\/]*?$/).to_a[0], Feed.new({}), [])
993 # 初期の編集ファイルはloglist.xml上の最も上のファイル
994 session["filepath"] = db["loglist"].path[0]
995 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
996 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1000 params["action"] = ""
1004 filelist = FileUploader.new.filelist()
1006 # タイプがファイルのみリストとして取得する
1008 filelist.each { |fname| db["filelist"] << fname if File.ftype(XMLPATH + fname) == "file"}
1013 # loglist.xmlが存在するかチェック
1014 if File.exist?(LISTXMLPATH) == false
1015 # なかった場合はloglist.xmlを自動生成
1016 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}diary.xml"], LISTXMLPATH)
1018 Feed.to_xml(XMLPATH + File.basename(loglist.path[0]), Feed.new({}), [])
1021 db["loglist"] = LogList.readxml(LISTXMLPATH)
1023 # diary.xmlが存在するかチェック
1024 if File.exist?(XMLPATH + File.basename(db["loglist"].path[0])) == false
1025 # なかった場合はdiary.xmlを自動生成
1026 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), Feed.new({}), [])
1029 # 初期の編集ファイルはloglist.xml上の最も上のファイル
1030 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1031 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1032 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1037 # マルチパートフォームの場合の処理です
1038 def Controller.MultiForm(cgi, session, params, db)
1040 # loglist.xmlをロードします
1041 db["loglist"] = LogList.readxml(LISTXMLPATH)
1045 case params["action"]
1047 # この段階のエラーに対しては強度のエラーを発する
1049 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1050 db["loglist"].path.each do |val|
1051 if val == db["logpath"]
1052 # 重複していた場合エラーメッセージを表示し、処理を行わない
1054 params["action"] = ""
1055 params["mode"] = "error"
1056 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1061 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1062 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1065 if db["loginsertindex"] == 0
1066 params["action"] = ""
1067 params["mode"] = "error"
1068 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1072 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank?
1073 params["action"] = ""
1074 params["mode"] = "error"
1075 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1080 file = FileUploader.new
1081 file.upload(db["logpath"], db["importxml"])
1084 db["loglist"].path[db["loginsertindex"], 0] = db["logpath"]
1085 db["loglist"].display[db["loginsertindex"], 0] = db["logdisplay"]
1086 db["loglist"].to_xml
1089 db["loglist"] = LogList.readxml(LISTXMLPATH)
1090 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1091 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1092 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1095 # 入力されたログファイルパスが既に存在するかを確認
1097 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1098 db["loglist"].path.each do |val|
1099 if val == db["logpath"]
1100 # 重複していた場合エラーメッセージを表示し、処理を行わない
1102 params["action"] = ""
1103 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1110 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1111 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1112 db["importxml"] = cgi["updata"].read
1116 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1118 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1119 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1120 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1121 db["error"] << "</div>"
1122 params["action"] = ""
1128 if db["loginsertindex"] == 0
1129 params["action"] = ""
1130 db["error"] = "<br><span style='color: #ff0000'>ラジオボックスでログの挿入位置を選択してください!</span><br>"
1134 if db["logpath"] == FEEDXMLDIR || db["logdisplay"].blank?
1135 params["action"] = ""
1136 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名は空欄にできません。</span><br>"
1145 case params["action"]
1147 # この段階のエラーに対しては強度のエラーを発する
1149 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1150 db["loglist"].path.each do |val|
1151 if val == db["logpath"]
1152 # 重複していた場合エラーメッセージを表示し、処理を行わない
1153 params["action"] = ""
1154 params["mode"] = "error"
1155 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1160 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1162 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank? || db["importxml"].blank?
1163 params["action"] = ""
1164 params["mode"] = "error"
1165 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1170 FileUtils.move(XMLPATH + "diary.xml", XMLPATH + File.basename(db["logpath"]))
1172 file = FileUploader.new
1173 file.upload("diary.xml", db["importxml"])
1176 db["loglist"].path[1, 0] = db["logpath"]
1177 db["loglist"].display[1, 0] = db["logdisplay"]
1178 db["loglist"].to_xml
1181 db["loglist"] = LogList.readxml(LISTXMLPATH)
1182 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1183 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1184 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1187 # 入力されたログファイルパスが既に存在するかを確認
1189 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1190 db["loglist"].path.each do |val|
1191 if val == db["logpath"]
1192 # 重複していた場合エラーメッセージを表示し、処理を行わない
1193 params["action"] = ""
1194 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1200 if checkflag == true
1201 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1202 db["importxml"] = cgi["updata"].read
1206 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1208 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1209 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1210 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1211 db["error"] << "</div>"
1212 params["action"] = ""
1217 if db["logpath"].blank? || db["logdisplay"].blank? || db["importxml"].blank?
1218 params["action"] = ""
1219 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名、ログのパスは空欄にできません。</span><br>"
1231 # Formのenctypeがmultypartだった場合、入力された値をrubyバージョンに左右されずに読み取るメソッドです。
1232 def Controller.get_mpart_value(cgi_param)
1233 if RUBY_VERSION >= "1.9.0"
1234 cgi_param[0..cgi_param.length].to_s
1240 # アップロードされたXMLをバージョンに左右されずに読み取るために、ruby-1.9.1以上ではエンコーディングを強制指定します
1241 def Controller.fix_updata_enc(file_to_s)
1242 if RUBY_VERSION >= "1.9.0"
1243 file_to_s.force_encoding("UTF-8")
1252 # SESSION変数、パラメータなどを取得します
1254 session = CGI::Session.new(cgi)
1255 params = Hash[*cgi.params.to_a.map{|k, v| [k, v[0].to_s]}.flatten]
1259 if session["login"] != "true"
1260 if (cgi["loginid"] == LOGINID && cgi["password"] == PASSWORD)
1261 session["login"] = "true"
1263 # ワークフォルダの中をクリーンアップします
1264 filelist = Dir::entries("./work")
1265 # 削除条件 : 最終変更日時から1日(60*60*24sec)かつ、ファイルタイプがファイルの場合
1266 filelist.each do |file|
1267 File.delete("./work/#{file}") if Time.now - File.ctime("./work/#{file}") > 86400 && File.ftype("./work/#{file}") == "file"
1273 if params["mode"] == "logout"
1274 session["login"] = nil
1275 session["logini"] = nil
1276 session["password"] = nil
1282 # セッションが有効な場合のも実行します
1283 if session["login"] == "true"
1286 db = PStore.new("./work/#{session.session_id}.dat")
1292 File.delete("./work/#{session.session_id}.dat")
1293 # PStoreが破損していた場合はセッション情報を破棄する
1294 session["login"] = nil
1295 session["logini"] = nil
1296 session["password"] = nil
1301 if cgi["mode"].respond_to?(:read) && cgi["action"].respond_to?(:read)
1302 params["mode"] = cgi["mode"].read
1303 params["action"] = cgi["action"].read
1304 Controller.MultiForm(cgi, session, params, db)
1306 Controller.NormalForm(cgi, session, params, db)
1309 # エラー画面移行時はセッション情報を破棄する
1310 if params["mode"] == "error"
1311 session["login"] = nil
1312 session["logini"] = nil
1313 session["password"] = nil
1318 # メニューとして表示されるHTML文字列です
1319 if params["target_filepath"].blank?
1320 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["filepath"]} "
1322 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["target_filepath"]} "
1324 if USEFILEMANAGER == true
1325 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>"
1327 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>"
1331 # modeとactionの相関図は以下のようになります。
1336 if session["login"] != "true"
1337 # セッションが存在しない場合は強制的にトップページに遷移
1338 htmlwriter = HtmlWriter.new("./erbtemp/login.html.erb", binding)
1342 htmlwriter = HtmlWriter.new("./erbtemp/select.html.erb", binding)
1344 htmlwriter = HtmlWriter.new("./erbtemp/newentry.html.erb", binding)
1346 htmlwriter = HtmlWriter.new("./erbtemp/editentry.html.erb", binding)
1348 htmlwriter = HtmlWriter.new("./erbtemp/delentry.html.erb", binding)
1350 htmlwriter = HtmlWriter.new("./erbtemp/editfeed.html.erb", binding)
1352 htmlwriter = HtmlWriter.new("./erbtemp/log.html.erb", binding)
1354 htmlwriter = HtmlWriter.new("./erbtemp/insertfeed.html.erb", binding)
1356 htmlwriter = HtmlWriter.new("./erbtemp/replacefeed.html.erb", binding)
1358 htmlwriter = HtmlWriter.new("./erbtemp/indeximport.html.erb", binding)
1360 htmlwriter = HtmlWriter.new("./erbtemp/reset.html.erb", binding)
1362 htmlwriter = HtmlWriter.new("./erbtemp/error.html.erb", binding)
1364 htmlwriter = HtmlWriter.new("./erbtemp/index.html.erb", binding)
1368 # エラーが発生した場合、それを画面に表示します
1369 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1374 cgi.out{htmlwriter.to_code}
1376 # エラーが発生した場合、それを画面に表示します
1377 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1378 cgi.out{htmlwriter.to_code}
1385 # エラーが発生した場合、それを画面に表示します
1386 detail = ("%s: %s (%s)\n" %
1387 [evar.backtrace[0], evar.message, evar.send('class')]) +
1388 evar.backtrace[1..-1].join("\n")
1389 puts "content-type: text/html\n\n<plaintext>\n" + detail