File: counter.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 (408 lines) | stat: -rw-r--r-- 11,743 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
# counter.rb $Revision: 1.20 $
#
# Access counter plugin.
#
# 1. Usage
# counter(figure, filetype = ""): Show number of all visitors.
# counter_today(figure, filetype = ""): Show number of visitors for today.
# counter_today(figure, filetype = ""): Show number of visitors for yesterday.
#	 filetype: jpg, gif, png ... .
#
# kiriban?: Return true when the number is a kiriban.
# kiriban_today?: Return true when the number is a kiriban(for today's couner).
#
# counter
# counter 3
# coutner 3, "jpg"
# counter_today 4, "jpg"
# counter_yesterday
#
# 2. Documents
# See URLs below for more details.
#   http://ponx.s5.xrea.com/hiki/counter.rb.html (English) 
#   http://ponx.s5.xrea.com/hiki/ja/counter.rb.html (Japanese) 
#
# Copyright (c) 2002 MUTOH Masao <mutoh@highway.ne.jp>
# You can redistribute it and/or modify it under GPL2.
# 
=begin ChangeLog
2004-10-01 MUTOH Masao  <mutoh@highway.ne.jp>
   * Improved process against bots. @options["bot"] is now supported.

2003-11-15 MUTOH Masao  <mutoh@highway.ne.jp>
   * translate documents to English.

2003-02-15 MUTOH Masao  <mutoh@highway.ne.jp>
   * counter.dat礭ʤԶν
   * version 1.6.3

2002-11-26 Junichiro Kita <kita@kitaj.no-ip.com>
   * remove 'cgi.cookies = nil' in TDiaryCounter::main

2002-11-19 TADA Tadashi <sho@spc.gr.jp>
   * for squeeze.rb error more.
   * version 1.6.2

2002-11-13 TADA Tadashi <sho@spc.gr.jp>
   * for squeeze.rb error.

2002-10-12 MUTOH Masao  <mutoh@highway.ne.jp>
   * ƻȤȤưʤʤäƤԶν
   * 11ݻƤ桼򥯥꡼󥢥åפ褦ˤ
   * version 1.6.1

2002-08-30 MUTOH Masao  <mutoh@highway.ne.jp>
   * ǡե뤬ɤ߹ʤʤäȤ1ΥХååץǡ
     Ѥ줹褦ˤ(κݤˡ1ΥХååץǡ
     counter.dat.?.bakȤ̾ǥХååפ)1
     ХååץǡǤʤäƤΥͤ
     0ˤƥ顼̤ɽʤ褦ˤ
   * version 1.6.0

2002-07-23 MUTOH Masao  <mutoh@highway.ne.jp>
   * ХååץեΥե̾suffix(0-6ο)ˤ
      äơ1˸ŤեϾ񤭤Τǥեο
      7ĤȤʤ롣ΤǿȤ櫓ǤϤʤΤա
      (proposed by Junichiro KITA <kita@kitaj.no-ip.com>)
   * version 1.5.1

2002-07-19 MUTOH Masao  <mutoh@highway.ne.jp>
   * ñ̤ǥǡХååפ褦ˤ
     @options["counter.dairy_backup"]ǻꡣfalseꤷʤ¤
     Хååפ롣
   * Date#==᥽åɤnilϤʤ褦˽
   * require 'pstore'ɲ(tDiary version 1.5.xб)
   * logΥեޥåѹ(ơΥǡ)
   * @options["counter.deny_same_src_interval"]Υǥեͤ2
     ѹ
   * version 1.5.0

2002-05-19 MUTOH Masao  <mutoh@highway.ne.jp>
   * CookieȤȤΤǤʤƱ쥯饤ȤϢ³
     ȥåפʤ褦ˤ
   * @options["counter.deny_same_src_interval"]ɲáϢ³GETδֳ֤ꡣ
     ǥեȤ0.1(6ʬ)
   * version 1.4.0

2002-05-11 MUTOH Masao  <mutoh@highway.ne.jp>
   * ͤͿʤ5ȤƤ0ʤפѹ
     ޤ0̵0ꤷƤɤ
   * version 1.3.0

2002-05-05 MUTOH Masao  <mutoh@highway.ne.jp>
   * @debug = true  :->
   * ѹ
   * version 1.2.1

2002-05-04 MUTOH Masao  <mutoh@highway.ne.jp>
   * tlinkץ饰󤫤Υ򥫥ȤƤޤԶν
   * @options["counter.deny_user_agents"]ɲ
   * @options["counter.deny_remote_addrs"]ɲ
   * @options["counter.init_num"]ɲáֵǽȤδطǡcounter
   * ᥽åɤΰinit_numobsoleteȤޤ
   * @options["counter.kiriban"], @options["counter.kiriban_today"]ɲ
   * ֵǽɲ(kiriban?,kiriban_today?᥽åɲ)
   * version 1.2.0

