File: category.rb

package info (click to toggle)
tdiary 2.0.1-1sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 7,220 kB
  • ctags: 1,667
  • sloc: ruby: 20,044; lisp: 476; makefile: 91; sql: 32; sh: 31
file content (696 lines) | stat: -rw-r--r-- 16,612 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# category.rb $Revision: 1.21.2.1 $
#
# Copyright (c) 2003 Junichiro KITA <kita@kitaj.no-ip.com>
# Distributed under the GPL
#
require 'pstore'

#
# initialize
#
def category_init
	@conf['category.header1'] ||= %Q[<div class="adminmenu">\n<p>\n<%= category_navi %>\n</p>\n</div>\n]
	@conf['category.header2'] ||= %Q[<p>Categories |\n<%= category_list %>\n</p>\n]
	@conf['category.edit_support'] = true if @conf['category.edit_support'].nil?
end
category_init

def category_icon_location_init
	@category_icon_dir = (@conf['category.icon_dir'] || './icons/').sub(%r|/*$|, '/')
	@category_icon_url = (@conf['category.icon_url'] || './icons/').sub(%r|/*$|, '/')
end

def category_icon_init
	category_icon_location_init
	@conf['category.icon'] ||= ''

	@category_icon = {}
	@conf['category.icon'].split(/\n/).each do |l|
		c, i = l.split
		next if c.nil? or i.nil?
		@category_icon[c] = i if File.exists?("#{@category_icon_dir}#{i}")
	end
end
category_icon_init

#
# plugin methods
#
def category_form
	# don't you need this method any more?
end

def category_anchor(category)
	period = @conf['category.period'] || 'quarter'
	period_string = 
		case period
		when "month"
			"year=#{@date.year};month=#{'%02d' % @date.month};"
		when "quarter"
			"year=#{@date.year};month=#{(@date.month - 1) / 3 + 1}Q;"
		when "half"
			"year=#{@date.year};month=#{(@date.month - 1) / 6 + 1}H;"
		when "year"
			"year=#{@date.year};"
		else
			""
		end
	if @category_icon[category]
		%Q|<a href="#{@index}?#{period_string}category=#{CGI::escape(category)}"><img class="category" src="#{@category_icon_dir}#{@category_icon[category]}" alt="#{category}"></a>|
	else
		%Q|[<a href="#{@index}?#{period_string}category=#{CGI::escape(category)}">#{category}</a>]|
	end
end

def category_navi_anchor(info, label)
	((!label.nil?) && label.empty?) ? '' : %Q[<span class="adminmenu">#{info.make_anchor(label)}</span>\n]
end

def category_navi
	info = Category::Info.new(@cgi, @years, @conf)
	mode = info.mode

	result = ''
	case mode
	when :year, :half, :quarter, :month
		all_diary = Category::Info.new(@cgi, @years, @conf, :year => -1, :month => -1)
		all = Category::Info.new(@cgi, @years, @conf, :category => ['ALL'], :year => -1, :month => -1)
		result << category_navi_anchor(info.prev, @conf['category.prev_' + mode.to_s])
		result << category_navi_anchor(info.next, @conf['category.next_' + mode.to_s])
		result << category_navi_anchor(all_diary, @conf['category.all_diary'])
		result << category_navi_anchor(all, @conf['category.all'])
	when :all
		year = Category::Info.new(@cgi, @years, @conf, :year => Time.now.year.to_s)
		half = Category::Info.new(@cgi, @years, @conf, :year => Time.now.year.to_s, :month => "#{((Time.now.month - 1) / 6 + 1)}H")
		quarter = Category::Info.new(@cgi, @years, @conf, :year => Time.now.year.to_s, :month => "#{((Time.now.month - 1) / 3 + 1)}Q")
		month = Category::Info.new(@cgi, @years, @conf, :year => Time.now.year.to_s, :month => '%02d' % Time.now.month)
		result << category_navi_anchor(year, @conf['category.this_year'])
		result << category_navi_anchor(half, @conf['category.this_half'])
		result << category_navi_anchor(quarter, @conf['category.this_quarter'])
		result << category_navi_anchor(month, @conf['category.this_month'])
	end
	if !info.category.include?('ALL')
		all_category = Category::Info.new(@cgi, @years, @conf, :category => ['ALL'])
		result << category_navi_anchor(all_category, @conf['category.all_category'])
	end
	result
end

def category_list_sections
	info = Category::Info.new(@cgi, @years, @conf)
	category = info.category
	years = info.years
	r = ''

	@categorized.keys.sort.each do |c|
		info.category = c
		if @category_icon[c]
			img = %Q|<img class="category" src="#{@category_icon_dir}#{@category_icon[c]}" alt="#{c}">|
		else
			img = ''
		end
		r << <<HTML
<div class="conf day">
	<h2><span class="title">#{img}#{info.make_anchor}</span></h2>
	<div class="body">
		<p>
HTML
		@categorized[c].keys.sort.each do |ymd|
			text = Time.local(ymd[0,4], ymd[4,2], ymd[6,2]).strftime(@conf.date_format)
			@categorized[c][ymd].sort.each do |idx, title, excerpt|
				r << %Q|\t\t\t<a href="#{@conf.index}#{anchor "#{ymd}#p#{'%02d' % idx}"}" title="#{excerpt}">#{text}#p#{'%02d' % idx}</a> #{apply_plugin(title)}<br>\n|
			end
		end
		r << <<HTML
		</p>
	</div>
</div>
HTML
	end
	r
end

def category_list
	info = Category::Info.new(@cgi, @years, @conf)
	@categories.map do |c|
		info.category = c
		info.make_anchor
	end.join(" | \n")
end

def category_dropdown_list(label = nil, multiple = nil)
	label ||= 'Categorize!'
	multiple ||= false

	category = Category::Info.new(@cgi, @years, @conf).category
	category = ['ALL'] if category.empty?

	options = ''
	(['ALL'] + @categories).each do |c|
		options << %Q|\t\t<option value="#{CGI.escapeHTML(c)}"#{" selected" if category.include?(c)}>#{CGI.escapeHTML(c)}</option>\n|
	end

	<<HTML
<form method="get" action="#{@conf.index}?#{period_string}">
	<select name="category"#{" multiple" if multiple}>
#{options}
	</select>
	<input type="submit" value="#{label}">
</form>
HTML
end


#
# misc
#
::TDiary::TDiaryMonth.module_eval do
	attr_reader :diaries
end

def category_icon_save
	@conf['category.icon'] = @category_icon.map {|c, i| "#{c} #{i}"}.join("\n")
end


module Category

#
# Info
#
class Info
	def initialize(cgi, years, conf, args = {})
		@cgi = cgi
		@years = years
		@conf = conf
		@category = args[:category] || @cgi.params['category']
		@year = args[:year] || @cgi.params['year'][0]
		@month = args[:month] || @cgi.params['month'][0]
		@mode = :all
		set_mode
	end

protected
	attr_writer :year
	attr_writer :month
public
	attr :category, true
	attr_reader :year
	attr_reader :month
	attr_reader :mode

	def prev
		pp = self.dup

		case mode
		when :half
			h = @month.to_i
			if h == 1
				pp.month = "2H"
				pp.year = (@year.to_i - 1).to_s if @year
			else
				pp.month = "1H"
			end
		when :quarter
			q = @month.to_i
			if q == 1
				pp.month = "4Q"
				pp.year = (@year.to_i - 1).to_s if @year
			else
				pp.month = "#{q - 1}Q"
			end
		when :month
			m = @month.to_i
			if m == 1
				pp.month = "12"
				pp.year = (@year.to_i - 1).to_s if @year
			else
				pp.month = '%02d' % (m - 1)
			end
		when :year
			pp.year = (@year.to_i - 1).to_s
		end
		pp
	end

	def next
		pp = self.dup

		case mode
		when :half
			h = @month.to_i
			if h == 2
				pp.month = "1H"
				pp.year = (@year.to_i + 1).to_s if @year
			else
				pp.month = "2H"
			end
		when :quarter
			q = @month.to_i
			if q == 4
				pp.month = "1Q"
				pp.year = (@year.to_i + 1).to_s if @year
			else
				pp.month = "#{q + 1}Q"
			end
		when :month
			m = @month.to_i
			if m == 12
				pp.month = "01"
				pp.year = (@year.to_i + 1).to_s if @year
			else
				pp.month = '%02d' % (m + 1)
			end
		when :year
			pp.year = (@year.to_i + 1).to_s
		end
		pp
	end

	def make_anchor(label = nil)
		a = @category.map {|c| "category=#{CGI.escape(c)}"}.join(';')
		a << ";year=#{@year}" if @year
		a << ";month=#{@month}" if @month
		if label
			case mode
			when :year
				label = label.gsub(/\$1/, @year)
			when :month, :quarter, :half
				label = label.gsub(/\$2/, @month)
				label = label.gsub(/\$1/, @year || '*')
			end
		else
			label = @category.map {|c| CGI.escapeHTML(c)}.join(':')
		end
		%Q|<a href="#{@conf.index}?#{a}">#{label}</a>|
	end

	#
	# return ym_spec
	#
	# {"yyyy" => ["mm", ...], ...}
	#
	# date spec:
	#  (1) none               -> all diary
	#  (2) month=xH           -> all diary in xH of all year
	#  (3) year=YYYY;month=xH -> all diary in YYYY/xH
	#  (4) month=xQ           -> all diary in xQ of all year
	#  (5) year=YYYY;month=xQ -> all diary in YYYY/xQ
	#  (6) month=MM           -> all diary in MM of all year
	#  (7) year=YYYY;month=MM -> all diary in YYYY/MM
	#  (8) year=YYYY          -> all diary in YYYY
	#
	def years
		if @mode == :all
			return @years
		end

		months = case @mode
		when :half
			[('01'..'06'), ('07'..'12')][@month.to_i - 1].to_a
		when :quarter
			[['01', '02', '03'], ['04', '05', '06'], ['07', '08', '09'], ['10', '11', '12']][@month.to_i - 1]
		when :month
			[@month]
		else
			('01'..'12').to_a
		end

		r = {}
		(@year ? [@year] : @years.keys).each do |y|
			r[y] = months
		end
		r
	end

	#
	# date spec:
	#  (1) none                -> all
	#  (2) month=xH            -> half
	#  (3) year=YYYY;month=xH  -> half
	#  (4) month=xQ            -> quarter
	#  (5) year=YYYY;month=xQ  -> quarter
	#  (6) month=MM            -> month
	#  (7) year=YYYY;month=MM  -> month
	#  (8) year=YYYY           -> year
	#
	def set_mode
		if @year.nil? and @month.nil?
			@mode = :all
		end

		if /\d{4}/ === @year.to_s
			@mode = :year
		else
			@year = nil
		end

		if /[12]H/ === @month.to_s
			@mode = :half
		elsif /[1-4]Q/ === @month.to_s
			@mode = :quarter
		elsif (1..12).include?(@month.to_i)
			@mode = :month
		else
			@month = nil
		end

	end
end

#
# Cache
#
class Cache
	def initialize(conf, bind)
		@conf = conf
		@binding = bind                           # ...... very ugly
		@dir = "#{conf.data_path}/category"
		Dir.mkdir(@dir) unless File.exist?(@dir) 
	end

	def add_categories(list)
		return if list.nil? or list.empty?
		replace_categories(restore_categories + list)
	end

	def replace_categories(list)
		PStore.new(cache_file).transaction do |db|
			db['category'] = list.sort.uniq
		end
	end

	#
	# restore category names
	# ["category1", "category2", ...]
	#
	def restore_categories
		list = nil
		PStore.new(cache_file).transaction do |db|
			list = db['category'] if db.root?('category')
			db.abort
		end
		list || []
	end

	#
	# cache each section of diary
	# used in update_proc
	#
	def replace_sections(diary)
		return if diary.nil? or !diary.categorizable?

		categorized = categorize_diary(diary)
		categories = restore_categories
		deleted = []
		ymd = diary.date.strftime('%Y%m%d')

		categories.each do |c|
			PStore.new(cache_file(c)).transaction do |db|
				db['category'] = {} unless db.root?('category')
				if diary.visible? and categorized[c]
					db['category'].update(categorized[c])
				else
					# diary is invisible or sections of this category is deleted
					db['category'].delete(ymd)
					deleted << c if db['category'].empty?
				end
			end
		end

		if !deleted.empty?
			deleted.each do |c|
				File.unlink(cache_file(c))
			end
			replace_categories(categories - deleted)
		end
	end

	#
	# (re)create category cache
	#
	def recreate(years)
		cgi = CGI::new
		def cgi.referer; nil; end

		list = []
		years.each do |y, ms|
			ms.each do |m|
				ym = "#{y}#{m}"
				cgi.params['date'] = [ym]
				m = TDiaryMonth.new(cgi, '', @conf)
				sections = {}
				m.diaries.each do |ymd, diary|
					next if !diary.visible?
					initial_replace_sections(diary)
					diary.each_section do |s|
						list |= s.categories unless s.categories.empty?
					end
				end
			end
		end

		replace_categories(list)
	end

	#
	# categorize sections of category of years
	#
	# {"category" => {"yyyymmdd" => [[idx, title, excerpt], ...], ...}, ...}
	#
	def categorize(category, years)
		categories = category - ['ALL']
		if categories.empty?
			categories = restore_categories
		else
			categories &= restore_categories
		end

		categorized = {}
		categories.each do |c|
			PStore.new(cache_file(c)).transaction do |db|
				categorized[c] = db['category']
				db.abort
			end
			categorized[c].keys.each do |ymd|
				y, m = ymd[0,4], ymd[4,2]
				if years[y].nil? or !years[y].include?(m)
					categorized[c].delete(ymd)
				end
			end
			categorized.delete(c) if categorized[c].empty?
		end

		categorized
	end

private
	def cache_file(category = nil)
		if category
			"#{@dir}/#{CGI.escape(category)}".untaint
		else
			"#{@dir}/category_list"
		end
	end

	#
	# categorize sections of diary
	#
	# {"category" => {"yyyymmdd" => [[idx, title, excerpt], ...]}}
	#
	def categorize_diary(diary)
		categorized = {}
		ymd = diary.date.strftime('%Y%m%d')

		idx = 1
		diary.each_section do |s|
			s.categories.each do |c|
				categorized[c] = {} if categorized[c].nil?
				categorized[c][ymd] = [] if categorized[c][ymd].nil?
				body = <<EVAL
text = apply_plugin(<<'BODY', true)
#{s.body_to_html}
BODY
EVAL
				shorten = begin
					@conf.shorten(eval(body.untaint, @binding))
				rescue NameError
					""
				end
				categorized[c][ymd] << [idx, s.stripped_subtitle_to_html, shorten]
			end
			idx +=1
		end

		categorized
	end

	#
	# cache each section of diary
	# used in recreate
	#
	def initial_replace_sections(diary)
		return if diary.nil? or !diary.visible? or !diary.categorizable?

		categorized = categorize_diary(diary)
		categorized.keys.each do |c|
			PStore.new(cache_file(c)).transaction do |db|
				db['category'] = {} unless db.root?('category')
				db['category'].update(categorized[c])
			end
		end
	end
end

end # module Category

# read cache here so that you can use category with secure mode.
@category_cache = Category::Cache.new(@conf, binding)

#
# display categories you use on update form
#
@conf['category.edit_support'] and add_edit_proc do |date|
	ret = ''
	unless @categories.size == 0 then
		ret << %Q[
		<script type="text/javascript">
		<!--
		function inj_c(val){
			target = window.document.forms[0].body
			target.focus();
			target.value += val
		}
		//-->
		</script>
		]
		ret << '<div class="field title">'
		ret << "#{@category_conf_label}:\n"
		@categories.each do |c|
			e_c = CGI.escapeHTML(c)
			ret << %Q!| <a href="javascript:inj_c(&quot;[#{e_c}]&quot;)">#{e_c}</a>\n!
		end
		ret << "|\n</div>\n<br>\n"
	end
end


#
# when update diary, update cache
#
add_update_proc do
	cache = @category_cache
	list = []
	diary = @diaries[@date.strftime('%Y%m%d')]
	diary.each_section do |s|
		list |= s.categories
	end
	cache.add_categories(list)
	cache.replace_sections(diary)
end


#
# configuration
#
def category_icon_find_icons
   return if @category_all_icon
	@category_all_icon = []
	%w(png jpg gif bmp).each do |e|
		@category_all_icon += Dir.glob("#{@category_icon_dir}*.#{e}").map {|i| File.basename(i)}
	end
	@category_all_icon.sort!
end

def category_icon_select(category)
	options = %Q|<\t<option value="none">#{@category_icon_none_label}</option>\n|
	@category_all_icon.each do |i|
		options << %Q|\t<option value="#{CGI.escapeHTML(i)}"#{" selected" if @category_icon[category] == i}>#{CGI.escapeHTML(i)}</option>\n|
	end
	<<HTML
<select name="category.icon.#{category}">
#{options}
</select>
HTML
end

def category_icon_sample
	@category_all_icon.map do |i|
		%Q|<img src="#{@category_icon_url}#{i}" alt="#{i}">\n|
	end.join("/\n")
end

if @mode == 'conf' || @mode == 'saveconf'
	add_conf_proc('category', @category_conf_label) do
		cache = @category_cache
		if @mode == 'saveconf'
			if @cgi.valid?( 'category_initialize' )
				@category_cache.recreate(@years)
			end

			[
				'category.header1',
				'category.header2',
			].each do |name|
				@conf[name] = @conf.to_native( @cgi.params[name][0] )
			end
			[
				'category.prev_year',
				'category.next_year',
				'category.prev_half',
				'category.next_half',
				'category.prev_quarter',
				'category.next_quarter',
				'category.prev_month',
				'category.next_month',
				'category.this_year',
				'category.this_half',
				'category.this_quarter',
				'category.this_month',
				'category.all_diary',
				'category.all_category',
				'category.all',
			].each do |name|
				@conf[name] = @conf.to_native( @cgi.params[name][0] )
			end
			if ["month", "quearter", "half", "year", "all"].index(@cgi.params["category.period"][0])
				@conf["category.period"] = @cgi.params["category.period"][0]
			end
			@conf['category.edit_support'] = (@cgi.params['category.edit_support'][0] == 'true')
		end
		category_conf_html
	end

	category_icon_find_icons if @cgi.params['conf'][0] == 'category_icon'
	add_conf_proc('category_icon', @category_icon_conf_label) do
		if @mode == 'saveconf'
			unless @conf.secure
				[
					'category.icon_dir',
					'category.icon_url',
				].each do |name|
					@conf[name] = @cgi.params[name][0].sub(%r|/*$|, '/')
				end
				category_icon_location_init
			end
			@cgi.params.keys.each do |key|
				next unless /\Acategory\.icon\..*\z/ === key
				category = key.sub(/\Acategory\.icon\./, '')
				@category_icon[category] = @cgi.params[key][0] if @cgi.params[key][0] != 'none'
			end
			category_icon_save
		end
		category_icon_conf_html
	end
	if @cgi.valid?('category_initialize')
		@category_cache.recreate(@years)
	end
end

@categories = @category_cache.restore_categories
if @mode == 'categoryview'
	info = Category::Info.new(@cgi, @years, @conf)
	@categorized = @category_cache.categorize(info.category, info.years)
end

# vim: ts=3