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"
22 {:id => "login", :password => "password", :name => "テストユーザ"}
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 PLUGINDIR = "./plugins/"
49 INITIALXML = "diary.xml"
52 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>)"
54 APPTITLE = "FeedGenerator for Ruby version 2.0.0.0"
62 # ruby-1.9.x以降ではファイルを開いた際、エンコードの指定を行わないとエラーの原因になります。
63 # ただしruby-1.8.6以前はエンコードの指定に対応していないため、独自メソッドを定義してファイルの入出力を行います。
65 # _arg[0]_ :: 入出力を行うファイルのパス
66 # _arg[1]_ :: モードの指定。例 : w:utf-8(書き込みモード・UTF-8エンコードでファイルを開く)
72 arg[1] = mode[/[^:]+/] if RUBY_VERSION < "1.8.7" && mode.include?(':')
73 rdonly_p = /\A[^:]*[wa+]/ !~ mode
75 rdonly_p = !(mode & (IO::WRONY | IO::RDWR))
78 f.flock(rdonly_p ? File::LOCK_SH : File::LOCK_EX)
102 # = Feed/Entryのスーパークラス
104 # 入出力用のメソッドなど、共通する機能を提供します
108 # _hash_ :: 値を格納したhash配列。superfeed.new(CGI::Session.new(new CGI).params)のようにして使う。
114 @paramlist.each do |key|
115 val = hash[key.to_sym] || hash[key.to_s]
118 val.gsub!(/\r\n|\r/, "\n")
119 @attr[key.to_sym] = CGI.escapeHTML(val)
122 @attr[key.to_sym] = ""
126 # 可視・不可視を示すハッシュキーを格納する配列です
129 # ハッシュキーの日本語説明を格納する配列です
134 attr_reader :attr, :paramlist, :name, :display
136 # 内部の@attrハッシュにアクセスする手段を提供するメソッドです
138 # AbstractEntry.attr[:title]にアクセスしたい場合はAbstractEntry.titleで可能になります。
139 # AbstractEntry.send("title")という方法でもアクセス可能です。
140 def method_missing(methname, *args)
141 methname = methname.to_s
143 if methname[-1] == ?=
145 raise ArgumentError, "wrong number of arguments (#{args.length} for 1)" unless args.length == 1
147 methname = @paramlist.find{|par|par == methname}
148 return @attr[methname.to_sym] = args[0] if methname
151 raise ArgumentError, "wrong number of arguments (#{args.length} for 0)" unless args.empty?
152 return @attr[methname.to_sym] if @attr.key?(methname.to_sym)
154 # attr上にキーがない値を入れようとした場合はNoMethodError
163 @attr[key.to_sym] = value
169 # Feedの基礎情報を保有するクラスです
170 class Feed < AbstractEntry
173 # _hash_ :: 値を格納したhash配列。feed.new(CGI::Session.new(new CGI).params)のようにして使います。
179 @paramlist = ["feedattr", "title", "subtitle", "self", "url", "updated", "feedid", "rights", "aname", "amail", "others"]
181 # AbstractEntryのinitializeメソッドを呼び出し、値を@attr配列に格納します
184 # 可視・不可視を示すハッシュキーを格納する配列です
185 @display = {"feedattr" => "none", "title" => "", "subtitle" => "",
186 "self" => "", "url" => "",
187 "updated" => "none", "feedid" => "",
188 "rights" => "", "aname" => "",
189 "amail" => "", "others" => "none"}
191 # デバッグモードの場合、全ての入力要素を表示します
193 @display.each do |key, val|
198 # ハッシュキーの日本語説明を格納する配列です
199 @name = {"feedattr" => "feedの保持している属性", "title" => "ウェブページのタイトル", "subtitle" => "ウェブページの簡単な説明",
200 "self" => "このXMLファイルのURL", "url" => "ウェブページのURL",
201 "updated" => "XMLファイルの最終更新日", "feedid" => "あなたのページ独自のID",
202 "rights" => "ページの著作権表記", "aname" => "ページの製作者",
203 "amail" => "ページ製作者のメールアドレス", "others" => "その他の要素"}
207 # Atom XMLファイルを読み込んで解析し、等価なFeedオブジェクトを返却するメソッドです
209 # _path_ :: Atom XMLファイルのパス
210 def self.readxml(path)
213 doc = REXML::Document.new(myopen(path, "r:utf-8"){|f|f.read})
219 doc.elements["feed"].attributes.each_attribute do |attr|
220 xmlattr.push("#{attr.to_string} ")
222 xml[:feedattr] = xmlattr.join("\n").gsub(/"/, "'")
224 # XML解析部分です。各element毎に判定を行います
225 doc.elements.each("feed") do |elm|
226 elm.elements.each { |child|
230 xml[:feedid] = child.text
231 when "title", "subtitle", "updated", "rights"
232 xml[child.name.to_sym] = child.text
234 child.elements.each do |gchild|
237 xml[:aname] = gchild.text
239 xml[:amail] = gchild.text
243 child.attributes.each do |k, v|
246 xml[:self] = child.attributes["href"]
247 elsif v == "alternate"
248 xml[:url] = child.attributes["href"]
255 # 上記判定以外の全要素は配列に格納します
256 others.push(child.to_s)
265 xml[:others] = others.join("\n")
270 # 内部に保持している情報を、Atom Feed1.0形式の文字列に出力するメソッドです
274 # buf.push("<feed #{@attr[:feedattr]}>")
275 buf.push("<feed xml:lang='ja-jp' xmlns='http://www.w3.org/2005/Atom'>");
276 buf.push("<title type=\"text\">#{@attr[:title]}</title>")
277 buf.push("<subtitle type=\"text\">#{@attr[:subtitle]}</subtitle>")
278 buf.push("<link rel=\"self\" type=\"application/atom+xml\" href=\"#{@attr[:self]}\" />")
279 buf.push("<link rel=\"alternate\" type=\"text/html\" href=\"#{@attr[:url]}\" />")
280 buf.push("<updated>#{Time.now.iso8601}</updated>")
281 buf.push("<id>#{@attr[:feedid]}</id>")
282 buf.push("<rights type=\"text\">#{@attr[:rights]}</rights>")
284 buf.push("\t<name>#{@attr[:aname]}</name>")
285 buf.push("\t<email>#{@attr[:amail]}</email>")
286 buf.push("</author>")
287 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
289 return buf.join("\n")
293 def self.update(path, feed)
294 entrylist = Entry.readxml(path)
295 Feed.to_xml(path, feed, entrylist)
302 # _feed_ :: Feedオブジェクト
303 # _entry_ :: Entryオブジェクトの配列
304 def self.to_xml(path, feed, entrylist_tmp)
306 entrylist = entrylist_tmp.dup
307 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
308 buf.push("#{feed.to_s}\n")
309 entrylist.each { |entry|
310 if REPLACEENTRYIDANDURL
311 entry.entryid.gsub!(/^[^\?]*\?/, "")
312 entry.entryid = feed.url + "?" + entry.entryid
313 entry.url = feed.url + "#" + entry.entryid
315 buf.push("#{entry.to_s}\n")
319 myopen(path, "w") do |f|
320 f.print buf.join("\n")
326 # _feed_ :: Feedオブジェクト
327 # _entry_ :: Entryオブジェクトの配列
328 def self.to_xml_plain(path, feed, entrylist)
330 buf.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
331 buf.push("#{feed.to_s}\n")
332 entrylist.each { |entry|
333 buf.push("#{entry.to_s}\n")
337 myopen(path, "w") do |f|
338 f.print buf.join("\n")
346 # Entryの基礎情報を保有するクラスです
347 class Entry < AbstractEntry
350 # _hash_ :: 値を格納したhash配列。entry.new(CGI::Session.new(new CGI).params)のようにして使います。
356 @paramlist = ["entryid", "title", "summary", "published", "updated", "url", "content", "others"]
358 # AbstractEntryのinitializeメソッドを呼び出し、値を@attr配列に格納します
361 # 可視・不可視を示すハッシュキーを格納する配列です
362 @display = {"entryid" => "none", "title" => "",
363 "summary" => "", "published" => "none",
364 "updated" => "none", "url" => "",
365 "content" => "", "others"=>"none"}
367 # デバッグモードの場合、全ての入力要素を表示します
369 @display.each do |key, val|
374 # ハッシュキーの日本語説明を格納する配列です
375 @name = {"entryid" => "記事固有のID", "title" => "記事のタイトル",
376 "summary" => "記事の簡単な説明", "published" => "記事の出版時刻",
377 "updated" => "記事の更新時刻", "url" => "記事へのURLアドレス",
378 "content" => "記事の本文", "others"=>"その他の項目"}
381 # Atom XMLファイルを読み込んで解析し、等価なEntryオブジェクト配列を返却するメソッドです
383 # _path_ :: Atom XMLファイルのパス
384 def self.readxml(path)
387 doc = REXML::Document.new(myopen(path, "r:utf-8"){|f|f.read})
391 # XML解析部分です。各element毎に判定を行います
392 doc.elements.each("feed/entry") do |elm|
395 elm.elements.each do |child|
399 xml[:entryid] = child.text
401 xml[:url] = child.attributes["href"]
402 when "title", "summary", "summary", "published", "updated", "content"
403 xml[child.name.to_sym] = child.text
405 # 上記判定以外の全要素は配列に格納します
406 others.push(child.to_s)
412 xml[:others] = others.join("\n")
413 entrylist.push(Entry.new(xml))
419 # Atom XMLファイルを読み込んで解析し、テンプレートファイルにしたがってHTMLに変換するメソッドです
420 def self.to_html(xmlpath, destpath, entry_temppath, html_temppath)
422 if xmlpath.empty? or destpath.empty? or entry_temppath.empty? or html_temppath.empty?
427 unless File.exist?(xmlpath) and File.exist?(entry_temppath) and File.exist?(html_temppath)
432 entrylist = Entry.readxml(xmlpath)
437 body << e.to_template(entry_temppath)
441 html_temp = HtmlWriter.new(html_temppath, binding)
444 myopen(destpath, 'w:utf-8') { |f|
445 f.write(CGI.pretty(html_temp.to_code))
449 # Entryをテンプレートに沿って変形するメソッド
450 def to_template(temppath)
451 erb = HtmlWriter.new(temppath, binding)
452 title = CGI.unescapeHTML(@attr[:title])
453 date = @attr[:published]
454 content = CGI.unescapeHTML(@attr[:content])
459 def self.insert(path, entry)
460 feed = Feed.readxml(path)
461 entrylist = Entry.readxml(path)
462 entrylist.unshift entry
464 Feed.to_xml(path, feed, entrylist)
470 def self.update(path, entry)
471 feed = Feed.readxml(path)
472 entrylist = Entry.readxml(path)
475 entrylist.each_with_index { |e, i|
476 if e.entryid == entry.entryid
481 Feed.to_xml(path, feed, entrylist) if successed
487 def self.select(path, entryid)
488 feed = Feed.readxml(path)
489 entrylist = Entry.readxml(path)
492 entrylist.each_with_index { |e, i|
493 entry = entrylist[i].dup if e.entryid == entryid
500 def self.delete(path, entryid)
501 feed = Feed.readxml(path)
502 entrylist = Entry.readxml(path)
506 entrylist.each_with_index { |e, i|
507 if e.entryid == entryid
514 entrylist.delete_at delete_index
515 Feed.to_xml(path, feed, entrylist)
521 # データソースから読み取ったHTMLを、エディタで編集可能な形式に変換するメソッドです
522 def content_for_generator
523 str = @attr[:content].dup
525 str.gsub!(/(<\/(?:p|h\d|div)(?:>|>))\n/i, '\1')
526 str.gsub!(/\n/, '<br>') if REPLACEBRTAG
527 str.gsub!(/(<(?:(?!>).)*?)#{Regexp.escape(RELAYPATH)}/) { "#$1#{HOMEBASE}" }
531 # エディタで編集されたCONTENT要素を、データソースに書き込める形式に変換するメソッドです
533 str = @attr[:content].dup
534 str = CGI.unescapeHTML(str)
536 str.gsub!(/(\r\n|\n)/, "")
537 str.gsub!(/<br>|<br[ ]*\/>/i, "\n") if REPLACEBRTAG
538 str.gsub!(/(<br>|<br[ ]*\/>|<\/p>|<\/h\d>|<\/div>)(?=[^\n])/i) { "#$1\n" } unless REPLACEBRTAG
539 str.gsub!(/(<[^>]*?)#{Regexp.escape(HOMEBASE)}/) { "#$1#{RELAYPATH}" }
543 # 確認画面で表示されるCONTENT要素を生成するメソッドです
545 str = @attr[:content].dup
546 str = CGI.unescapeHTML(str)
548 str.gsub!(/<br>|<br[ ]*\/>/i, "\n") if REPLACEBRTAG
549 str.gsub!(/(<[^>]*?)#{Regexp.escape(RELAYPATH)}/) { "#$1#{HOMEBASE}" }
553 # 内部に保持している情報を、Atom Feed1.0形式の文字列に出力するメソッドです
557 buf.push("<id>#{@attr[:entryid]}</id>")
558 buf.push("<title>#{@attr[:title]}</title>")
559 buf.push("<summary>#{@attr[:summary]}</summary>")
560 buf.push("<published>#{@attr[:published]}</published>")
561 buf.push("<updated>#{@attr[:updated]}</updated>")
562 buf.push("<link href=\"#{@attr[:url]}\" />")
563 buf.push("<content type=\"html\">#{@attr[:content]}</content>")
564 buf.push("#{CGI.unescapeHTML(@attr[:others])}") if @attr[:others] != ""
567 return buf.join("\n")
573 # テンプレートファイル(*.erb)を読み込み、管理するクラスです
577 # _template_ :: テンプレートファイル(*.erb)のパス
578 # _binding_ :: binding変数
579 def initialize(template, binding)
580 @erb = ERB.new(myopen(template, "r:utf-8") {|f| f.read}, nil, "-")
584 # テンプレートファイルの文字列を返却するメソッドです
586 @erb.result(@binding)
592 # loglist.xmlにかかわる入出力を行います
596 # _display_ :: 画面表示用文字の配列
597 # _path_ :: XMLファイルパスの配列
598 # _logpath_ :: loglist.xmlのパス
599 def initialize(display, path, logpath)
605 attr_accessor :display, :path, :logpath
607 # loglist.xmlファイルを読み込んで解析し、LogListオブジェクトを返却するメソッドです
609 # _logpath_ :: loglist.xmlへのパス
610 def LogList.readxml(logpath)
614 myopen(logpath, "r:utf-8") { |f|
618 doc = REXML::Document.new(lines.join("\n"))
622 doc.elements.each("list/file") { |elm|
623 elm.elements.each {|child|
626 @display.push(child.text)
628 @path.push(child.text)
635 return LogList.new(@display, @path, logpath)
638 # loglist.xmlにオブジェクトの内容を反映するメソッドです
642 path.each_with_index do |path, i|
644 buf.push("<display>#{@display[i]}</display>")
645 buf.push("<path>#{@path[i]}</path>")
650 myopen(@logpath, "w") do |f|
651 f.print buf.join("\n")
665 # ファイルの一覧を取得し、ファイル名称を格納した配列を返却します
667 arr = Dir::entries(XMLPATH).sort
676 # _name_ :: 消去するファイル名
678 File.delete(XMLPATH + name.match(/[^\/]*?$/).to_a[0])
683 # _name_ :: アップロードファイルの名称
684 # _img_ :: アップロードファイル
685 def upload(name, img)
686 open(XMLPATH + File.basename(name), "w") do |f|
696 class FeedGenPluginManager
697 def self.exec(mode, filepath)
698 feed = Feed.readxml(XMLPATH + filepath)
699 entries = Entry.readxml(XMLPATH + filepath)
702 Dir.foreach(PLUGINDIR) do |fn|
703 next unless File.extname(fn) == '.rb'
704 require File.join(PLUGINDIR, fn)
705 plugin_name = "FeedGenPlugins::"
706 plugin_name << File.basename(fn).gsub(/\.rb\Z/, "")
707 plugin_ins = plugin_name.split(/::/).inject(Object) { |c,name| c.const_get(name) }
708 plugin_ins.new.exec(mode, feed, entries)
715 # コントローラ部分に相当する処理を受け持つクラスです
717 def Controller.NormalForm(cgi, session, params, db)
719 # modeとactionの相関図は以下のようになります。
727 session["filepath"] = params["logpath"]
728 db["loglist"] = LogList.readxml(LISTXMLPATH)
729 # 初期状態で選択されるログは「loglist.xml」の最上に位置するログになります
730 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
731 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
732 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
736 case params["action"]
739 session["target_filepath"] = params["target_filepath"]
740 db["newentry"] = Entry.new(params)
741 db["newentry"].content = db["newentry"].content_for_blog
744 session["target_filepath"] = params["target_filepath"]
745 successed = Entry.insert(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
747 db["error"] = "日記の新規追加に失敗しました。"
748 params["mode"] = "error"
751 FeedGenPluginManager.exec("newentry", File.basename(session["filepath"]))
755 session["target_filepath"] = params["target_filepath"]
756 db["newentry"] = Entry.new(params)
758 # New Diary - Default
759 session["target_filepath"] = session["filepath"]
760 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
761 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
766 case params["action"]
769 session["target_filepath"] = params["target_filepath"]
770 session["editid"] = cgi["editid"].to_s
771 db["editentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["editid"])
774 session["target_filepath"] = params["target_filepath"]
775 session["editid"] = cgi["editid"].to_s
776 db["editentry"] = Entry.new(params)
777 db["editentry"].content = db["editentry"].content_for_blog
780 session["target_filepath"] = params["target_filepath"]
781 successed = Entry.update(XMLPATH + File.basename(params["target_filepath"]), Entry.new(params))
783 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
784 params["mode"] = "error"
787 FeedGenPluginManager.exec("editentry", File.basename(session["filepath"]))
790 session["target_filepath"] = params["target_filepath"]
791 db["editentry"] = Entry.new(params)
793 # Edit Diary - Default
794 session["target_filepath"] = session["filepath"]
795 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
796 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
801 case params["action"]
804 session["target_filepath"] = params["target_filepath"]
805 session["delid"] = cgi["delid"].to_s
806 db["delentry"] = Entry.select(XMLPATH + File.basename(session["target_filepath"]), session["delid"])
809 session["target_filepath"] = params["target_filepath"]
810 successed = Entry.delete(XMLPATH + File.basename(params["target_filepath"]), cgi["delid"].to_s)
812 db["error"] = "日記の編集処理に失敗しました。<br>該当の日記が既に存在しない可能性があります。"
813 params["mode"] = "error"
816 FeedGenPluginManager.exec("delentry", File.basename(session["filepath"]))
819 session["target_filepath"] = params["target_filepath"]
820 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["target_filepath"]))
821 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["target_filepath"]))
823 # Delete Diary - Default
824 session["target_filepath"] = session["filepath"]
825 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
826 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
831 case params["action"]
834 session["target_filepath"] = params["target_filepath"]
835 db["feed"] = Feed.new(params)
836 # 実際にFeed情報の変更をファイルに反映
838 session["target_filepath"] = params["target_filepath"]
839 db["feed"] = Feed.new(params)
841 session["target_filepath"] = params["target_filepath"]
842 Feed.update(XMLPATH + File.basename(params["target_filepath"]), Feed.new(params))
844 session["target_filepath"] = session["filepath"]
845 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
851 db["loglist"] = LogList.readxml(LISTXMLPATH)
852 case params["action"]
853 # ログファイルの編集を実際にファイルに反映
855 # エラーチェック。この段階のエラーは強度のエラーを発する。
856 db["loglist"].path.each do |val|
857 if val == cgi["logpath"]
858 # 重複していた場合エラーメッセージを表示し、処理を行わない
859 params["action"] = ""
860 params["mode"] = "error"
861 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。<br>環境を見直してください。"
867 db["loglist"].path[1, 0] = cgi["logpath"]
868 db["loglist"].display[1, 0] = cgi["logdisplay"]
870 # 既存のdiary.xmlを指定された名称でコピーして保存
871 FileUtils.copy_file(XMLPATH + File.basename(db["loglist"].path[0]), XMLPATH + File.basename(db["logpath"]), true)
873 db["loglist"] = LogList.readxml(LISTXMLPATH)
875 # 新たなdiary.xmlを生成。この際保持する情報は同一のFeedオブジェクトnew()
876 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), db["feed"], [])
880 db["loglist"].path.each do |val|
881 if val == cgi["logpath"]
882 # 重複していた場合エラーメッセージを表示し、処理を行わない
883 params["action"] = ""
884 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
889 db["logpath"] = cgi["logpath"]
890 db["logdisplay"] = cgi["logdisplay"]
892 if db["logpath"].blank? || db["logdisplay"].blank?
893 params["action"] = ""
899 db["logdelindex"] = params["logdelindex"].to_i
901 if db["logdelindex"] < 1
902 db["error"] = "<span style='color: #ff0000'>ログファイルの削除パラメタが不正です。</span><br>"
903 params["action"] = ""
907 if cgi["logdelindex"].to_i < 1
908 params["action"] = ""
909 params["mode"] = "error"
910 db["error"] = "ログファイルの削除中に重大なエラーが発生しました。<br>環境を見直してください。"
914 File.delete(XMLPATH + File.basename(db["loglist"].path[db["logdelindex"]]))
916 db["loglist"].path.delete_at(cgi["logdelindex"].to_i)
917 db["loglist"].display.delete_at(cgi["logdelindex"].to_i)
920 db["loglist"] = LogList.readxml(LISTXMLPATH)
926 db["logeditindex"] = params["logdelindex"].to_i
928 db["logpath"] = db["loglist"].path[db["logeditindex"]]
929 db["logdisplay"] = db["loglist"].display[db["logeditindex"]]
931 if db["logeditindex"] == 0
932 db["error"] = "<span style='color: #ff0000'>ログファイルの編集パラメタが不正です。</span><br>"
933 params["action"] = ""
938 db["loglist"].path.each_with_index do |val, i|
939 if db["logeditindex"] != i
940 if params["logpath"].to_s == db["loglist"].path[i].to_s
946 if checkflag == false
947 params["action"] = "edit"
948 db["error"] = "<span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
950 db["loginsertindex"] = params["loginsertindex"].to_i
952 db["logpath"] = params["logpath"].to_s
953 db["logdisplay"] = params["logdisplay"].to_s
958 db["loglist"].path.each_with_index do |val, i|
959 if db["logeditindex"] != i
960 if params["logpath"].to_s == db["loglist"].path[i].to_s
966 if checkflag == false
967 params["action"] = ""
968 params["mode"] = "error"
969 db["error"] = "ログファイルの編集中に重大なエラーが発生しました。<br>環境を見直してください。"
972 db["loginsertindex"] = params["loginsertindex"].to_i
974 db["logpath"] = params["logpath"].to_s
975 db["logdisplay"] = params["logdisplay"].to_s
978 if XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]) != XMLPATH + File.basename(db["logpath"])
979 FileUtils.move(XMLPATH + File.basename(db["loglist"].path[db["logeditindex"]]), XMLPATH + File.basename(db["logpath"]))
981 db["loglist"].path.delete_at(db["logeditindex"])
982 db["loglist"].display.delete_at(db["logeditindex"])
983 db["loglist"].path.insert(db["loginsertindex"] + 1, db["logpath"])
984 db["loglist"].display.insert(db["loginsertindex"] + 1, db["logdisplay"])
991 # 現在編集中のデータを強制的に最上のファイルパスに変更
992 session["filepath"] = db["loglist"].path[0]
995 prevmonth = (DateTime.now << 1)
997 # 前月の時刻を元に、ディフォルト書式を生成します
998 db["logpath"] = FEEDXMLDIR + prevmonth.strftime("%Y%m") + ".xml"
999 db["logdisplay"] = prevmonth.strftime("%Y年%m月").gsub("年0", "年")
1004 db["loglist"] = LogList.readxml(LISTXMLPATH)
1008 case params["action"]
1011 file = FileUploader.new
1012 file.filelist().each { |fname|
1013 file.delete(fname) if File.ftype(XMLPATH + fname) == "file"
1018 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}#{INITIALXML}"], LISTXMLPATH)
1021 db["loglist"] = LogList.readxml(LISTXMLPATH)
1024 Feed.to_xml(XMLPATH + db["loglist"].path[0].match(/[^\/]*?$/).to_a[0], Feed.new({}), [])
1026 # 初期の編集ファイルはloglist.xml上の最も上のファイル
1027 session["filepath"] = db["loglist"].path[0]
1028 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1029 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1033 params["action"] = ""
1037 filelist = FileUploader.new.filelist()
1039 # タイプがファイルのみリストとして取得する
1041 filelist.each { |fname| db["filelist"] << fname if File.ftype(XMLPATH + fname) == "file"}
1046 # loglist.xmlが存在するかチェック
1047 if File.exist?(LISTXMLPATH) == false
1048 # なかった場合はloglist.xmlを自動生成
1049 loglist = LogList.new(["最新の記事"], ["#{FEEDXMLDIR}#{INITIALXML}"], LISTXMLPATH)
1051 Feed.to_xml(XMLPATH + File.basename(loglist.path[0]), Feed.new({}), [])
1054 db["loglist"] = LogList.readxml(LISTXMLPATH)
1056 # diary.xmlが存在するかチェック
1057 if File.exist?(XMLPATH + File.basename(db["loglist"].path[0])) == false
1058 # なかった場合はdiary.xmlを自動生成
1059 Feed.to_xml(XMLPATH + File.basename(db["loglist"].path[0]), Feed.new({}), [])
1062 # 初期の編集ファイルはloglist.xml上の最も上のファイル
1063 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1064 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1065 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1070 # マルチパートフォームの場合の処理です
1071 def Controller.MultiForm(cgi, session, params, db)
1073 # loglist.xmlをロードします
1074 db["loglist"] = LogList.readxml(LISTXMLPATH)
1078 case params["action"]
1080 # この段階のエラーに対しては強度のエラーを発する
1082 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1083 db["loglist"].path.each do |val|
1084 if val == db["logpath"]
1085 # 重複していた場合エラーメッセージを表示し、処理を行わない
1087 params["action"] = ""
1088 params["mode"] = "error"
1089 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1094 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1095 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1098 if db["loginsertindex"] == 0
1099 params["action"] = ""
1100 params["mode"] = "error"
1101 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1105 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank?
1106 params["action"] = ""
1107 params["mode"] = "error"
1108 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1113 file = FileUploader.new
1114 file.upload(db["logpath"], db["importxml"])
1117 db["loglist"].path[db["loginsertindex"], 0] = db["logpath"]
1118 db["loglist"].display[db["loginsertindex"], 0] = db["logdisplay"]
1119 db["loglist"].to_xml
1122 db["loglist"] = LogList.readxml(LISTXMLPATH)
1123 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1124 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1125 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1128 # 入力されたログファイルパスが既に存在するかを確認
1130 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1131 db["loglist"].path.each do |val|
1132 if val == db["logpath"]
1133 # 重複していた場合エラーメッセージを表示し、処理を行わない
1135 params["action"] = ""
1136 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1143 db["loginsertindex"] = cgi["loginsertindex"].read.to_i
1144 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1145 db["importxml"] = cgi["updata"].read
1149 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1151 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1152 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1153 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1154 db["error"] << "</div>"
1155 params["action"] = ""
1161 if db["loginsertindex"] == 0
1162 params["action"] = ""
1163 db["error"] = "<br><span style='color: #ff0000'>ラジオボックスでログの挿入位置を選択してください!</span><br>"
1167 if db["logpath"] == FEEDXMLDIR || db["logdisplay"].blank?
1168 params["action"] = ""
1169 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名は空欄にできません。</span><br>"
1178 case params["action"]
1180 # この段階のエラーに対しては強度のエラーを発する
1182 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1183 db["loglist"].path.each do |val|
1184 if val == db["logpath"]
1185 # 重複していた場合エラーメッセージを表示し、処理を行わない
1186 params["action"] = ""
1187 params["mode"] = "error"
1188 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1193 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1195 if File.basename(db["logpath"]).blank? || db["logdisplay"].blank? || db["importxml"].blank?
1196 params["action"] = ""
1197 params["mode"] = "error"
1198 db["error"] = "ログファイルの追加中に重大なエラーが発生しました。"
1203 FileUtils.move(XMLPATH + INITIALXML, XMLPATH + File.basename(db["logpath"]))
1205 file = FileUploader.new
1206 file.upload(INITIALXML, db["importxml"])
1209 db["loglist"].path[1, 0] = db["logpath"]
1210 db["loglist"].display[1, 0] = db["logdisplay"]
1211 db["loglist"].to_xml
1214 db["loglist"] = LogList.readxml(LISTXMLPATH)
1215 session["filepath"] = db["loglist"].path[0] if session["filepath"] == nil
1216 db["feed"] = Feed.readxml(XMLPATH + File.basename(session["filepath"]))
1217 db["entry"] = Entry.readxml(XMLPATH + File.basename(session["filepath"]))
1220 # 入力されたログファイルパスが既に存在するかを確認
1222 db["logpath"] = Controller.get_mpart_value(cgi["logpath"])
1223 db["loglist"].path.each do |val|
1224 if val == db["logpath"]
1225 # 重複していた場合エラーメッセージを表示し、処理を行わない
1226 params["action"] = ""
1227 db["error"] = "<br><span style='color: #ff0000'>同一のファイルが存在します!別の名前を指定してください。</span><br>"
1233 if checkflag == true
1234 db["logdisplay"] = Controller.get_mpart_value(cgi["logdisplay"])
1235 db["importxml"] = cgi["updata"].read
1239 REXML::Document.new(Controller.fix_updata_enc(db["importxml"].to_s))
1241 db["error"] = "<br><span style='color: #ff0000'>不正な整形のXMLです!ファイルを見直してください。</span><br>"
1242 db["error"] << "<div class='divstyle' style='width: 560px; color: #ff0000; text-align: left;'>"
1243 db["error"] << CGI.escapeHTML(exception.to_s).gsub("\n", "<br>")
1244 db["error"] << "</div>"
1245 params["action"] = ""
1250 if db["logpath"].blank? || db["logdisplay"].blank? || db["importxml"].blank?
1251 params["action"] = ""
1252 db["error"] = "<br><span style='color: #ff0000'>インポートファイル、及び、ログの表示名、ログのパスは空欄にできません。</span><br>"
1264 # Formのenctypeがmultypartだった場合、入力された値をrubyバージョンに左右されずに読み取るメソッドです。
1265 def Controller.get_mpart_value(cgi_param)
1266 if RUBY_VERSION >= "1.9.0"
1267 cgi_param[0..cgi_param.length].to_s
1273 # アップロードされたXMLをバージョンに左右されずに読み取るために、ruby-1.9.1以上ではエンコーディングを強制指定します
1274 def Controller.fix_updata_enc(file_to_s)
1275 if RUBY_VERSION >= "1.9.0"
1276 file_to_s.force_encoding("UTF-8")
1285 # SESSION変数、パラメータなどを取得します
1287 session = CGI::Session.new(cgi)
1288 params = Hash[*cgi.params.to_a.map{|k, v| [k, v[0].to_s]}.flatten]
1292 if session["login"] != "true"
1296 if (cgi["loginid"] == h[:id] && cgi["password"] == h[:password])
1297 session["login"] = "true"
1298 session["name"] = h[:name]
1303 if (session["login"] == "true")
1304 # ワークフォルダの中をクリーンアップします
1305 filelist = Dir::entries("./work")
1306 # 削除条件 : 最終変更日時から1日(60*60*24sec)かつ、ファイルタイプがファイルの場合
1307 filelist.each do |file|
1308 File.delete("./work/#{file}") if Time.now - File.ctime("./work/#{file}") > 86400 && File.ftype("./work/#{file}") == "file"
1314 if params["mode"] == "logout"
1315 session["login"] = nil
1321 # セッションが有効な場合のも実行します
1322 if session["login"] == "true"
1325 db = PStore.new("./work/#{session.session_id}.dat")
1331 File.delete("./work/#{session.session_id}.dat")
1332 # PStoreが破損していた場合はセッション情報を破棄する
1333 session["login"] = nil
1338 if cgi["mode"].respond_to?(:read) && cgi["action"].respond_to?(:read)
1339 params["mode"] = cgi["mode"].read
1340 params["action"] = cgi["action"].read
1341 Controller.MultiForm(cgi, session, params, db)
1343 Controller.NormalForm(cgi, session, params, db)
1346 # エラー画面移行時はセッション情報を破棄する
1347 if params["mode"] == "error"
1348 session["login"] = nil
1353 # メニューとして表示されるHTML文字列です
1354 if params["target_filepath"].blank?
1355 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["filepath"]} "
1357 menu = "<div class=\"divstyle\" style=\"width: #{TABLEWIDTH}px;\"><div class=\"divstyle\" align=\"center\" style=\"margin-bottom: 5px;\">現在編集中のファイル : #{session["target_filepath"]} "
1359 if USEFILEMANAGER == true
1360 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>"
1362 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>"
1366 # modeとactionの相関図は以下のようになります。
1371 if session["login"] != "true"
1372 # セッションが存在しない場合は強制的にトップページに遷移
1373 htmlwriter = HtmlWriter.new("./erbtemp/login.html.erb", binding)
1377 htmlwriter = HtmlWriter.new("./erbtemp/select.html.erb", binding)
1379 htmlwriter = HtmlWriter.new("./erbtemp/newentry.html.erb", binding)
1381 htmlwriter = HtmlWriter.new("./erbtemp/editentry.html.erb", binding)
1383 htmlwriter = HtmlWriter.new("./erbtemp/delentry.html.erb", binding)
1385 htmlwriter = HtmlWriter.new("./erbtemp/editfeed.html.erb", binding)
1387 htmlwriter = HtmlWriter.new("./erbtemp/log.html.erb", binding)
1389 htmlwriter = HtmlWriter.new("./erbtemp/insertfeed.html.erb", binding)
1391 htmlwriter = HtmlWriter.new("./erbtemp/replacefeed.html.erb", binding)
1393 htmlwriter = HtmlWriter.new("./erbtemp/indeximport.html.erb", binding)
1395 htmlwriter = HtmlWriter.new("./erbtemp/reset.html.erb", binding)
1397 htmlwriter = HtmlWriter.new("./erbtemp/error.html.erb", binding)
1399 htmlwriter = HtmlWriter.new("./erbtemp/index.html.erb", binding)
1403 # エラーが発生した場合、それを画面に表示します
1404 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1409 cgi.out{htmlwriter.to_code}
1411 # エラーが発生した場合、それを画面に表示します
1412 htmlwriter = HtmlWriter.new("./erbtemp/exception.html.erb", binding)
1413 cgi.out{htmlwriter.to_code}
1420 # エラーが発生した場合、それを画面に表示します
1421 detail = ("%s: %s (%s)\n" %
1422 [evar.backtrace[0], evar.message, evar.send('class')]) +
1423 evar.backtrace[1..-1].join("\n")
1424 puts "content-type: text/html\n\n<plaintext>\n" + detail