Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 2002 lines (1765 sloc) 45.017 kb
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 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
=begin
== NAME
tDiary: the "tsukkomi-able" web diary system.
tdiary.rb $Revision: 1.227 $

Copyright (C) 2001-2005, TADA Tadashi <sho@spc.gr.jp>
You can redistribute it and/or modify it under GPL2.
=end

TDIARY_VERSION = '2.1.2'

require 'cgi'
require 'uri'
begin
require 'erb_fast'
rescue LoadError
require 'erb'
end

=begin
== String class
enhanced String class
=end
class String
def make_link
r = %r<(((http[s]{0,1}|ftp)://[\(\)%#!/0-9a-zA-Z_$@.&+-,'"*=;?:~-]+)|([0-9a-zA-Z_.-]+@[\(\)%!0-9a-zA-Z_$.&+-,'"*-]+\.[\(\)%!0-9a-zA-Z_$.&+-,'"*-]+))>
return self.
gsub( / /, "\001" ).
gsub( /</, "\002" ).
gsub( />/, "\003" ).
gsub( /&/, '&amp;' ).
gsub( /\"/, "\004").
gsub( r ){ $1 == $2 ? "<a href=\"#$2\">#$2</a>" : "<a href=\"mailto:#$4\">#$4</a>" }.
gsub( /\004/, '&quot;' ).
gsub( /\003/, '&gt;' ).
gsub( /\002/, '&lt;' ).
gsub( /^\001+/ ) { $&.gsub( /\001/, '&nbsp;' ) }.
gsub( /\001/, ' ' ).
gsub( /\t/, '&nbsp;' * 8 )
end
end

=begin
== CGI class
enhanced CGI class
=end
class CGI
def valid?( param, idx = 0 )
begin
self.params[param] and self.params[param][idx] and self.params[param][idx].length > 0
rescue NameError # for Tempfile class of ruby 1.6
self.params[param][idx].stat.size > 0
end
end

def mobile_agent?
self.user_agent =~ %r[(DoCoMo|J-PHONE|Vodafone|MOT-|UP\.Browser|DDIPOCKET|ASTEL|PDXGW|Palmscape|Xiino|sharp pda browser|Windows CE|L-mode)]i
end

def https?
return false if env_table['HTTPS'].nil? or /off/i =~ env_table['HTTPS']
true
end

def request_uri
env_table['REQUEST_URI']
end

def redirect_url
env_table['REDIRECT_URL']
end

if RUBY_VERSION >= '1.8.0' && RUBY_VERSION < '1.8.2'
module QueryExtension
%w[ CONTENT_LENGTH SERVER_PORT ].each do |env|
define_method(env.sub(/^HTTP_/n, '').downcase) do
(val = env_table[env]) && Integer(val)
end
end
end
end
end

=begin
== Safe module
=end
require 'thread'
module Safe
def safe( level = 4 )
result = nil
if $SAFE < level then
Thread.start {
$SAFE = level
result = yield
}.join
else
result = yield
end
result
  end
  module_function :safe
end

#
# module TDiary
#
module TDiary
PATH = File::dirname( __FILE__ )

#
# class Comment
# Management a comment.
#
class Comment
attr_reader :name, :mail, :body, :date

def initialize( name, mail, body, date = Time::now )
@name, @mail, @body, @date = name, mail, body, date
@show = true
end

def shorten( length = 120 )
matched = body.gsub( /\n/, ' ' ).scan( /^.{0,#{length - 2}}/ )[0]
unless $'.empty? then
matched + '..'
else
matched
end
end

def visible?; @show; end
def show=( s ); @show = s; end

def ==( c )
(@name == c.name) and (@mail == c.mail) and (@body == c.body)
end
end

#
# module CommentManager
# Management comments in a day. Include in Diary class.
#
module CommentManager
private
#
# call this method when initialize
#
def init_comments
@comments = []
end

public
def add_comment( com )
@comments << com
if not @last_modified or @last_modified < com.date
@last_modified = com.date
end
com
end

def count_comments( all = false )
i = 0
@comments.each do |comment|
i += 1 if all or comment.visible?
end
i
end

def each_comment( limit = 3 )
@comments.each_with_index do |com,idx|
break if idx >= limit
yield com
end
end

def each_comment_tail( limit = 3 )
idx = 0
comments = @comments.collect {|c|
idx += 1
if c.visible? then
[c, idx]
else
nil
end
}.compact
s = comments.size - limit
s = 0 if s < 0
for idx in s...comments.size
yield comments[idx][0], comments[idx][1] # idx is start with 1.
end
end

def each_visible_comment( limit = 3 )
@comments.each_with_index do |com,idx|
break if idx >= limit
next unless com.visible?
yield com,idx+1 # idx is start with 1.
end
end

def each_visible_trackback( limit = 3 )
i = 0
@comments.find_all {|com|
com.visible_true? and /^TrackBack$/ =~ com.name
}[0,limit].each do |com|
i += 1 # i starts with 1.
yield com,i
end
end

def each_visible_trackback_tail( limit = 3 )
i = 0
@comments.find_all {|com|
com.visible_true? and /^TrackBack$/ =~ com.name
}.reverse[0,limit].reverse.each do |com|
i += 1 # i starts with 1.
yield com,i
end
end
end

#
# module RefererManager
# Management referers in a day. Include in Diary class.
#
module RefererManager
private
#
# call this method when initialize
#
def init_referers
@referers = {}
@new_referer = true # for compatibility
end

public
def add_referer( ref, count = 1 )
newer_referer
ref = ref.sub( /#.*$/, '' ).sub( /\?\d{8}$/, '' )
if /^([^:]+:\/\/)([^\/]+)/ =~ ref
ref = $1 + $2.downcase + $'
end
uref = CGI::unescape( ref )
if pair = @referers[uref] then
pair = [pair, ref] if pair.class != Array # for compatibility
@referers[uref] = [pair[0] + count, pair[1]]
else
@referers[uref] = [count, ref]
end
end

def count_referers
@referers.size
end

def each_referer( limit = 10 )
newer_referer
@referers.values.sort.reverse.each_with_index do |ary,idx|
break if idx >= limit
yield ary[0], ary[1]
end
end

private
def newer_referer
unless @new_referer then # for compatibility
@referers.keys.each do |ref|
count = @referers[ref]
if count.class != Array then
@referers.delete( ref )
@referers[CGI::unescape( ref )] = [count, ref]
end
end
@new_referer = true
end
end
end

#
# module/class Filter
#
module Filter
class Filter
def initialize( cgi, conf )
@cgi, @conf = cgi, conf
end

def comment_filter( diary, comment )
true
end

def referer_filter( referer )
true
end
end
end

#
# module DiaryBase
# Base module of Diary.
#
module DiaryBase
include CommentManager
include RefererManager

def init_diary
init_comments
init_referers
@show = true
end

def date
@date
end

def set_date( date )
if date.class == String then
y, m, d = date.scan( /^(\d{4})(\d\d)(\d\d)$/ )[0]
raise ArgumentError::new( 'date string needs YYYYMMDD format.' ) unless y
@date = Time::local( y, m, d )
else
@date = date
end
end

def title
@title || ''
end

def set_title( title )
@title = title
@last_modified = Time::now
end

def show( s )
@show = s
end

def visible?
@show != false;
end

def last_modified
@last_modified ? @last_modified : Time::at( 0 )
end

def last_modified=( lm )
@last_modified = lm
end

def eval_rhtml( opt, path = '.' )
ERB::new( File::open( "#{path}/skel/#{opt['prefix']}diary.rhtml" ){|f| f.read }.untaint ).result( binding )
end
end

#
# exception classes
#
class TDiaryError < StandardError; end
class PermissionError < TDiaryError; end
class PluginError < TDiaryError; end
class BadStyleError < TDiaryError; end

#
# class IOBase
# base of IO class
#
class IOBase
def calendar
raise StandardError, 'not implemented'
end

def transaction( date )
raise StandardError, 'not implemented'
end

def diary_factory( date, title, body, style = nil )
raise StandardError, 'not implemented'
end

def styled_diary_factory( date, title, body, style_name = 'tDiary' )
if style_class = style( style_name.downcase )
return style_class::new( date, title, body )
else
raise BadStyleError, "bad style: #{style_name}"
end
end

def load_styles
@styles = {}
Dir::glob( "#{TDiary::PATH}/tdiary/*_style.rb" ) do |style_file|
require style_file.untaint
style = File::basename( style_file ).sub( /_style\.rb$/, '' )
@styles[style] = TDiary::const_get( "#{style.capitalize}Diary" )
end
end

def style( s )
@styles ? @styles[s.downcase] : nil
end
end

# class ForceRedirect
# force redirect to another page
#
class ForceRedirect < StandardError
attr_reader :path
def initialize( path )
@path = path
end
end

#
# class Config
# configuration class
#
class Config
def initialize(cgi)
@cgi = cgi
load

instance_variables.each do |v|
v.sub!( /@/, '' )
instance_eval( <<-SRC
def #{v}
@#{v}
end
def #{v}=(p)
@#{v} = p
end
SRC
)
end

bot = ["googlebot", "Hatena Antenna", "moget@goo.ne.jp"]
bot += @options['bot'] || []
@bot = Regexp::new( "(#{bot.uniq.join( '|' )})", true )
end

# saving to tdiary.conf in @data_path
def save
result = ERB::new( File::open( "#{PATH}/skel/tdiary.rconf" ){|f| f.read }.untaint ).result( binding )
result.untaint unless @secure
Safe::safe( @secure ? 4 : 1 ) do
eval( result, binding, "(TDiary::Config#save)", 1 )
end
File::open( "#{@data_path}tdiary.conf", 'w' ) do |o|
o.print result
end
end

def mobile_agent?
%r[(DoCoMo|J-PHONE|Vodafone|MOT-|UP\.Browser|DDIPOCKET|ASTEL|PDXGW|Palmscape|Xiino|sharp pda browser|Windows CE|L-mode)]i =~ @cgi.user_agent
end

def bot?
@bot =~ @cgi.user_agent
end

#
# get/set/delete plugin options
#
def []( key )
@options[key]
end

def []=( key, val )
@options2[key] = @options[key] = val
end

def delete( key )
@options.delete( key )
@options2.delete( key )
end

def base_url
return '' unless @cgi.script_name
if @cgi.https?
port = (@cgi.server_port == 443) ? '' : ':' + @cgi.server_port.to_s
"https://#{ @cgi.server_name }#{ port }#{File::dirname(@cgi.script_name)}/"
else
port = (@cgi.server_port == 80) ? '' : ':' + @cgi.server_port.to_s
"http://#{ @cgi.server_name }#{ port }#{File::dirname(@cgi.script_name)}/"
end.sub(%r|/+$|, '/')
end

private
# loading tdiary.conf in current directory
def load
@secure = true unless @secure
@options = {}
eval( File::open( "tdiary.conf" ){|f| f.read }.untaint, binding, "(tdiary.conf)", 1 )

# language setup
@lang = 'ja' unless @lang
begin
instance_eval( File::open( "#{TDiary::PATH}/tdiary/lang/#{@lang}.rb" ){|f| f.read }.untaint, "(tdiary/lang/#{@lang}.rb)", 1 )
rescue Errno::ENOENT
@lang = 'ja'
retry
end

@data_path += '/' if /\/$/ !~ @data_path
@style = 'tDiary' unless @style
@index = './' unless @index
@update = 'update.rb' unless @update
@hide_comment_form = false unless defined?( @hide_comment_form )

@author_name = '' unless @author_name
@index_page = '' unless @index_page
@hour_offset = 0 unless @hour_offset

@html_title = '' unless @html_title
@header = '' unless @header
@footer = '' unless @footer

@section_anchor = '<span class="sanchor">_</span>' unless @section_anchor
@comment_anchor = '<span class="canchor">_</span>' unless @comment_anchor
@date_format = '%Y-%m-%d' unless @date_format
@latest_limit = 10 unless @latest_limit
@show_nyear = false unless @show_nyear

@theme = 'default' if not @theme and not @css
@css = '' unless @css

@show_comment = true unless defined?( @show_comment )
@comment_limit = 3 unless @comment_limit

@show_referer = true unless defined?( @show_referer )
@referer_limit = 10 unless @referer_limit
@referer_day_only = false unless defined?( @referer_day_only )
@no_referer = [] unless @no_referer
@no_referer2 = [] unless @no_referer2
@no_referer = @no_referer2 + @no_referer
@referer_table = [] unless @referer_table
@referer_table2 = [] unless @referer_table2
@referer_table = @referer_table2 + @referer_table

@options = {} unless @options.class == Hash
if @options2 then
@options.update( @options2 )
else
@options2 = {}.taint
end
@options.taint

# for 1.4 compatibility
@section_anchor = @paragraph_anchor unless @section_anchor
end

# loading tdiary.conf in @data_path.
def load_cgi_conf
raise TDiaryError, 'No @data_path variable.' unless @data_path

@data_path += '/' if /\/$/ !~ @data_path
raise TDiaryError, 'Do not set @data_path as same as tDiary system directory.' if @data_path == "#{PATH}/"

variables = [
:author_name, :author_mail, :index_page, :hour_offset,
:html_title, :header, :footer,
:section_anchor, :comment_anchor, :date_format, :latest_limit, :show_nyear,
:theme, :css,
:show_comment, :comment_limit, :mail_on_comment, :mail_header,
:show_referer, :referer_limit, :referer_day_only, :no_referer2, :referer_table2,
:options2,
:icon, :description,
]
begin
cgi_conf = File::open( "#{@data_path}tdiary.conf" ){|f| f.read }
cgi_conf.untaint unless @secure
def_vars = ""
variables.each do |var| def_vars << "#{var} = nil\n" end
eval( def_vars )
Safe::safe( @secure ? 4 : 1 ) do
eval( cgi_conf, binding, "(TDiary::Config#cgi_conf)", 1 )
end
variables.each do |var| eval "@#{var} = #{var} if #{var} != nil" end
rescue IOError, Errno::ENOENT
end
end

def method_missing( *m )
if m.length == 1 then
instance_eval( <<-SRC
def #{m[0]}
@#{m[0]}
end
def #{m[0]}=( p )
@#{m[0]} = p
end
SRC
)
end
nil
end
end

#
# class Plugin
# plugin management class
#
class Plugin
attr_reader :cookies

def initialize( params )
@header_procs = []
@footer_procs = []
@update_procs = []
@body_enter_procs = []
@body_leave_procs = []
@edit_procs = []
@form_procs = []
@conf_keys = []
@conf_procs = {}
@cookies = []

params.each_key do |key|
eval( "@#{key} = params['#{key}']" )
end

# for 1.4 compatibility
@index = @conf.index
@update = @conf.update
@author_name = @conf.author_name || ''
@author_mail = @conf.author_mail || ''
@index_page = @conf.index_page || ''
@html_title = @conf.html_title || ''
@theme = @conf.theme
@css = @conf.css
@date_format = @conf.date_format
@referer_table = @conf.referer_table
@options = @conf.options

# for ruby 1.6.x support
if @conf.secure then
@cgi.params.each_value do |p|
p.each {|v| v.taint}
end
end

# loading plugins
@plugin_files = []
plugin_path = @conf.plugin_path || "#{PATH}/plugin"
plugin_file = ''
begin
Dir::glob( "#{plugin_path}/*.rb" ).sort.each do |file|
plugin_file = file
load_plugin( file )
@plugin_files << plugin_file
end
rescue Exception
raise PluginError::new( "Plugin error in '#{File::basename( plugin_file )}'.\n#{$!}\n#{$!.backtrace[0]}" )
end
end

def load_plugin( file )
@resource_loaded = false
begin
res_file = File::dirname( file ) + "/#{@conf.lang}/" + File::basename( file )
open( res_file.untaint ) do |src|
instance_eval( src.read.untaint, "(plugin/#{@conf.lang}/#{File::basename( res_file )})", 1 )
end
@resource_loaded = true
rescue IOError, Errno::ENOENT
end
File::open( file.untaint ) do |src|
instance_eval( src.read.untaint, "(plugin/#{File::basename( file )})", 1 )
end
end

def eval_src( src, secure )
self.taint
@conf.taint
@body_enter_procs.taint
@body_leave_procs.taint
return Safe::safe( secure ? 4 : 1 ) do
eval( src, binding, "(TDiary::Plugin#eval_src)", 1 )
end
end

private
def add_header_proc( block = Proc::new )
@header_procs << block
end

def header_proc
r = []
@header_procs.each do |proc|
r << proc.call
end
r.join.chomp
end

def add_footer_proc( block = Proc::new )
@footer_procs << block
end

def footer_proc
r = []
@footer_procs.each do |proc|
r << proc.call
end
r.join.chomp
end

def add_update_proc( block = Proc::new )
@update_procs << block
end

def update_proc
@update_procs.each do |proc|
proc.call
end
''
end

def add_body_enter_proc( block = Proc::new )
@body_enter_procs << block
end

def body_enter_proc( date )
r = []
@body_enter_procs.each do |proc|
r << proc.call( date )
end
r.join
end

def add_body_leave_proc( block = Proc::new )
@body_leave_procs << block
end

def body_leave_proc( date )
r = []
@body_leave_procs.each do |proc|
r << proc.call( date )
end
r.join
end

def add_edit_proc( block = Proc::new )
@edit_procs << block
end

def edit_proc( date )
r = []
@edit_procs.each do |proc|
r << proc.call( date )
end
r.join
end

def add_form_proc( block = Proc::new )
@form_procs << block
end

def form_proc( date )
r = []
@form_procs.each do |proc|
r << proc.call( date )
end
r.join
end

def add_conf_proc( key, label, block = Proc::new )
return unless @mode =~ /^(conf|saveconf)$/
@conf_keys << key unless @conf_keys.index( key )
@conf_procs[key] = [label, block]
end

def each_conf_key
@conf_keys.each do |key|
yield key
end
end

def conf_proc( key )
r = ''
label, block = @conf_procs[key]
r = block.call if block
r
end

def conf_label( key )
label, block = @conf_procs[key]
label
end

def add_cookie( cookie )
begin
@cookies << cookie
rescue SecurityError
raise SecurityError, "can't use cookies in plugin when secure mode"
end
end

def apply_plugin( str, remove_tag = false )
return '' unless str
r = str.dup
if @options['apply_plugin'] and str.index( '<%' ) then
r = str.untaint if $SAFE < 3
Safe::safe( @conf.secure ? 4 : 1 ) do
begin
r = ERB::new( r ).result( binding )
rescue Exception
r = %Q|<p class="message">Invalid Text</p>#{r}|
end
end
end
r.gsub!( /<[^"'<>]*(?:"[^"]*"[^"'<>]*|'[^']*'[^"'<>]*)*(?:>|(?=<)|$)/, '' ) if remove_tag
r
end

def disp_referer( table, ref )
ref = @conf.to_native( CGI::unescape( ref ) )
str = nil
table.each do |url, name|
if /#{url}/i =~ ref then
str = ref.gsub( /#{url}/in, name )
break
end
end
str ? str : ref
end

def bot?
@conf.bot?
end

def method_missing( *m )
super if @debug
# ignore when no plugin
end
end

#
# module CategorizableDiary
#
module CategorizableDiary
def categorizable?; true; end
end

#
# module UncategorizableDiary
#
module UncategorizableDiary
def categorizable?; false; end
end

#
# class TDiaryBase
# tDiary CGI
#
class TDiaryBase
DIRTY_NONE = 0
DIRTY_DIARY = 1
DIRTY_COMMENT = 2
DIRTY_REFERER = 4

attr_reader :cookies
attr_reader :conf
attr_reader :date
attr_reader :diaries

def initialize( cgi, rhtml, conf )
@cgi, @rhtml, @conf = cgi, rhtml, conf
@diaries = {}
@cookies = []

unless @conf.io_class then
require 'tdiary/defaultio'
@conf.io_class = DefaultIO
end
@io = @conf.io_class.new( self )
end

def eval_rhtml( prefix = '' )
begin
r = do_eval_rhtml( prefix )
rescue PluginError, SyntaxError, ArgumentError
r = ERB::new( File::open( "#{PATH}/skel/plugin_error.rhtml" ) {|f| f.read }.untaint ).result( binding )
rescue Exception
raise
end
return r
end

def restore_parser_cache( date, key )
parser_cache( date, key )
end

def store_parser_cache( date, key, obj )
parser_cache( date, key, obj )
end

def clear_parser_cache( date )
parser_cache( date )
end

def last_modified
nil
end

def []( date )
@diaries[date.strftime( '%Y%m%d' )]
end

def calendar
@years = @io.calendar unless @years
end

protected
def do_eval_rhtml( prefix )
# load plugin files
load_plugins

# load and apply rhtmls
if cache_enable?( prefix ) then
r = File::open( "#{cache_path}/#{cache_file( prefix )}" ) {|f| f.read } rescue nil
end
if r.nil?
files = ["header.rhtml", @rhtml, "footer.rhtml"]
rhtml = files.collect {|file|
path = "#{PATH}/skel/#{prefix}#{file}"
begin
File::open( "#{path}.#{@conf.lang}" ) {|f| f.read }
rescue
File::open( path ) {|f| f.read }
end
}.join
r = ERB::new( rhtml.untaint ).result( binding )
r = ERB::new( r ).src
store_cache( r, prefix ) unless @diaries.empty?
end

# apply plugins
r = @plugin.eval_src( r.untaint, @conf.secure ) if @plugin
@cookies += @plugin.cookies
r
end

def mode
self.class.to_s.sub( /^TDiary::TDiary/, '' ).downcase
end

def load_plugins
calendar
@plugin = Plugin::new(
'conf' => @conf,
'mode' => mode,
'diaries' => @diaries,
'cgi' => @cgi,
'years' => @years,
'cache_path' => cache_path,
'date' => @date,
'comment' => @comment,
'last_modified' => last_modified
)
end

def <<( diary )
@diaries[diary.date.strftime( '%Y%m%d' )] = diary
end

def delete( date )
@diaries.delete( date.strftime( '%Y%m%d' ) )
end

def cache_path
@conf.cache_path || "#{@conf.data_path}cache"
end

def cache_file( prefix )
nil
end

def cache_enable?( prefix )
cache_file( prefix ) and FileTest::file?( "#{cache_path}/#{cache_file( prefix )}" )
end

def store_cache( cache, prefix )
unless FileTest::directory?( cache_path ) then
begin
Dir::mkdir( cache_path )
rescue Errno::EEXIST
end
end
if cache_file( prefix ) then
File::open( "#{cache_path}/#{cache_file( prefix )}", 'w' ) do |f|
f.flock(File::LOCK_EX)
f.write( cache )
end
end
end

def clear_cache( target = /.*/ )
Dir::glob( "#{cache_path}/*.r[bh]*" ).each do |c|
File::delete( c.untaint ) if target =~ c
end
end

def parser_cache( date, key = nil, obj = nil )
return nil if @ignore_parser_cache

require 'pstore'
unless FileTest::directory?( cache_path ) then
begin
Dir::mkdir( cache_path )
rescue Errno::EEXIST
end
end
file = date.strftime( "#{cache_path}/%Y%m.parser" )

unless key then
begin
File::delete( file )
File::delete( file + '~' )
rescue
end
return nil
end

begin
PStore::new( file ).transaction do |cache|
begin
unless obj then # restore
ver = cache.root?('version') ? cache['version'] : nil
if ver == TDIARY_VERSION and cache.root?(key)
obj = cache[key]
else
clear_cache
end
cache.abort
else # store
cache[key] = obj
cache['version'] = TDIARY_VERSION
end
rescue PStore::Error
end
end
rescue
begin
File::delete( file )
File::delete( file + '~' )
rescue
end
return nil
end
obj
end

def load_filters
return if @filters

@filters = []
filter_path = @conf.filter_path || "#{PATH}/tdiary/filter"
Dir::glob( "#{filter_path}/*.rb" ).sort.each do |file|
require file.untaint
@filters << TDiary::Filter::const_get( "#{File::basename( file, '.rb' ).capitalize}Filter" )::new( @cgi, @conf )
end
end

def comment_filter( diary, comment )
load_filters unless @filters
@filters.each do |filter|
return false unless filter.comment_filter( diary, comment )
end
true
end

def referer_filter( referer )
load_filters unless @filters
@filters.each do |filter|
return false unless filter.referer_filter( referer )
end
true
end
end

#
# class TDiaryAuthorOnlyBase
# base class for author-only access pages
#
class TDiaryAuthorOnlyBase < TDiaryBase
def csrf_protection_get_is_okay
false
end

def initialize( cgi, rhtml, conf )
super
csrf_check( cgi, conf )
end
private

def csrf_check( cgi, conf )
# CSRF condition check
protection_method = conf.options['csrf_protection_method']
masterkey = conf.options['csrf_protection_key']
updaterb_regexp = conf.options['csrf_protection_allowed_referer_regexp_for_update']

protection_method = 1 unless protection_method

return if protection_method == -1 # don't use this setting!

check_key = (protection_method & 2 != 0)
check_referer = (protection_method & 1 != 0)

masterkey = '' unless masterkey

updaterb_regexp = '' unless updaterb_regexp

if (masterkey != '' && check_key)
@csrf_protection="<input type=\"hidden\" name=\"csrf_protection_key\" value=\"#{CGI::escapeHTML(masterkey)}\">"
else
@csrf_protection="<!-- no CSRF protection key used -->"
end

referer = cgi.referer || ''
referer = referer.sub(/\?.*$/, '')
base_uri = URI.parse(conf.base_url)
config_uri = URI.parse(conf.base_url) + conf.update

referer_is_empty = referer == ''
referer_uri = URI.parse(referer) if !referer_is_empty
referer_is_config = !referer_is_empty && config_uri == referer_uri
referer_is_config ||= Regexp.new(updaterb_regexp) =~ referer if !referer_is_empty && updaterb_regexp != ''
is_post = cgi.request_method == 'POST'

given_key = nil
if cgi.valid?('csrf_protection_key')
given_key = cgi.params['csrf_protection_key'][0]
case given_key
when String
else
given_key = given_key.read
end
end

is_key_ok = masterkey != '' && given_key == masterkey

keycheck_ok = !check_key || is_key_ok
referercheck_ok = referer_is_config || (!check_referer && referer_is_empty)

if csrf_protection_get_is_okay then
return if is_post || given_key == nil
else
return if keycheck_ok && referercheck_ok
end

raise Exception.new(<<"EOS")
Security Error: Possible Cross-site Request Forgery (CSRF)

Diagnostics:
- Protection Method is #{ protection_method }
- Mode is #{ self.mode || 'unknown' }
- GET is #{ csrf_protection_get_is_okay ? '' : 'not '}allowed
- Request Method is #{ is_post ? 'POST' : 'not POST' }
- Referer is #{ referer_is_empty ? 'empty' : referer_is_config ? 'config' : 'another page' }
- Given referer: #{ CGI::escapeHTML( referer_uri.to_s )}
- Expected base URI: #{ CGI::escapeHTML( base_uri.to_s )}
- Expected update URI: #{ CGI::escapeHTML( config_uri.to_s )}
- CSRF key is #{ is_key_ok ? 'OK' : given_key ? 'NG (' + (given_key || '') + ')' : 'nothing' }
EOS
end

def load_plugins
super
@plugin.instance_eval("def csrf_protection\n#{(@csrf_protection || '').dump}\nend;")
end
end

#
# class TDiaryAdmin
# base class of administration
#
class TDiaryAdmin < TDiaryAuthorOnlyBase
def initialize( cgi, rhtml, conf )
super
begin
@date = Time::local( @cgi.params['year'][0].to_i, @cgi.params['month'][0].to_i, @cgi.params['day'][0].to_i )
rescue ArgumentError, NameError
raise TDiaryError, 'bad date'
end
end
end

#
# class TDiaryForm
# show diary append form
#
class TDiaryForm < TDiaryAdmin
def csrf_protection_get_is_okay; true; end

def initialize( cgi, rhtml, conf )
begin
super
rescue TDiaryError
end
@date = Time::now + (@conf.hour_offset * 3600).to_i
@diary = @io.diary_factory( @date, '', '', @conf.style )
end
end

#
# class TDiaryEdit
# show edit diary form
#
class TDiaryEdit < TDiaryAdmin
def csrf_protection_get_is_okay; true; end

def initialize( cgi, rhtm, conf )
super

@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = self[@date]
if @diary then
@conf.style = @diary.style
else
@diary = @io.diary_factory( @date, '', '', @conf.style )
end
DIRTY_NONE
end
end
end

#
# class TDiaryPreview
# preview diary
#
class TDiaryPreview < TDiaryAdmin
def initialize( cgi, rhtm, conf )
super

@title = @conf.to_native( @cgi.params['title'][0] )
@body = @conf.to_native( @cgi.params['body'][0] )
@old_date = @cgi.params['old'][0]
@hide = @cgi.params['hide'][0] == 'true' ? true : false

@io.transaction( @date ) do |diaries|
@diaries = diaries
diary = @diaries[@date.strftime( '%Y%m%d' )]
@conf.style = diary.style if diary
@diary = @io.diary_factory( @date, @title, @body, @conf.style )
@diary.show( ! @hide )
DIRTY_NONE
end
end

def eval_rhtml( prefix = '' )
begin
@show_result = true
r = do_eval_rhtml( prefix )
rescue PluginError, SyntaxError, ArgumentError
@exception = $!.dup
@show_result = false
r = super
end
r
end
end

#
# class TDiaryUpdate
# super class of diary saving classes
#
class TDiaryUpdate < TDiaryAdmin
def initialize( cgi, rhtml, conf )
@title = conf.to_native( cgi.params['title'][0] )
@body = conf.to_native( cgi.params['body'][0] )
@hide = cgi.params['hide'][0] == 'true' ? true : false
super
end

protected
def do_eval_rhtml( prefix )
super
@plugin.instance_eval { update_proc }
anchor_str = @plugin.instance_eval( %Q[anchor "#{@diary.date.strftime('%Y%m%d')}"].untaint )
clear_cache( /(latest|#{@date.strftime( '%Y%m' )})/ )
raise ForceRedirect::new( "#{@conf.index}#{anchor_str}" )
end
end

#
# class TDiaryAppend
# append diary
#
class TDiaryAppend < TDiaryUpdate
def initialize( cgi, rhtml, conf )
begin
super
rescue TDiaryError
@date = newdate
end
@author = @conf.multi_user ? @cgi.remote_user : nil

@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = self[@date] || @io.diary_factory( @date, @title, '', @conf.style )
self << @diary.append( @body, @author )
@diary.set_title( @title ) unless @title.empty?
@diary.show( ! @hide )
DIRTY_DIARY
end
end

protected
def newdate
Time::now + (@conf.hour_offset * 3600).to_i
end
end

#
# class TDiaryReplace
# replace diary
#
class TDiaryReplace < TDiaryUpdate
def initialize( cgi, rhtm, conf )
super
old_date = @cgi.params['old'][0]

@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = self[@date]
if @diary then
if @date.strftime( '%Y%m%d' ) != old_date then
@diary.append( @body, @append )
@diary.set_title( @title ) if @title.length > 0
else
@diary.replace( @date, @title, @body )
end
else
@diary = @io.diary_factory( @date, @title, @body, @conf.style )
end
@diary.show( ! @hide )
self << @diary
DIRTY_DIARY
end
end
end

#
# class TDiaryShowComment
# change visible mode of comments
#
class TDiaryShowComment < TDiaryAdmin
def initialize( cgi, rhtml, conf )
super

@io.transaction( @date ) do |diaries|
@diaries = diaries
dirty = DIRTY_NONE
@diary = self[@date]
if @diary then
idx = 0
@diary.each_comment( 100 ) do |com|
com.show = @cgi.params[(idx += 1).to_s][0] == 'true' ? true : false;
end
self << @diary
clear_cache( /(latest|#{@date.strftime( '%Y%m' )})/ )
dirty = DIRTY_COMMENT
end
dirty
end
end

def eval_rhtml( prefix = '' )
load_plugins
@plugin.instance_eval { update_proc }
super
end
end

#
# class TDiaryFormPlugin
# show edit diary form after calling form plugin.
#
class TDiaryFormPlugin < TDiaryAuthorOnlyBase
def initialize( cgi, rhtm, conf )
super

if @cgi.valid?( 'date' ) then
if @cgi.params['date'][0].kind_of?( String ) then
date = @cgi.params['date'][0]
else
date = @cgi.params['date'][0].read
end
@date = Time::local( *date.scan( /(\d{4})(\d\d)(\d\d)/ )[0] )
else
@date = Time::now + (@conf.hour_offset * 3600).to_i
@diary = @io.diary_factory( @date, '', '', @conf.style )
end

@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = self[@date]
if @diary then
@conf.style = @diary.style
else
@diary = @io.diary_factory( @date, '', '', @conf.style )
end
DIRTY_NONE
end
end
end

#
# class TDiaryConf
# show configuration form
#
class TDiaryConf < TDiaryAuthorOnlyBase
def csrf_protection_get_is_okay; true; end

def initialize( cgi, rhtml, conf )
super
@key = @cgi.params['conf'][0]
end
end

#
# class TDiarySaveConf
# save configuration
#
class TDiarySaveConf < TDiaryConf
def csrf_protection_get_is_okay; false; end

def initialize( cgi, rhtml, conf )
super
end

def eval_rhtml( prefix = '' )
r = super

begin
@conf.save
clear_cache
rescue
@error = [$!.dup, $@.dup]
end

r
end
end

#
# class TDiaryView
# base of view mode classes
#
class TDiaryView < TDiaryBase
def initialize( cgi, rhtml, conf )
super

# save referer to latest
if (!@conf.referer_day_only or (@cgi.params['date'][0] and @cgi.params['date'][0].length == 8)) and referer_filter( @cgi.referer ) then
ym = latest_month
@date = ym ? Time::local( ym[0], ym[1] ) : Time::now
@io.transaction( @date ) do |diaries|
@diaries = diaries
dirty = DIRTY_NONE
@diaries.keys.sort.reverse_each do |key|
@diary = @diaries[key]
break if @diary.visible?
end
if @diary then
@diary.add_referer( @cgi.referer )
dirty = DIRTY_REFERER
end
dirty
end
end
end

def last_modified
lm = Time::at( 0 )
@diaries.each_value do |diary|
lmd = diary.last_modified
lm = lmd if lm < lmd and diary.visible?
end
lm
end

protected
def each_day
@diaries.keys.sort.each do |date|
diary = @diaries[date]
next unless diary.visible?
yield diary
end
end

def latest_month
result = nil
calendar
@years.keys.sort.reverse_each do |year|
@years[year.to_s].sort.reverse_each do |month|
result = [year, month]
break
end
break
end
result
end

def oldest_month
result = nil
calendar
@years.keys.sort.each do |year|
@years[year.to_s].sort.each do |month|
result = [year, month]
break
end
break
end
result
end

def cache_enable?( prefix )
super and (File::mtime( "#{cache_path}/#{cache_file( prefix )}" ) > last_modified )
end
end

#
# class TDiaryDay
# show day mode view
#
class TDiaryDay < TDiaryView
def initialize( cgi, rhtm, conf )
super
begin
# time is noon for easy to calc leap second.
load( Time::local( *@cgi.params['date'][0].scan( /^(\d{4})(\d\d)(\d\d)$/ )[0] ) + 12*60*60 )
rescue ArgumentError, NameError
raise TDiaryError, 'bad date'
end
@diary = nil if @diary and not @diary.visible?
end

def last_modified
@diary ? @diary.last_modified : Time::at( 0 )
end

protected
def load( date )
if not @diary or (@diary.date.dup + 12*60*60).gmtime.strftime( '%Y%m%d' ) != date.dup.gmtime.strftime( '%Y%m%d' ) then
@date = date
@io.transaction( @date ) do |diaries|
@diaries = diaries
dirty = DIRTY_NONE
@diary = self[@date]
if @diary and referer_filter( @cgi.referer ) then
@diary.add_referer( @cgi.referer )
dirty = DIRTY_REFERER
end
dirty
end
else
@date = date
@diary = self[@date]
end
end

def cookie_name
@cgi.cookies['tdiary'][0] or ''
end

def cookie_mail
@cgi.cookies['tdiary'][1] or ''
end
end

#
# class TDiaryComment
# save a comment
#
class TDiaryComment < TDiaryDay
def initialize( cgi, rhtml, conf )
super
end

protected
def load( date )
@date = date
@name = @conf.to_native( @cgi.params['name'][0] )
@mail = @cgi.params['mail'][0]
@body = @conf.to_native( @cgi.params['body'][0] )
@comment = Comment::new( @name, @mail, @body )

dirty = DIRTY_NONE
@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = self[@date]
if @diary and comment_filter( @diary, @comment ) then
@diary.add_comment( @comment )
dirty = DIRTY_COMMENT
cookie_path = File::dirname( @cgi.script_name )
cookie_path += '/' if cookie_path !~ /\/$/
@cookies << CGI::Cookie::new( {
'name' => 'tdiary',
'value' => [@name,@mail],
'path' => cookie_path,
'expires' => Time::now.gmtime + 90*24*60*60 # 90days
} )
else
@comment = nil
end
dirty
end
end

def do_eval_rhtml( prefix )
load_plugins
@plugin.instance_eval { update_proc } if @comment
anchor_str = @plugin.instance_eval( %Q[anchor "#{@diary.date.strftime('%Y%m%d')}"].untaint )
raise ForceRedirect::new( "#{@conf.index}#{anchor_str}#c#{'%02d' % @diary.count_comments( true )}" )
end
end

#
# class TDiaryMonth
# show month mode view
#
class TDiaryMonth < TDiaryView
def initialize( cgi, rhtml, conf )
super

begin
date = Time::local( *@cgi.params['date'][0].scan( /^(\d{4})(\d\d)$/ )[0] )
d1 = @date.dup.gmtime if @date
d2 = date.dup.gmtime
if not @date or d1.year != d2.year or d1.month != d2.month then
@date = date
@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = @diaries[@diaries.keys.sort.reverse[0]]
DIRTY_NONE
end
end
rescue ArgumentError, NameError
raise TDiaryError, 'bad date'
end
end

protected
def cache_file( prefix )
"#{prefix}#{@rhtml.sub( /month/, @date.strftime( '%Y%m' ) ).sub( /\.rhtml$/, '.rb' )}"
end
end

#
# class TDiaryNYear
# show nyear mode view
#
class TDiaryNYear < TDiaryView
def initialize(cgi, rhtml, conf)
super

@diaries = {}
month, day = @cgi.params['date'][0].scan(/^(\d\d)(\d\d)$/)[0]
nyear(month).each do |y, m|
@date = Time::local(y, m)
@io.transaction(@date) do |diaries|
ymd = y + m + day
@diaries[ymd] = diaries[ymd] if diaries[ymd]
DIRTY_NONE
end
end
end

protected
def nyear(month)
r = []
calendar
@years.keys.reverse_each do |year|
r << [year, month] if @years[year].include? month
end
r
end
end


#
# class TDiaryLatest
# show latest mode view
#
class TDiaryLatest < TDiaryView
def initialize( cgi, rhtml, conf )
super
if @cgi.params['date'][0] then
ym = [@cgi.params['date'][0][0,4].to_i, @cgi.params['date'][0][4,2].to_i]
@date = nil
else
ym = latest_month
end
unless @date then
@date = ym ? Time::local( ym[0], ym[1] ) : Time::now
@io.transaction( @date ) do |diaries|
@diaries = diaries
if @cgi.params['date'][0] then
@diary = @diaries[@cgi.params['date'][0][0,8]]
@date = @diary.date if @diary
end
unless @diary then
@diary = @diaries[@diaries.keys.sort.reverse[0]]
@date = @diary.date if @diary
end
DIRTY_NONE
end
end

if ym then
# read +2 days for calc ndays.prev in count_diaries method
limit = limit_size( @conf.latest_limit ) + 2

# read next month data until limit
y = ym[0].to_i
m = ym[1].to_i
latest = latest_month
diaries_tmp = {}.update( @diaries )
diaries_size = count_diaries_after( diaries_tmp )
while ( latest and diaries_size < limit )
date = if m == 12 then
Time::local( y += 1, m = 1 )
else
Time::local( y, m += 1 )
end
break if date > Time::local( *latest )
@io.transaction( date ) do |diaries|
diaries_tmp.update( diaries )
diaries_size = count_diaries_after( diaries_tmp )
DIRTY_NONE
end
end

# read prev month data until limit
y = ym[0].to_i
m = ym[1].to_i
oldest = oldest_month
diaries_size = count_diaries_before( @diaries )
while ( oldest and diaries_size < limit )
date = if m == 1 then
Time::local( y -= 1, m = 12 )
else
Time::local( y, m -= 1 )
end
break if date < Time::local( *oldest )
@io.transaction( date ) do |diaries|
@diaries.update( diaries )
diaries_size = count_diaries_before( @diaries )
DIRTY_NONE
end
end
end
end

def latest( limit = 5 )
start = start_date
limit = limit_size( limit )
idx = 0
@diaries.keys.sort.reverse_each do |date|
next if date > start
diary = @diaries[date]
next unless diary.visible?
yield diary
idx += 1
break if idx >= limit
end
end

protected
def count_diaries_after( diaries )
start = start_date
limit = limit_size( @conf.latest_limit )
diaries_size = 0
continue_exist = true
diaries.keys.sort.each do |date|
if diaries[date].visible? and date > start then
continue_exist = true if diaries_size < limit
@conf['ndays.next'] = date if diaries_size < limit
diaries_size += 1
end
end
@conf['ndays.next'] = nil unless continue_exist
diaries_size
end

def count_diaries_before( diaries )
start = start_date
limit = limit_size( @conf.latest_limit )
diaries_size = 0
continue_exist = false
diaries.keys.sort.reverse_each do |date|
if diaries[date].visible? and date <= start then
continue_exist = true if diaries_size >= limit
@conf['ndays.prev'] = date if diaries_size <= limit
diaries_size += 1
end
end
@conf['ndays.prev'] = nil unless continue_exist
diaries_size
end

def cache_file( prefix )
if @cgi.params['date'][0] then
nil
else
"#{prefix}#{@rhtml.sub( /\.rhtml$/, '.rb' )}"
end
end

def start_date
if @cgi.params['date'][0] then
@cgi.params['date'][0][0,8]
else
'99999999' # max of date string
end
end

def limit_size( default_limit )
if @cgi.params['date'][0] then
date = @cgi.params['date'][0]
limit = date[9,date.length-9].to_i
limit = 30 if limit > 30
limit
else
default_limit
end
end
end

#
# class TDiaryCategoryView
# base of category view mode classes
#
class TDiaryCategoryView < TDiaryBase
attr_reader :last_modified
def initialize(cgi, rhtml, conf)
super
@last_modified = Time.now
end
end

#
# exception class for TrackBack
#
class TDiaryTrackBackError < StandardError
end

#
# class TDiaryTrackBackBase
#
class TDiaryTrackBackBase < TDiaryBase
public :mode
def initialize( cgi, rhtml, conf )
super
date = @cgi.request_uri.scan(%r!/(\d{4})(\d\d)(\d\d)!)[0]
if date
@date = Time::local(*date)
else
@date = Time::now
end
end

def diary_url
@conf.base_url + @conf.index.sub(%r|^\./|, '') + @plugin.instance_eval(%Q|anchor "#{@date.strftime('%Y%m%d')}"|)
end

def self.success_response
<<HERE
<?xml version="1.0" encoding="iso-8859-1"?>
<response>
<error>0</error>
</response>
HERE
end

def self.fail_response(reason)
<<HERE
<?xml version="1.0" encoding="iso-8859-1"?>
<response>
<error>1</error>
<message>#{reason}</message>
</response>
HERE
end
end

#
# class TDiaryTrackBackRSS
# generate RSS
#
class TDiaryTrackBackRSS < TDiaryTrackBackBase
def initialize( cgi, rhtml, conf )
super
@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = @diaries[@date.strftime('%Y%m%d')]
DIRTY_NONE
end
end

def eval_rhtml( prefix = '' )
raise TDiaryTrackBackError.new("invalid date: #{@date.strftime('%Y%m%d')}") unless @diary
load_plugins
r = <<RSSHEAD
<?xml version="1.0" encoding="#{@conf.encoding}"?>
<response>
<error>0</error>
<rss version="0.91">
<channel>
<title>#{@diary.title}</title>
<link>#{diary_url}</link>
<description></description>
<language>#{@conf.html_lang}</language>
RSSHEAD
@diary.each_comment(100) do |com, idx|
begin
next unless com.visible_true?
rescue NameError, NoMethodError
next unless com.visible?
end
next unless /^(TrackBack|Pingback)$/ =~ com.name
url, blog_name, title, excerpt = com.body.split(/\n/, 4)
r << <<RSSITEM
<item>
<title>#{CGI::escapeHTML( title )}</title>
<link>#{CGI::escapeHTML( url )}</link>
<description>#{CGI::escapeHTML( excerpt )}</description>
</item>
RSSITEM
end
r << <<RSSFOOT
</channel>
</rss>
</response>
RSSFOOT
end
end

#
# class TDiaryTrackBackReceive
# receive TrackBack ping and store as comment
#
class TDiaryTrackBackReceive < TDiaryTrackBackBase
def initialize( cgi, rhtml, conf )
super
@error = nil

url = @cgi.params['url'][0]
blog_name = @conf.to_native( @cgi.params['blog_name'][0] || '' )
title = @conf.to_native( @cgi.params['title'][0] || '' )
excerpt = @conf.to_native( @cgi.params['excerpt'][0] || '' )
if excerpt.length > 255
excerpt = @conf.shorten( excerpt, 252 )
end

body = [url, blog_name, title, excerpt].join("\n")
@cgi.params['name'] = ['TrackBack']
@cgi.params['body'] = [body]

@comment = Comment::new('TrackBack', '', body)
begin
@io.transaction( @date ) do |diaries|
@diaries = diaries
@diary = @diaries[@date.strftime('%Y%m%d')]
if @diary and comment_filter( @diary, @comment ) then
@diary.add_comment(@comment)
DIRTY_COMMENT
else
@comment = nil
DIRTY_NONE
end
end
rescue
@error = $!.message
end
end

def eval_rhtml( prefix = '' )
raise TDiaryTrackBackError.new(@error) if @error
load_plugins
@plugin.instance_eval { update_proc }
TDiaryTrackBackBase::success_response
end
end

#
# class TDiaryTrackBackShow
# show TrackBacks
#
class TDiaryTrackBackShow < TDiaryTrackBackBase
def eval_rhtml( prefix = '' )
load_plugins
anchor_str = @plugin.instance_eval(%Q|anchor "#{@date.strftime('%Y%m%d')}"|)
url = "#{@conf.index}#{anchor_str}#t"
url[0, 0] = '../' if %r|^https?://|i !~ @conf.index
raise ForceRedirect::new( url )
end
end
end

# vim: ts=3
Something went wrong with that request. Please try again.