2002-04-27 MUTOH Masao  <mutoh@highway.ne.jp>
   * add_header_procȤʤ褦ˤ
   * @options["counter.timer"]ͭˤʤʤԶν
   * @options["counter.log"]ɲátrueꤹcounter.dat
      Ʊǥ쥯ȥcounter.logȤե
      1ΥϿ褦ˤ
   * cookieͤȤƥСֹ褦ˤ
   * version 1.1.0

2002-04-25 MUTOH Masao  <mutoh@highway.ne.jp>
   * HEADǥä˺ƤӥȤ褦
      ʤäƤޤäƤԶν(by NT<nt@24i.net>)
   * version 1.0.4

2002-04-24 MUTOH Masao  <mutoh@highway.ne.jp>
   * ĥåߤ줿Ȥ˥顼ȯԶν
   * version 1.0.3

2002-04-23 MUTOH Masao  <mutoh@highway.ne.jp>
   * ǡե塢åͭü
      @today0ˤʤԶν
   * 줿Ȥ˿ɽʤԶν
   * HEADǥäϥȤʤ褦ˤ
      (reported by NT<nt@24i.net>, suggested a solution 
         by TADA Tadashi <sho@spc.gr.jp>)
   * version 1.0.2

2002-04-21 MUTOH Masao  <mutoh@highway.ne.jp>
   * CSS_ȤäƤȤ-ľ(reported by NT<nt@24i.net>)
   * TDiaryCountData#up@all+1ʤԶν
   * version 1.0.1

2002-04-14 MUTOH Masao  <mutoh@highway.ne.jp>
   * version 1.0.0
=end

def counter_allow?
	return false if bot?
	if @options 
		if @options["counter.deny_user_agents"] 
			agents = Regexp.new("(tlink|#{@options["counter.deny_user_agents"].uniq.join('|')})", true)
			return false if agents =~ @cgi.user_agent
      end
		if @options["counter.deny_remote_addrs"] 
			agents = Regexp.new("(tlink|#{@options["counter.deny_remote_addrs"].uniq.join('|')})", true)
			return false if agents =~ @cgi.remote_addr
      end
	end
	true 
end

if ["latest", "month", "day"].include?(@mode) and 
	ENV['REQUEST_METHOD'] == 'GET' and counter_allow?

require 'date'
require 'pstore'

eval(<<TOPLEVEL_CLASS, TOPLEVEL_BINDING)
class TDiaryCountData
	attr_reader :today, :yesterday, :all, :newestday, :ignore_cookie
	attr_writer :ignore_cookie #means ALWAYS ignore a cookie.

	def initialize
	  @today, @yesterday, @all = 0, 0, 0
	  @newestday = nil
	  @ignore_cookie = false
	end

	def up(now, cache_path, cgi, log)
	  if @newestday
		if now == @newestday
		  @today += 1
		else
		  log(@newestday, cache_path) if log
		  @yesterday = ((now - 1) == @newestday) ? @today : 0
		  @today = 1
		  @newestday = now
        time = Time.now
		  @users.reject!{|key, val|
			 time - val > 2 * 3600
		  }
		end
	  else
		@yesterday = 0
		@today = 1
		@newestday = now
	  end
	  @all += 1
	end

	def previous_access_time(remote_addr, user_agent, interval)
	  @users = Hash.new unless @users
	  now = Time.now

	  ret = @users[[remote_addr, user_agent]]
	  @users[[remote_addr, user_agent]] = now
	  ret
	end

	def log(day, path)
	  return unless day
	  open(path + "/counter.log", "a") do |io|
		io.print day, " : ", @all, ",", @today, ",", @yesterday, "\n"
	  end
	end
end
TOPLEVEL_CLASS

module TDiaryCounter
	@version = "1.6.3"

	def run(cache_path, cgi, options)
		timer = options["counter.timer"] if options
		timer = 12 unless timer	# 12 hour
		@init_num = options["counter.init_num"] if options
		@init_num = 0 unless @init_num
		dir = cache_path + "/counter"
		path = dir + "/counter.dat"
		today = Date.today
		Dir.mkdir(dir, 0700) unless FileTest.exist?(dir)
	
		cookie = nil
		begin
		  cookie = main(cache_path, cgi, options, timer, dir, path, today)
		rescue
		  back = (Dir.glob(path + ".?").sort{|a,b| File.mtime(a) <=> File.mtime(b)}.reverse)[0]
		  
		  if back
			copy(back, back + ".bak")
			copy(back, path)
		  else
			rm(path)
		  end
		  begin
			cookie = main(cache_path, cgi, options, timer, dir, path, today)
		  rescue 
			@cnt = TDiaryCountData.new
		  end
		end
		cookie
	end

	def main(cache_path, cgi, options, timer, dir, path, today)
		cookie = nil
		db = PStore.new(path)
		db.transaction do
			begin
				@cnt = db["countdata"]
			rescue PStore::Error
			end
            unless @cnt
              @cnt = TDiaryCountData.new
            end

			changed = false
			if new_user?(cgi, options)
				@cnt.up(today, dir, cgi, (options and options["counter.log"]))
				cookie = CGI::Cookie.new({"name" => "tdiary_counter", 
													"value" => @version, 
													 "expires" => Time.now + timer * 3600})
				changed = true
			end
			if options["counter.kiriban"]
				@kiriban = options["counter.kiriban"].include?(@cnt.all + @init_num) 
			end
 			if ! @kiriban and options["counter.kiriban_today"]
				@kiriban_today = options["counter.kiriban_today"].include?(@cnt.today)
			end

			if @cnt.ignore_cookie
				@cnt.ignore_cookie = false
				changed = true
			end

			#when it is kiriban time, ignore the cookie next access time. 
			if @kiriban or @kiriban_today
				@cnt.ignore_cookie = true
				changed = true
			end

			if changed
				if options["counter.daily_backup"] == nil || options["counter.daily_backup"] 
					copy(path, path + "." + today.wday.to_s)
				end
				db["countdata"] = @cnt
			end
		end
		cookie
	end

	def rm( fn, force = true )
	  first = true
	  begin
		File.unlink fn
	  rescue Errno::ENOENT
		force or raise
	  rescue
		# rescue dos?
		begin
		  if first then
			first = false
			File.chmod 0777, fn
			retry
		  end
		rescue
		end
	  end
	end

	def copy(old, new)
		if FileTest.exist?(old)
			File.open(old,  'rb') {|r|
				File.open(new, 'wb') {|w|
					st = r.stat
					begin
						while true do
							w.write r.sysread(st.blksize)
						end
					rescue EOFError
					end
				} 
			}
		end
	end
		
	def new_user?(cgi, options)
		if ! cgi.cookies or ! cgi.cookies.keys.include?("tdiary_counter")
			interval = options["counter.deny_same_src_interval"] if options
			interval = 2 unless interval	# 2 hour.
			previous_access_time = @cnt.previous_access_time(cgi.remote_addr, cgi.user_agent, interval)
			if previous_access_time
				ret = Time.now - previous_access_time > interval * 3600
			else
				ret = true
			end
		else
			ret = @cnt.ignore_cookie
		end
		ret
	end

	def format(classtype, theme_url, cnt, figure = 0, filetype = "", init_num = 0, &proc)
		str = "%0#{figure}d" % (cnt + init_num)
		result = %Q[<span class="counter#{classtype}">]
		depth = 0
		str.scan(/./).each do |num|
			if block_given?
				result << %Q[<img src="#{theme_url}/#{yield(num)}" alt="#{num}" />]
			elsif filetype == ""
				result << %Q[<span class="counter-#{depth}"><span class="counter-num-#{num}">#{num}</span></span>]
			else 
				result << %Q[<img src="#{theme_url}/#{num}.#{filetype}" alt="#{num}" />]
			end
			depth += 1
		end
		result << "</span>"
	end

	def called?; @called; end
	def called; @called = true; end
	def all; @cnt.all + @init_num; end
	def today; @cnt.today; end
	def yesterday; @cnt.yesterday; end
	def kiriban?; @kiriban; end
	def kiriban_today?; @kiriban_today; end

	module_function :new_user?, :all, :today, :yesterday, :format, 
							:main, :run, :copy, :rm, :kiriban?, :kiriban_today?
end

#init_num is deprecated.
#please replace it to @options["counter.init_num"]
def counter(figure = 0, filetype = "", init_num = 0, &proc) 
	TDiaryCounter.format("", theme_url, TDiaryCounter.all, figure, filetype, init_num, &proc)
end

def counter_today(figure = 0, filetype = "", &proc)
	TDiaryCounter.format("-today", theme_url, TDiaryCounter.today, figure, filetype, 0, &proc)
end

def counter_yesterday(figure = 0, filetype = "", &proc)
	TDiaryCounter.format("-yesterday", theme_url, TDiaryCounter.yesterday, figure, filetype, 0, &proc)
end

def kiriban?
	TDiaryCounter.kiriban?
end

def kiriban_today?
	TDiaryCounter.kiriban_today?
end

tdiary_counter_cookie = TDiaryCounter.run(@cache_path, @cgi, @options)
if tdiary_counter_cookie
	if defined?(add_cookie)
		add_cookie(tdiary_counter_cookie)
	else
		@cookie = tdiary_counter_cookie if tdiary_counter_cookie
	end
end

end