tudu-web-1 /library/Dao/Td/Tudu/Tudu.php

Language PHP Lines 2328
MD5 Hash 82f155822ecd9b08f290aa459db9b898
Repository https://github.com/polokk/tudu-web-1.git View Raw File
   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
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
<?php
/**
 * Tudu Dao
 *
 * LICENSE
 *
 *
 * @category   Dao
 * @package    Dao_Td
 * @subpackage Tudu
 * @copyright  Copyright (c) 2009-2010 Shanghai Best Oray Information S&T CO., Ltd.
 * @link       http://www.oray.com/
 * @version    $Id: Tudu.php 2809 2013-04-07 09:57:05Z cutecube $
 */

/**
 * @category   Dao
 * @package    Dao_Td
 * @subpackage Tudu
 * @copyright  Copyright (c) 2009-2010 Shanghai Best Oray Information S&T CO., Ltd.
 */
class Dao_Td_Tudu_Tudu extends Oray_Dao_Abstract
{
    const STATUS_UNSTART  = 0;   // 未开始
    const STATUS_DOING    = 1;   // 进行中
    const STATUS_DONE     = 2;   // 已完成
    const STATUS_REJECT   = 3;   // 已拒绝
    const STATUS_CANCEL   = 4;   // 已取消

    const SPECIAL_CYCLE = 1;
    const SPECIAL_VOTE  = 2; // 投票

    const TYPE_TASK    = 'task';
    const TYPE_NOTICE  = 'notice';
    const TYPE_DISCUSS = 'discuss';
    const TYPE_MEETING = 'meeting';

    /**
     * 用户角色
     * @var string
     */
    const ROLE_ACCEPTER = 'to';      // 接收人
    const ROLE_SENDER   = 'from';    // 发送人
    const ROLE_CC       = 'cc';      // 被抄送

    /**
     * Initialize object
     *
     * Called from {@link __construct()} as final step of object instantiation.
     *
     * @return void
     */
    public function init()
    {}

    /**
     * Get record
     *
     * SELECT t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.cycle_id AS cycleid,
     * t.type, t.subject, t.from, t.to, t.cc, t.priority, t.privacy,
     * p.post_id AS postid, p.content, p.poster_info AS posterinfo, p.attach_num AS attachnum,
     * t.last_post_time AS lastposttime, t.last_poster AS lastposter,
     * t.view_num AS viewnum, t.reply_num AS replynum, t.log_num AS lognum,
     * t.percent, t.score, t.status, t.special,
     * t.start_time AS starttime, t.end_time AS endtime,
     * t.total_time AS totaltime, t.elapsed_time AS elapsedtime,
     * t.accept_time AS accepttime, t.create_time AS create_time,
     * tu.unique_id AS uniqueid, TRIM(LEADING ',' FROM tu.labels) labels,
     * tu.is_read AS isread, tu.is_forward AS isforward,
     * t.is_draft AS isdraft, t.is_done AS isdone
     * FROM td_tudu t
     * LEFT JOIN td_post p ON p.tudu_id = t.tudu_id AND p.is_first = 1
     * LEFT JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id AND tu.unique_id = ?
     * WHERE t.tudu_id = ?
     *
     * @param array $condition
     * @param array $filter
     * @return Dao_Td_Tudu_Record_Tudu
     */
    public function getTudu(array $condition, $filter = null)
    {
        if (empty($condition['tuduid'])
            || empty($condition['uniqueid'])) {
            return null;
        }

        $table   = "td_tudu t "
                 . "LEFT JOIN td_post p ON p.tudu_id = t.tudu_id AND p.is_first = 1 "
                 . "LEFT JOIN td_tudu_group g ON g.tudu_id = p.tudu_id "
                 . "LEFT JOIN td_class c ON t.class_id = c.class_id AND t.org_id = c.org_id AND t.board_id = c.board_id "
                 . "LEFT JOIN td_flow f ON t.flow_id = f.flow_id AND t.org_id = f.org_id AND t.board_id = f.board_id "
                 . "LEFT JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id AND tu.unique_id = "
                 . $this->_db->quote($condition['uniqueid']) . " "
                 . "LEFT JOIN td_tudu_flow fl ON fl.tudu_id = t.tudu_id";

        $columns = "t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.cycle_id AS cycleid, t.prev_tudu_id AS prevtuduid, "
                 . "t.type, t.subject, t.from, t.to, t.cc, t.bcc, t.priority, t.privacy, t.password, t.is_auth AS isauth, fl.current_step_id AS stepid, "
                 . "p.post_id AS postid, p.content, p.header, p.poster_info AS posterinfo, p.attach_num AS attachnum, t.app_id AS appid, "
                 . "t.last_post_time AS lastposttime, t.last_poster AS lastposter, t.last_forward AS lastforward, "
                 . "t.view_num AS viewnum, t.reply_num AS replynum, t.log_num AS lognum, t.cycle_num AS cyclenum, "
                 . "fl.step_num as stepnum, t.percent, t.score, t.status, t.special, t.notify_all AS notifyall, t.accep_mode AS accepmode,"
                 . "t.start_time AS starttime, t.end_time AS endtime, t.need_confirm AS needconfirm, "
                 . "t.total_time AS totaltime, t.elapsed_time AS elapsedtime, "
                 . "t.accept_time AS accepttime, t.create_time AS createtime, "
                 . "tu.unique_id AS uniqueid, TRIM(LEADING ',' FROM tu.labels) labels, "
                 . "tu.is_read AS isread, tu.is_forward AS isforward, tu.mark, "
                 . "tu.role, tu.percent AS selfpercent, tu.forward_info AS forwardinfo, "
                 . "tu.tudu_status AS selftudustatus, tu.accept_time AS selfaccepttime, tu.auth_code AS authcode, "
                 . "t.is_draft AS isdraft, t.is_done AS isdone, t.is_top AS istop, p.is_send AS issend, "
                 . "t.class_id AS classid, t.flow_id AS flowid, c.class_name AS classname, "
                 . "g.type AS nodetype, g.parent_tudu_id AS parentid, g.root_tudu_id AS rootid";
        $where   = array();

        $where[] = 't.tudu_id = ' . $this->_db->quote($condition['tuduid']);

        if (isset($filter['orgid'])) {
            $where[] = 't.org_id = ' . $this->_db->quote($filter['orgid']);
        }

        // WHERE
        $where = implode(' AND ', $where);

        $sql = "SELECT {$columns} FROM {$table} WHERE {$where} LIMIT 0, 1";

        $record = $this->_db->fetchRow($sql);

        if (!$record) {
            return null;
        }

        return Oray_Dao::record('Dao_Td_Tudu_Record_Tudu', $record);
    }


    /**
     * Get records
     *
     * SQL here..
     *
     * @param array $condition
     * @param array $filter
     * @param array $sort
     * @param int   $maxCount
     * @return Oray_Dao_Recordset
     */
    public function getTudus(array $condition, $filter = null, $sort = null, $maxCount = null)
    {
        $table   = "td_tudu t LEFT JOIN td_tudu_group g ON t.tudu_id = g.tudu_id";
        $columns = 't.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, `from`, `to`, is_draft AS isdraft, subject, '
                 . 'g.type AS nodetype, g.parent_tudu_id AS parentid';
        $where   = array();
        $order   = array();
        $limit   = '';

        if (!empty($condition['tuduids']) && is_array($condition['tuduids'])) {
            $where[] = 't.tudu_id IN(' . implode(',', array_map(array($this->_db, 'quote'), $condition['tuduids'])) . ')';
        }

        if (!empty($condition['parentid'])) {
            $where[] = 'g.parent_tudu_id = ' . $this->_db->quote($condition['parentid']);

            if (!empty($condition['uniqueid'])) {
                $where[] = 'g.unique_id = ' . $this->_db->quote($condition['uniqueid']);
            }
        }

        if (empty($where)) {
            return new Oray_Dao_Recordset();
        }

        // WHERE
        $where = implode(' AND ', $where);
        if ($where) {
            $where = 'WHERE ' . $where;
        }

        $sort  = $this->_formatSort($sort);
        foreach ($sort as $key => $val) {
            switch ($key) {
                default:
                    continue 2;
            }
            $order[] = $key . ' ' . $val;
        }

        // ORDER
        $order = implode(', ', $order);
        if ($order) {
            $order = 'ORDER BY ' . $order;
        }

        // LIMIT
        if (is_int($maxCount) && $maxCount > 0) {
            $limit = 'LIMIT ' . $maxCount;
        }

        $sql = "SELECT $columns FROM $table $where $order $limit";
        $records = $this->_db->fetchAll($sql);

        return new Oray_Dao_Recordset($records, 'Dao_Td_Tudu_Record_Tudus');
    }

    /**
     *
     * @param $condition
     * @param $filter
     */
    public function getUserTudus(array $condition, $filter = null, $offset = null, $count = null)
    {
        $table = "td_tudu t "
               . "LEFT JOIN td_tudu_group g ON g.tudu_id = t.tudu_id "
               . "LEFT JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id AND tu.unique_id = "
               . $this->_db->quote($condition['uniqueid'])
               . "LEFT JOIN td_post AS p ON p.tudu_id = t.tudu_id AND p.is_first = 1";

        $columns = "t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.is_done AS isdone, t.percent, t.cycle_id AS cycleid, t.percent, t.reply_num AS replynum, t.accept_time AS lastaccepttime, "
                 . "t.last_post_time AS lastposttime, t.is_done, t.priority, t.privacy, t.password, t.start_time AS starttime, t.end_time AS endtime, p.attach_num AS attachnum, tu.accept_time as accepttime, "
                 . "t.type, t.subject, t.from, t.to, t.cc, t.bcc, t.status, t.is_draft AS isdraft, t.need_confirm AS needconfirm, tu.unique_id AS uniqueid, "
                 . "TRIM(LEADING ',' FROM tu.labels) labels, tu.role, tu.accepter_info AS accepterinfo, tu.tudu_status AS selfstatus, tu.is_read as isread, g.type as nodetype ";
        $where   = array();
        $limit   = '';

        if (empty($condition)) {
            return null;
        }

        if (!empty($condition['uniqueid'])) {
            $where[] = 'tu.unique_id = ' . $this->_db->quote($condition['uniqueid']);
        }

        if (!empty($condition['labelid'])) {
            $table  .= ' LEFT JOIN td_tudu_label AS tl ON tl.unique_id = tu.unique_id AND tl.tudu_id = tu.tudu_id';
            $where[] = 'tl.label_id = ' . $this->_db->quote($condition['labelid']);
        }

        if (!empty($condition['type'])) {
            $where[] = 't.type = ' . $this->_db->quote($condition['type']);
        }

        // 关键字
        if (!empty($condition['keyword'])) {
            $keyword = $this->_db->quote('%' . $condition['keyword'] . '%');
            $where[] = 't.subject LIKE ' . $keyword;
        }

        if (!$filter || !isset($filter['role']) || $filter['role'] == true) {
            $where[] = 'tu.role IS NOT NULL';
        }

        if (!$filter || !isset($filter['isdone']) || $filter['isdone'] == true) {
            $where[] = 't.status <= 2';
            $where[] = 't.is_done = 0';
        }

        $where = implode(' AND ', $where);
        if ($where) {
            $where = 'WHERE ' . $where;
        }

        if (null !== $count) {
            $limit = 'LIMIT';
            if (null !== $offset) {
                $limit .= ' ' . (int) $offset . ',';
            }

            $limit .= ' ' . (int) $count;
        }

        $sql = "SELECT $columns FROM $table $where ORDER BY last_post_time DESC $limit";

        $records = $this->_db->fetchAll($sql);

        if (!$records) {
            return array();
        }

        return $records;
    }

    /**
     * 读取图度组
     *
     * @param array $condition
     * @param array $filter
     */
    public function getTuduGroups(array $condition, $filter = null)
    {
        $table   = "td_tudu t "
                 . "LEFT JOIN td_tudu_group g ON g.tudu_id = t.tudu_id "
                 . "INNER JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id";
        $columns = "t.org_id AS orgid, t.board_id AS boardid, tu.unique_id AS uniqueid, t.tudu_id AS tuduid, "
                 . "t.subject, t.type, t.from, t.to, g.type AS nodetype";
        $where   = array();
        $bind    = array();

        if (isset($condition['uniqueid'])) {
            $where[] = "tu.unique_id = :uniqueid";
            $bind['uniqueid'] = $condition['uniqueid'];
        }

        if (isset($condition['orgid'])) {
            $where[] = "t.org_id = :orgid";
            $bind['orgid'] = $condition['orgid'];
        }

        if ($filter && array_key_exists('isdraft', $filter)) {
            if (null !== $filter['isdraft']) {
                $where[] = "t.is_draft = " . ($filter['isdraft'] ? 1 : 0);
            }
        } else {
            $where[] = "t.is_draft = 0";
        }

        if ($filter && array_key_exists('isdone', $filter)) {
            if (null !== $filter['isdone']) {
                $where[] = "t.is_done = " . ($filter['isdone'] ? 1 : 0);
            }
        } else {
            $where[] = "t.is_done = 0";
        }

        $where[] = "(g.type = 'node' OR  g.type = 'root')";

        // WHERE
        $where = implode(' AND ', $where);
        if ($where) {
            $where = 'WHERE ' . $where;
        }

        $sql = "SELECT $columns FROM $table $where ORDER BY t.last_post_time DESC";

        $records = $this->_db->fetchAll($sql, $bind);

        if (!$records) {
            return new Oray_Dao_Recordset();
        }

        return new Oray_Dao_Recordset($records, 'Dao_Td_Tudu_Record_TuduGroups');
    }

    /**
     *
     *
     * @param $condition
     * @param $filter
     * @param $sort
     * @param $maxCount
     */
    public function getGroupTudus(array $condition, $filter = null, $sort = null, $maxCount = null)
    {
        $table   = "td_tudu t "
                 . "LEFT JOIN td_post p ON p.tudu_id = t.tudu_id AND p.is_first = 1 "
                 . "LEFT JOIN td_tudu_group g ON g.tudu_id = p.tudu_id "
                 . "LEFT JOIN td_class c ON t.class_id = c.class_id AND t.org_id = c.org_id AND t.board_id = c.board_id "
                 . "LEFT JOIN td_tudu_flow fl ON fl.tudu_id = t.tudu_id "
                 . "LEFT JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id AND tu.unique_id = "
                 . $this->_db->quote($condition['uniqueid']);

        $columns = "t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.cycle_id AS cycleid, t.prev_tudu_id AS prevtuduid, "
                 . "t.type, t.subject, t.from, t.to, t.cc, t.priority, t.privacy, t.password, fl.current_step_id AS stepid, "
                 . "p.post_id AS postid, '' AS content, '' AS posterinfo, p.attach_num AS attachnum, "
                 . "t.last_post_time AS lastposttime, t.last_poster AS lastposter, t.last_forward AS lastforward, "
                 . "t.view_num AS viewnum, t.reply_num AS replynum, t.log_num AS lognum, "
                 . "t.percent, t.score, t.status, t.special, t.notify_all AS notifyall, t.accep_mode AS accepmode, "
                 . "t.start_time AS starttime, t.end_time AS endtime, t.complete_time AS completetime, t.need_confirm AS needconfirm, "
                 . "t.total_time AS totaltime, t.elapsed_time AS elapsedtime, "
                 . "t.accept_time AS accepttime, t.create_time AS createtime, "
                 . "tu.unique_id AS uniqueid, TRIM(LEADING ',' FROM tu.labels) labels, "
                 . "tu.is_read AS isread, tu.is_forward AS isforward, tu.mark, "
                 . "tu.role, tu.percent AS selfpercent, tu.forward_info AS forwardinfo, "
                 . "tu.tudu_status AS selftudustatus, tu.accept_time AS selfaccepttime, "
                 . "t.is_draft AS isdraft, t.is_done AS isdone, t.is_top AS istop, p.is_send AS issend, "
                 . "t.class_id AS classid, t.flow_id AS flowid, c.class_name AS classname, "
                 . "g.type AS nodetype, g.parent_tudu_id AS parentid";
        $where   = array();
        $order   = array();
        $limit   = '';

        if (!empty($condition['tuduids']) && is_array($condition['tuduids'])) {
            $where[] = 't.tudu_id IN(' . implode(',', array_map(array($this->_db, 'quote'), $condition['tuduids'])) . ')';
        }

        if (!empty($condition['parentid'])) {
            $where[] = 'g.parent_tudu_id = ' . $this->_db->quote($condition['parentid']);
        }

        if (!empty($condition['senderid'])) {
            $where[] = 'g.unique_id = ' . $this->_db->quote($condition['senderid']);
        }

        if (!empty($condition['role'])) {
            $where[] = 'tu.role = ' . $this->_db->quote($condition['role']);
        }

        if (!empty($condition['starttime']) && !empty($condition['endtime'])) {
            $startTime = (int) $condition['starttime'];
            $endTime   = (int) $condition['endtime'];
            $where[] = "(((t.start_time >= {$startTime} AND t.start_time <= {$endTime}) "
                 . "OR (t.end_time >= {$startTime} AND t.end_time <= {$endTime}) "
                 . "OR ((t.start_time <= {$startTime} OR t.start_time IS NULL) "
                 . "AND (t.end_time >= {$endTime} OR t.end_time IS NULL)))"
                 . "AND (((t.complete_time <= {$endTime} AND t.complete_time >= {$startTime}) "
                 . "OR (t.complete_time >= {$endTime} AND t.complete_time >= {$startTime})) "
                 . "OR t.complete_time IS NULL) OR (t.status <= 1 AND DATEDIFF(FROM_UNIXTIME(UNIX_TIMESTAMP(), '%Y-%m-%d'), FROM_UNIXTIME(t.end_time, '%Y-%m-%d')) > 0 AND t.end_time <= {$endTime}))";

            // 不显示“已取消”,和“已拒绝并确认“的图度
            $where[] = '(t.status <= 2 OR (t.status = 3 AND t.is_done = 0)) ';
        }

        if ($filter && array_key_exists('isdraft', $filter)) {
            if (null !== $filter['isdraft']) {
                $where[] = 't.is_draft = ' . ($filter['isdraft'] ? 1 : 0);
            }
        } else {
            $where[] = 't.is_draft = 0';
        }

        if (empty($where)) {
            return new Oray_Dao_Recordset();
        }

        // WHERE
        $where = implode(' AND ', $where);
        if ($where) {
            $where = 'WHERE ' . $where;
        }

        $sort  = $this->_formatSort($sort);
        foreach ($sort as $key => $val) {
            switch ($key) {
                case 'lastposttime':
                    $key = 'last_post_time';
                    break;
                case 'subject':
                    $key = 'subject';
                    break;
                case 'endtime':
                    $key = 'end_time';
                    break;
                case 'from':
                    $key = '`from`';
                    break;
                case 'to':
                    $key = '`to`';
                    break;
                case 'istop':
                    $key = 'is_top';
                    break;
                default:
                    continue 2;
                    break;
            }
            $order[] = $key . ' ' . $val;
        }

        // ORDER
        $order = implode(', ', $order);
        if ($order) {
            $order = 'ORDER BY ' . $order;
        }

        // LIMIT
        if (is_int($maxCount) && $maxCount > 0) {
            $limit = 'LIMIT ' . $maxCount;
        }

        $sql = "SELECT $columns FROM $table $where $order $limit";

        $records = $this->_db->fetchAll($sql);

        return new Oray_Dao_Recordset($records, 'Dao_Td_Tudu_Record_Tudu');
    }

    /**
     * 获取用户图度箱的图度列表
     *
     * SELECT t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.cycle_id AS cycleid,
     * t.type, t.subject, t.from, t.to, t.cc, t.priority, t.privacy,
     * t.last_post_time AS lastposttime, t.last_poster AS lastposter,
     * t.view_num AS viewnum, t.reply_num AS replynum, t.log_num AS lognum, t.percent, t.score, t.status,
     * t.start_time AS starttime, t.end_time AS endtime,
     * t.total_time AS totaltime, t.elapsed_time AS elapsedtime,
     * t.create_time AS create_time, p.post_id AS postid, p.content, '' AS posterinfo, p.attach_num AS attachnum,
     * tu.unique_id AS uniqueid, TRIM(LEADING ',' FROM tu.labels) labels,
     * tu.is_read AS isread, tu.is_forward AS isforward, is_draft AS isdraft, is_done AS isdone
     * FROM td_tudu t
     * LEFT JOIN td_post p ON p.tudu_id = t.tudu_id AND p.is_first = 1
     * INNER JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id
     * LEFT JOIN td_tudu_label tl ON tl.tudu_id = t.tudu_id AND tl.unique_id = tu.unique_id
     * WHERE tu.unique_id = ? AND tl.label_id = ?
     *
     * @param array $condition
     * @param mixed $sort
     * @param int $page
     * @param int $pageSize
     * @return Oray_Dao_Recordset
     */
    public function getTuduPage(array $condition = null, $sort = null, $page = null, $pageSize = null)
    {
        $table   = 'td_tudu t '
                 . 'LEFT JOIN td_post p ON p.tudu_id = t.tudu_id AND p.is_first = 1 '
                 . 'LEFT JOIN td_tudu_group g ON g.tudu_id = p.tudu_id '
                 . 'INNER JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id '
                 . "LEFT JOIN td_class c ON t.class_id = c.class_id AND t.org_id = c.org_id AND t.board_id = c.board_id "
                 . 'LEFT JOIN td_tudu_label tl ON tl.tudu_id = t.tudu_id AND tl.unique_id = tu.unique_id '
                 . 'LEFT JOIN td_tudu_cycle tc ON tc.cycle_id = t.cycle_id '
                 . 'LEFT JOIN td_tudu_flow fl ON fl.tudu_id = t.tudu_id ';

        $columns = "t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.cycle_id AS cycleid, t.prev_tudu_id AS prevtuduid, "
                 . "t.type, t.subject, t.from, t.to, t.cc, t.priority, t.privacy, t.password, fl.current_step_id AS stepid, t.app_id AS appid, "
                 . "t.last_post_time AS lastposttime, t.last_poster AS lastposter, t.last_forward AS lastforward, t.flow_id AS flowid, "
                 . "t.view_num AS viewnum, t.reply_num AS replynum, t.log_num AS lognum, t.percent, t.score, t.status, "
                 . "t.special, t.start_time AS starttime, t.end_time AS endtime, t.complete_time AS completetime, t.notify_all AS notifyall, "
                 . "t.total_time AS totaltime, t.elapsed_time AS elapsedtime, t.need_confirm AS needconfirm, "
                 . "t.create_time AS createtime, t.accept_time AS accepttime, t.accep_mode AS accepmode, "
                 . "p.post_id AS postid, '' AS content, '' AS posterinfo, p.attach_num AS attachnum, "
                 . "tu.unique_id AS uniqueid, TRIM(LEADING ',' FROM tu.labels) labels, tu.mark, "
                 . "tu.is_read AS isread, tu.is_forward AS isforward, is_draft AS isdraft, t.is_done AS isdone, t.is_top AS istop, "
                 . "tu.role, tu.percent AS selfpercent, tu.forward_info AS forwardinfo, "
                 . "tu.tudu_status AS selftudustatus, tu.accept_time AS selfaccepttime, "
                 . "t.class_id AS classid, c.class_name AS classname, tc.display_date AS displaydate, "
                 . "g.type AS nodetype, g.parent_tudu_id AS parentid";
        $primary = "t.tudu_id";
        $recordClass = "Dao_Td_Tudu_Record_Tudu";
        $where = array();
        $order = array();

        // $condition...
        if (isset($condition['tuduindexnum'])) {
            if (is_array($condition['tuduindexnum'])) {
                $arr = array_map('intval', $condition['tuduindexnum']);
                $where[] = 't.tudu_index_num IN (' . implode(',', $arr) . ')';
            } else {
                $where[] = 't.tudu_index_num = ' . $condition['tuduindexnum'];
            }
        }

        if (isset($condition['uniqueid'])) {
            $where[] = 'tu.unique_id = ' . $this->_db->quote($condition['uniqueid']);
        }

        if (isset($condition['label'])) {
            $where[] = 'tl.label_id = ' . $this->_db->quote($condition['label']);
        }

        // 板块
        if (isset($condition['boardid'])) {
            $where[] = 't.board_id = ' . $this->_db->quote($condition['boardid']);
        }

        // 主题分类
        if (isset($condition['classid'])) {
            $where[] = 't.class_id = ' . $this->_db->quote($condition['classid']);
        }

        // 查找已读状态
        if (isset($condition['isread'])) {
            $where[] = 'tu.is_read = ' . ($condition['isread'] ? 1 : 0);
        }

        // 关键字
        if (!empty($condition['keyword'])) {
            $keyword = $this->_db->quote('%' . $condition['keyword'] . '%');
            $where[] = 't.subject LIKE ' . $keyword;
        }

        // 发送人
        if (!empty($condition['from'])) {
            $from = $this->_db->quote('%' . $condition['from'] . '%');
            $where[] = 't.from LIKE ' . $from;
        }

        // 接收人
        if (!empty($condition['to'])) {
            $to = $this->_db->quote('%' . $condition['to'] . '%');
            $where[] = 't.to LIKE ' . $to;
        }

        // 状态
        if (isset($condition['status'])) {
            if (is_array($condition['status'])) {
                foreach ($condition['status'] as $item) {
                    $status[] = $this->_db->quote($item);
                }
                $where[] = 't.status IN (' . implode(',', $status) . ')';
            } else if (is_int($condition['status'])) {
                $where[] = 't.status = ' . $condition['status'];
            }
        }

        // 类型
        if (!empty($condition['type'])) {
            $where[] = 't.type = ' . $this->_db->quote($condition['type']);
        }

        // 已完成
        if (isset($condition['isdone'])) {
            $where[] = 't.is_done = ' . ($condition['isdone'] ? 1 : 0);
        }

        // 甘特图
        if(!empty($condition['startdate']) && !empty($condition['enddate'])) {
            $startDate = (int) $condition['startdate'];
            $endDate = (int) $condition['enddate'];
             $where[] = "(((t.start_time >= {$startDate} AND t.start_time <= {$endDate}) "
                 . "OR (t.end_time >= {$startDate} AND t.end_time <= {$endDate}) "
                 . "OR ((t.start_time <= {$startDate} OR t.start_time IS NULL) "
                 . "AND (t.end_time >= {$endDate} OR t.end_time IS NULL)))"
                 . "AND (((t.complete_time <= {$endDate} AND t.complete_time >= {$startDate}) "
                 . "OR (t.complete_time >= {$endDate} AND t.complete_time >= {$startDate})) "
                 . "OR t.complete_time IS NULL) OR (t.status <= 1 AND DATEDIFF(FROM_UNIXTIME(UNIX_TIMESTAMP(), '%Y-%m-%d'), FROM_UNIXTIME(t.end_time, '%Y-%m-%d')) > 0 AND t.end_time <= {$endDate}))";
        }

        $array = array(
            'createtime' => 't.create_time',
            'endtime'    => 't.end_time',
            'starttime'  => 't.start_time'
        );

        // createtime, endtime, starttime
        foreach ($array as $key => $col) {
            if (!isset($condition[$key])) {
                continue ;
            }

            if (is_array($condition[$key])) {
                $arr = array();
                if (isset($condition[$key]['start'])) {
                    $arr[] = $col . ' >= ' . (int) $condition[$key]['start'];
                }

                if (isset($condition[$key]['end'])) {
                    $arr[] = $col . ' <= ' . (int) $condition[$key]['end'];
                }

                if ($arr) {
                    $where[] = '(' . $col . ' IS NOT NULL AND ' . implode(' AND ', $arr) . ')';
                }
            } elseif (is_int($condition[$key])) {
                $where[] = '(' . $col . ' IS NOT NULL AND ' . $col . ' >= ' . $condition[$key] . ')';
            }
        }

        // 过期
        if (isset($condition['expiredate']) && is_int($condition['expiredate'])) {
            $where[] = '(tu.is_read = 0 OR t.start_time IS NULL OR t.start_time <= ' . $condition['expiredate'] . ')';
        }

        // WHERE
        $where = implode(' AND ', $where);
        if ($where) {
            $where = 'WHERE ' . $where;
        }

        // 格式化排序参数
        $sort = $this->_formatSort($sort);
        foreach ($sort as $key => $val) {
            switch ($key) {
                case 'lastposttime':
                    $key = 'last_post_time';
                    break;
                case 'subject':
                    $key = 'subject';
                    break;
                case 'endtime':
                    $key = 'end_time';
                    break;
                case 'starttime':
                    $key = 'start_time';
                    break;
                case 'from':
                    $key = '`from`';
                    break;
                case 'to':
                    $key = '`to`';
                    break;
                case 'istop':
                    $key = 'is_top';
                    break;
                case 'percent':
                    $key = 'percent';
                    break;
                default:
                    continue 2;
                    break;
            }
            $order[] = $key . ' ' . $val;
        }

        // ORDER
        $order = implode(', ', $order);
        if ($order) {
            $order = 'ORDER BY ' . $order;
        }

        if (null === $pageSize && null === $page) {
            $sql = "SELECT $columns FROM $table $where $order";
        } else {

            // 使用默认的分页大小
            if (null === $pageSize) {
                $pageSize = self::$_defaultPageSize;
            }

            if ($page < 1) $page = 1;

            $sql = "SELECT $columns FROM $table $where $order LIMIT " . $pageSize * ($page - 1) . ", " . $pageSize;
        }

        $records = $this->_db->fetchAll($sql);

        return new Oray_Dao_Recordset($records, $recordClass);
    }

    /**
     * 获取版块的图度列表
     *
     * SELECT
     * t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.cycle_id AS cycleid,
     * t.type, t.subject, t.from, t.to, t.cc, t.priority, t.privacy,
     * t.last_post_time AS lastposttime, t.last_poster AS lastposter,
     * t.view_num AS viewnum, t.reply_num AS replynum, t.log_num AS lognum, t.percent, t.score, t.status,
     * t.special, t.start_time AS starttime, t.end_time AS endtime,
     * t.total_time AS totaltime, t.elapsed_time AS elapsedtime,
     * t.create_time AS createtime, t.accept_time AS accepttime,
     * p.post_id AS postid, '' AS content, '' AS posterinfo, p.attach_num AS attachnum,
     * tu.unique_id AS uniqueid, TRIM(LEADING ',' FROM tu.labels) labels,
     * tu.is_read AS isread, tu.is_forward AS isforward, is_draft AS isdraft, is_done AS isdone,
     * g.type AS nodetype, g.parent_tudu_id AS parentid
     *
     * FROM td_tudu t
     * LEFT JOIN td_tudu_group g ON g.tudu_id = p.tudu_id
     * LEFT JOIN td_post p ON p.tudu_id = t.tudu_id AND p.is_first = 1
     * LEFT JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id AND tu.unique_id = ?
     *
     * WHERE t.is_draft = 0
     * AND t.org_id = ?
     * AND t.board_id = ?
     *
     * @param array $condition
     * @param mixed $sort
     * @param int $page
     * @param int $pageSize
     * @return Oray_Dao_Recordset
     */
    public function getBoardTuduPage(array $condition = null, $sort = null, $page = null, $pageSize = null)
    {
        $uniqueId = isset($condition['uniqueid'])
                  ? $this->_db->quote($condition['uniqueid'])
                  : "''";

        $table    = "td_tudu t "
                  . "LEFT JOIN td_post p ON p.tudu_id = t.tudu_id AND p.is_first = 1 "
                  . "LEFT JOIN td_tudu_group g ON g.tudu_id = p.tudu_id "
                  . "LEFT JOIN td_class c ON t.class_id = c.class_id AND t.org_id = c.org_id AND t.board_id = c.board_id "
                  . 'LEFT JOIN td_tudu_cycle tc ON tc.cycle_id = t.cycle_id '
                  . "LEFT JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id AND tu.unique_id = " . $uniqueId;
        $columns  = "t.org_id AS orgid, t.board_id AS boardid, t.tudu_id AS tuduid, t.cycle_id AS cycleid, "
                  . "t.type, t.subject, t.from, t.to, t.cc, t.priority, t.privacy, t.password, "
                  . "t.last_post_time AS lastposttime, t.last_poster AS lastposter, t.flow_id AS flowid, "
                  . "t.view_num AS viewnum, t.reply_num AS replynum, t.log_num AS lognum, t.percent, t.score, t.status, "
                  . "t.special, t.start_time AS starttime, t.end_time AS endtime, t.need_confirm AS needconfirm, "
                  . "t.total_time AS totaltime, t.elapsed_time AS elapsedtime, t.accep_mode AS accepmode, "
                  . "t.create_time AS createtime, t.accept_time AS accepttime, "
                  . "p.post_id AS postid, '' AS content, '' AS posterinfo, p.attach_num AS attachnum, "
                  . "tu.unique_id AS uniqueid, TRIM(LEADING ',' FROM tu.labels) labels, tu.mark, "
                  . "tu.is_read AS isread, tu.is_forward AS isforward, is_draft AS isdraft, is_done AS isdone, t.is_top AS istop, "
                  . "t.class_id AS classid, c.class_name AS classname, tc.display_date AS displaydate, "
                  . "g.type AS nodetype, g.parent_tudu_id AS parentid";
        $primary  = "t.tudu_id";
        $recordClass = "Dao_Td_Tudu_Record_Tudu";
        $where = array();
        $order = array();

        if (isset($condition['orgid'])) {
            $where[] = 't.org_id = ' . $this->_db->quote($condition['orgid']);
        }

        if (isset($condition['boardid'])) {
            if (is_array($condition['boardid'])) {
                $where[] = 't.board_id IN(' . implode(',', array_map(array($this->_db, 'quote'), $condition['boardid'])) . ')';
            } else {
                $where[] = 't.board_id = ' . $this->_db->quote($condition['boardid']);
            }
        }

        // 关键字
        if (!empty($condition['keyword'])) {
            $keyword = $this->_db->quote('%' . $condition['keyword'] . '%');
            $where[] = 't.subject LIKE ' . $keyword;
        }

        // 发送人
        if (!empty($condition['from'])) {
            $from = $this->_db->quote('%' . $condition['from'] . '%');
            $where[] = 't.from LIKE ' . $from;
        }

        // 接收人
        if (!empty($condition['to'])) {
            $to = $this->_db->quote('%' . $condition['to'] . '%');
            $where[] = 't.to LIKE ' . $to;
        }

        // 主题分类
        if (isset($condition['classid'])) {
            $where[] = 'c.class_id = ' . $this->_db->quote($condition['classid']);
        }

        // 类型
        if (!empty($condition['type'])) {
            if (is_array($condition['type'])) {
                $where[] = 't.type IN ( ' . implode(',', array_map(array($this->_db, 'quote'), $condition['type'])) . ')';
            } else {
                $where[] = 't.type = ' . $this->_db->quote($condition['type']);
            }
        }

        if (isset($condition['priority']) && is_int($condition['priority'])) {
            $where[] = 't.priority = ' . $condition['priority'];
        }

        if (isset($condition['status']) && is_int($condition['status'])) {
            $where[] = 't.status = ' . $condition['status'];
        }

        // 创建时间
        if (isset($condition['createtime'])) {
            if (is_array($condition['createtime'])) {
                $array = array();
                if (isset($condition['createtime']['start']) && is_int($condition['createtime']['start'])) {
                    $array[] = 't.create_time >= ' . $condition['createtime']['start'];
                }

                if (isset($condition['createtime']['end']) && is_int($condition['createtime']['end'])) {
                    $array[] = 't.create_time <= ' . $condition['createtime']['end'];
                }

                if ($array) {
                    $where[] = '(' . implode(' AND ', $array) . ')';
                }
            } elseif (is_int($condition['createtime'])) {
                $where[] = 't.create_time >= ' . $condition['createtime'];
            }
        }

        // 创建时间
        if (isset($condition['endtime'])) {
            if (is_array($condition['endtime'])) {
                $array = array();
                if (isset($condition['endtime']['start']) && is_int($condition['endtime']['start'])) {
                    $array[] = 't.end_time >= ' . $condition['endtime'];
                }

                if (isset($condition['endtime']['end']) && is_int($condition['endtime']['end'])) {
                    $array[] = 't.end_time <= ' . $condition['endtime'];
                }

                if ($array) {
                    $where[] = '(' . implode(' AND ', $array) . ')';
                }
            } elseif (is_int($condition['endtime'])) {
                $where[] = 't.end_time >= ' . $condition['endtime'];
            }
        }

        // 过期
        if (isset($condition['expiredate']) && is_int($condition['expiredate'])) {
            $where[] = '(t.is_done <> 1 OR t.create_time >= ' . $condition['expiredate'] . ')';
        }

        // 过滤草稿
        $where[] = 't.is_draft = 0';

        if (isset($condition['privacy'])) {
            $where[] = '(t.privacy = 0 OR tu.unique_id = ' . $uniqueId . ')';
        }

        if (isset($condition['self'])) {
            $where[] = 'tu.unique_id = ' . $uniqueId;
        }

        // WHERE
        $where = implode(' AND ', $where);

        // 格式化排序参数
        $sort = $this->_formatSort($sort);
        foreach ($sort as $key => $val) {
            switch ($key) {
                case 'lastposttime':
                    $key = 'last_post_time';
                    break;
                case 'subject':
                    $key = 'subject';
                    break;
                case 'endtime':
                    $key = 'end_time';
                    break;
                case 'istop':
                    $key = 'is_top';
                    break;
                default:
                    continue 2;
                    break;
            }
            $order[] = $key . ' ' . $val;
        }

        // ORDER
        $order = implode(', ', $order);

        // 使用默认的分页大小
        if (null === $pageSize) {
            $pageSize = self::$_defaultPageSize;
        }

        /**
         * @see Oray_Db_Paginator
         */
        require_once 'Oray/Db/Paginator.php';

        // 初始化分页器
        $paginator = new Oray_Db_Paginator(array(
            Oray_Db_Paginator::ADAPTER      => $this->_db,
            Oray_Db_Paginator::RECORD_CLASS => $recordClass,
            Oray_Db_Paginator::PAGE_SIZE    => $pageSize,
            Oray_Db_Paginator::TABLE        => $table,
            Oray_Db_Paginator::PRIMARY      => $primary,
            Oray_Db_Paginator::COLUMNS      => $columns,
            Oray_Db_Paginator::WHERE        => $where,
            Oray_Db_Paginator::ORDER        => $order
        ));

        // 返回查询结果
        return $paginator->query($page);
    }

    /**
     * 获取符合条件的图度数量
     *
     * @param $condition
     */
    public function getTuduCount(array $condition)
    {
        $table = 'td_tudu t ';

        if (isset($condition['orgid'])) {
            $where[] = 't.org_id = ' . $this->_db->quote($condition['orgid']);
        }

        if (isset($condition['type'])) {
            $where[] = 't.type = ' . $this->_db->quote($condition['type']);
        }

        if (isset($condition['boardid'])) {
            $where[] = 't.board_id = ' . $this->_db->quote($condition['boardid']);
        }

        if (isset($condition['uniqueid'])) {
            $table  .= 'INNER JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id ';
            $where[] = 'tu.unique_id = ' . $this->_db->quote($condition['uniqueid']);

            if (isset($condition['labelid'])) {
                $table  .= 'LEFT JOIN td_tudu_label tl ON tl.tudu_id = t.tudu_id AND tl.unique_id = tu.unique_id ';
                $where[] = 'tl.label_id = ' . $this->_db->quote($condition['labelid']);
            }
        }

        // 草稿
        if (isset($condition['isdraft'])) {
            $where[] = 't.is_draft = ' . ($condition['isdraft'] ? 1 : 0);
        }

        // 查找已读状态
        if (isset($condition['isread'])) {
            $where[] = 'tu.is_read = ' . ($condition['isread'] ? 1 : 0);
        }

        // 关键字
        if (!empty($condition['keyword'])) {
            $keyword = $this->_db->quote('%' . $condition['keyword'] . '%');
            $where[] = 't.subject LIKE ' . $keyword;
        }

        // 发送人
        if (!empty($condition['from'])) {
            $from = $this->_db->quote('%' . $condition['from'] . '%');
            $where[] = 't.from LIKE ' . $from;
        }

        // 接收人
        if (!empty($condition['to'])) {
            $to = $this->_db->quote('%' . $condition['to'] . '%');
            $where[] = 't.to LIKE ' . $to;
        }

        // 状态
        if (isset($condition['status'])) {
            if (is_array($condition['status'])) {
                foreach ($condition['status'] as $item) {
                    $status[] = $this->_db->quote($item);
                }
                $where[] = 't.status IN (' . implode(',', $status) . ')';
            } else if (is_int($condition['status'])) {
                $where[] = 't.status = ' . $condition['status'];
            }
        }

        // 版块
        if (!empty($condition['boardid'])) {
            $where[] = 't.board_id = ' . $this->_db->quote($condition['boardid']);
        }

        // 主题分类
        if (isset($condition['classid'])) {
            $where[] = 't.class_id = ' . $this->_db->quote($condition['classid']);
        }

        // 已完成
        if (isset($condition['isdone'])) {
            $where[] = 't.is_done = ' . ($condition['isdone'] ? 1 : 0);
        }

        $array = array(
            'createtime' => 't.create_time',
            'endtime'    => 't.end_time',
            'starttime'  => 't.start_time'
        );

        // createtime, endtime, starttime
        foreach ($array as $key => $col) {
            if (!isset($condition[$key])) {
                continue ;
            }

            if (is_array($condition[$key])) {
                $arr = array();
                if (isset($condition[$key]['start'])) {
                    $arr[] = $col . ' >= ' . (int) $condition[$key]['start'];
                }

                if (isset($condition[$key]['end'])) {
                    $arr[] = $col . ' <= ' . (int) $condition[$key]['end'];
                }

                if ($arr) {
                    $where[] = '(' . implode(' AND ', $arr) . ')';
                }
            } elseif (is_int($condition[$key])) {
                $where[] = $col . ' >= ' . $condition[$key];
            }
        }

        // 过期
        if (isset($condition['expiredate']) && is_int($condition['expiredate'])) {
            $where[] = '(tu.is_read = 0 OR t.start_time IS NULL OR t.start_time <= ' . $condition['expiredate'] . ')';
        }

        // WHERE
        $where = implode(' AND ', $where);
        if ($where) {
            $where = 'WHERE ' . $where;
        }

        $sql = "SELECT COUNT(0) FROM {$table} {$where}";

        $count = (int) $this->_db->fetchOne($sql);

        return $count;
    }

    /**
     * 统计符合条件的图度数量 -- 此方法将丢弃,请使用 getTuduCount 代替
     *
     * @param array $condition
     * @depared
     */
    public function countTudu(array $condition)
    {
        $table    = 'td_tudu t '
                  . 'INNER JOIN td_tudu_user tu ON tu.tudu_id = t.tudu_id '
                  . 'LEFT JOIN td_tudu_label tl ON tl.tudu_id = t.tudu_id AND tl.unique_id = tu.unique_id';

        // $condition...
        if (isset($condition['uniqueid'])) {
            $where[] = 'tu.unique_id = ' . $this->_db->quote($condition['uniqueid']);
        }

        if (isset($condition['label'])) {
            $where[] = 'tl.label_id = ' . $this->_db->quote($condition['label']);
        }

        // 状态
        if (isset($condition['isdraft']) && is_int($condition['isdraft'])) {
            $where[] = 't.is_draft = ' . (int) $condition['isdraft'];
        }

        // 查找已读状态
        if (isset($condition['isread'])) {
            $where[] = 'tu.is_read = ' . ($condition['isread'] ? 1 : 0);
        }

        // 关键字
        if (!empty($condition['keyword'])) {
            $keyword = $this->_db->quote('%' . $condition['keyword'] . '%');
            $where[] = 't.subject LIKE ' . $keyword;
        }

        // 发送人
        if (!empty($condition['from'])) {
            $from = $this->_db->quote('%' . $condition['from'] . '%');
            $where[] = 't.from LIKE ' . $from;
        }

        // 接收人
        if (!empty($condition['to'])) {
            $to = $this->_db->quote('%' . $condition['to'] . '%');
            $where[] = 't.to LIKE ' . $to;
        }

        // 状态
        if (isset($condition['status']) && is_int($condition['status'])) {
            $where[] = 't.status = ' . $condition['status'];
        }

        // 版块
        if (!empty($condition['boardid'])) {
            $where[] = 't.board_id = ' . $this->_db->quote($condition['boardid']);
        }

        // 主题分类
        if (isset($condition['classid'])) {
            $where[] = 't.class_id = ' . $this->_db->quote($condition['classid']);
        }

        // 类型
        if (!empty($condition['type'])) {
            $where[] = 't.type = ' . $this->_db->quote($condition['type']);
        }

        // 已完成
        if (isset($condition['isdone'])) {
            $where[] = 't.is_done = ' . ($condition['isdone'] ? 1 : 0);
        }

        $array = array(
            'createtime' => 't.create_time',
            'endtime'    => 't.end_time',
            'starttime'  => 't.start_time'
        );

        // createtime, endtime, starttime
        foreach ($array as $key => $col) {
            if (!isset($condition[$key])) {
                continue ;
            }

            if (is_array($condition[$key])) {
                $arr = array();
                if (isset($condition[$key]['start'])) {
                    $arr[] = $col . ' >= ' . (int) $condition[$key]['start'];
                }

                if (isset($condition[$key]['end'])) {
                    $arr[] = $col . ' <= ' . (int) $condition[$key]['end'];
                }

                if ($arr) {
                    $where[] = '(' . implode(' AND ', $arr) . ')';
                }
            } elseif (is_int($condition[$key])) {
                $where[] = $col . ' >= ' . $condition[$key];
            }
        }

        // 过期
        if (isset($condition['expiredate']) && is_int($condition['expiredate'])) {
            $where[] = '(tu.is_read = 0 OR t.start_time IS NULL OR t.start_time <= ' . $condition['expiredate'] . ')';
        }

        // WHERE
        $where = implode(' AND ', $where);
        if ($where) {
            $where = 'WHERE ' . $where;
        }

        $sql = "SELECT COUNT(0) FROM {$table} {$where}";

        $count = (int) $this->_db->fetchOne($sql);

        return $count;
    }

    /**
     * Create tudu
     *
     * @param $params
     * @return string|false
     */
    public function createTudu(array $params)
    {
        if (empty($params['orgid'])
            || empty($params['boardid'])
            || empty($params['tuduid'])
            || empty($params['type'])
            || empty($params['from'])
            || !array_key_exists('subject', $params)) {
            return false;
        }

        $address = self::formatAddress($params['from'], true);

        $createTime = empty($params['createtime']) ? time() : (int) $params['createtime'];

        $table = "td_tudu";
        $bind = array(
            'org_id'         => $params['orgid'],
            'board_id'       => $params['boardid'],
            'tudu_id'        => $params['tuduid'],
            'type'           => $params['type'],
            'subject'        => $params['subject'],
            'from'           => $params['from'],
            'priority'       => empty($params['priority']) ? 0 : (int) $params['priority'],
            'privacy'        => empty($params['privacy']) ? 0 : (int) $params['privacy'],
            'is_draft'       => 1,
            'last_poster'    => $address ? $address[0] : '',
            'last_post_time' => $createTime,
            'create_time'    => $createTime
            );

        if (isset($params['to'])) {
            $bind['to'] = $params['to'];
        }
        if (isset($params['cc'])) {
            $bind['cc'] = $params['cc'];
        }
        if (isset($params['bcc'])) {
            $bind['bcc'] = $params['bcc'];
        }
        if (isset($params['starttime'])) {
            $bind['start_time'] = $params['starttime'];
        }
        if (isset($params['endtime'])) {
            $bind['end_time'] = $params['endtime'];
        }
        if (isset($params['totaltime'])) {
            $bind['total_time'] = (int) $params['totaltime'];
        }
        if (isset($params['elapsedtime'])) {
            $bind['elapsed_time'] = (int) $params['elapsedtime'];
        }
        if (isset($params['accepttime'])) {
            $bind['accept_time'] = (int) $params['accepttime'];
        }
        if (isset($params['percent'])) {
            $bind['percent'] = (int) $params['percent'];
        }
        if (isset($params['status'])) {
            $bind['status'] = (int) $params['status'];
        }
        if (isset($params['viewnum'])) {
            $bind['view_num'] = (int) $params['viewnum'];
        }
        if (isset($params['isdone'])) {
            $bind['is_done'] = $params['isdone'] ? 1 : 0;
        }
        if (isset($params['istop'])) {
            $bind['is_top'] = $params['istop'] ? 1 : 0;
        }
        if (isset($params['notifyall'])) {
            $bind['notify_all'] = $params['notifyall'] ? 1 : 0;
        }
        if (!empty($params['prevtuduid'])) {
            $bind['prev_tudu_id'] = $params['prevtuduid'];
        }

        if (!empty($params['stepid'])) {
            $bind['step_id'] = $params['stepid'];
        }
        if (!empty($params['appid'])) {
            $bind['app_id'] = $params['appid'];
        }
        if (isset($params['special']) && is_int($params['special'])) {
            $bind['special'] = $params['special'];
        }
        if (isset($params['cycleid'])) {
            $bind['cycle_id'] = $params['cycleid'];
        }
        if (isset($params['flowid'])) {
            $bind['flow_id'] = $params['flowid'];
        }
        if (!empty($params['classid'])) {
            $bind['class_id'] = $params['classid'];
        }
        if (isset($params['password'])) {
            $bind['password'] = $params['password'];
        }
        if (isset($params['isauth'])) {
            $bind['is_auth'] = $params['isauth'] ? 1 : 0;
        }
        if (isset($params['needconfirm'])) {
            $bind['need_confirm'] = $params['needconfirm'] ? 1 : 0;
        }
        if (isset($params['cyclenum']) && is_int($params['cyclenum'])) {
            $bind['cycle_num'] = $params['cyclenum'];
        }
        if (isset($params['acceptmode'])) {
            $bind['accep_mode'] = $params['acceptmode'] ? 1 : 0;
        }

        try {
            $this->_db->insert($table, $bind);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return $params['tuduid'];
    }

    /**
     * Update tudu
     *
     * @param string $tuduId
     * @param array $params
     * @return boolean
     */
    public function updateTudu($tuduId, array $params)
    {
        if (empty($tuduId)) {
            return false;
        }

        $table = "td_tudu";
        $bind  = array();
        $where = "tudu_id = " . $this->_db->quote($tuduId);

        if (isset($params['subject'])) {
            $bind['subject'] = $params['subject'];
        }
        if (!empty($params['boardid'])) {
            $bind['board_id'] = $params['boardid'];
        }
        if (isset($params['from'])) {
            $bind['from'] = $params['from'];
        }
        if (isset($params['to'])) {
            $bind['to'] = $params['to'];
        }
        if (array_key_exists('cc', $params)) {
            $bind['cc'] = $params['cc'];
        }
        if (array_key_exists('bcc', $params)) {
            $bind['bcc'] = $params['bcc'];
        }
        if (isset($params['priority'])) {
            $bind['priority'] = (int) $params['priority'];
        }
        if (isset($params['privacy'])) {
            $bind['privacy'] = (int) $params['privacy'];
        }
        if (isset($params['stepnum']) && is_int($params['stepnum'])) {
            $bind['step_num'] = $params['stepnum'];
        }

        if (array_key_exists('password', $params)) {
            $bind['password'] = $params['password'];
        }

        if (array_key_exists('prevtuduid', $params)) {
            $bind['prev_tudu_id'] = $params['prevtuduid'];
        }
        if (array_key_exists('stepid', $params)) {
            $bind['step_id'] = $params['stepid'];
        }

        if (isset($params['lastposter'])) {
            $bind['last_poster'] = $params['lastposter'];
        }
        if (isset($params['lastposttime'])) {
            $bind['last_post_time'] = (int) $params['lastposttime'];
        }

        if (isset($params['isdraft'])) {
            $bind['is_draft'] = $params['isdraft'] ? 1 : 0;
        }

        if (isset($params['isdone'])) {
            $bind['is_done'] = $params['isdone'] ? 1 : 0;
        }
        if (isset($params['istop'])) {
            $bind['is_top'] = $params['istop'] ? 1 : 0;
        }
        if (isset($params['notifyall'])) {
            $bind['notify_all'] = $params['notifyall'] ? 1 : 0;
        }

        if (array_key_exists('starttime', $params)) {
            $bind['start_time'] = $params['starttime'];
        }
        if (array_key_exists('endtime', $params)) {
            $bind['end_time'] = $params['endtime'];
        }
        if (isset($params['totaltime'])) {
            $bind['total_time'] = $params['totaltime'];
        }
        if (array_key_exists('accepttime', $params)) {
            $bind['accept_time'] = $params['accepttime'];
        }
        if (isset($params['createtime'])) {
            $bind['create_time'] = $params['createtime'];
        }
        if (isset($params['percent'])) {
            $bind['percent'] = (int) $params['percent'];
        }
        if (isset($params['status'])) {
            $bind['status'] = (int) $params['status'];
        }
        if (isset($params['special']) && is_int($params['special'])) {
            $bind['special'] = $params['special'];
        }
        if (isset($params['score'])) {
            $bind['score'] = (int) $params['score'];
        }
        if (array_key_exists('cycleid', $params)) {
            $bind['cycle_id'] = $params['cycleid'];
        }
        if (array_key_exists('classid', $params)) {
            $bind['class_id'] = $params['classid'];
        }
        if (array_key_exists('flowid', $params)) {
            $bind['flow_id'] = $params['flowid'];
        }
        if (!empty($params['lastforward'])) {
            $bind['last_forward'] = $params['lastforward'];
        }
        if (array_key_exists('password', $params)) {
            $bind['password'] = $params['password'];
        }
        if (isset($params['isauth'])) {
            $bind['is_auth'] = $params['isauth'] ? 1 : 0;
        }
        if (isset($params['needconfirm'])) {
            $bind['need_confirm'] = $params['needconfirm'] ? 1 : 0;
        }
        if (isset($params['acceptmode'])) {
            $bind['accep_mode'] = $params['acceptmode'] ? 1 : 0;
        }

        if (!$bind) {
            return false;
        }

        try {
            $this->_db->update($table, $bind, $where);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * Delete tudu
     *
     * @param string $tuduId
     * @return boolean
     */
    public function deleteTudu($tuduId)
    {
        $sql = "call sp_td_delete_tudu(" . $this->_db->quote($tuduId) . ")";

        try {
            $ret = $this->_db->fetchOne($sql);
            if ($ret == 0) {
                return false;
            }
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }
        return true;
    }

    /**
     * Send tudu
     *
     * @param $tuduId
     * @return boolean
     */
    public function sendTudu($tuduId)
    {
        $sql = "call sp_td_send_tudu(" . $this->_db->quote($tuduId) . ")";

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }
        return true;
    }

    /**
     * 图度移动版块
     *
     * @param $tuduId
     * @param $boardId
     * @param $classId
     */
    public function moveTudu($tuduId, $boardId, $classId = null)
    {
        $tuduId  = $this->_db->quote($tuduId);
        $boardId = $this->_db->quote($boardId);
        $classId = $this->_db->quote($classId);

        $sql = "call sp_td_move_tudu({$tuduId}, {$boardId}, {$classId})";

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }
        return true;
    }

    /**
     * 获取图度关联用户
     *
     * @param string $tuduId
     * @param array  $filter
     */
    public function getUsers($tuduId, $filter = null)
    {
        $table   = 'td_tudu_user u ';
        $columns = 'u.unique_id as uniqueid, u.is_read as isread, u.is_forward as isforward, u.labels, u.role, u.is_foreign AS isforeign, '
                 . 'u.accepter_info AS accepterinfo, u.auth_code AS authcode, u.percent';

        $where = array(
            'u.tudu_id = ' . $this->_db->quote($tuduId),
            '(u.labels <> \'\' OR u.is_foreign = 1)'
        );

        if (isset($filter['role'])) {
            $where[] = 'u.role = ' . $this->_db->quote($filter['role']);
        }

        if (isset($filter['isforeign'])) {
            $where[] = 'u.is_foreign = ' . $this->_db->quote($filter['isforeign']);
        }

        if (isset($filter['uniqueid'])) {
            if (is_array($filter['uniqueid'])) {
                $arr = array_map(array($this->_db, 'quote'), $filter['uniqueid']);
                $where[] = 'u.unique_id IN (' . implode(',', $arr) . ')';
            } else {
                $where[] = 'u.unique_id = ' . $this->_db->quote($filter['uniqueid']);
            }
        }

        if (isset($filter['labelid'])) {
            $table .= 'INNER JOIN td_tudu_label l ON u.tudu_id = l.tudu_id AND u.unique_id = l.unique_id AND l.label_id = '
                    . $this->_db->quote($filter['labelid']);
        }

        $sql = "SELECT {$columns} FROM {$table} WHERE " . implode(' AND ', $where);

        $records = $this->_db->fetchAll($sql);

        foreach ($records as &$record) {
            $info = self::formatAddress($record['accepterinfo'], true);
            $record['email']    = !empty($info[3]) ? $info[3] : null;
            $record['truename'] = !empty($info[0]) ? $info[0] : null;
        }

        return $records;
    }

    /**
     * 获取执行人
     *
     * @param string $tuduId
     */
    public function getAccepters($tuduId, $stepId = null)
    {
        $tuduId = $this->_db->quote($tuduId);

        $table   = 'td_tudu_user';
        $columns = 'unique_id AS uniqueid, is_read AS isread, is_forward AS isforward, labels, role, percent, auth_code AS authcode, '
                 . 'accepter_info AS accepterinfo, tudu_status AS tudustatus, forward_info AS forwardinfo, accept_time AS accepttime, '
                 . 'is_foreign AS isforeign, '
                 . 'IF((accept_time IS NOT NULL OR tudu_status >= 2), (SELECT SUM(elapsed_time) FROM td_post WHERE tudu_id = ' . $tuduId . ' AND unique_id = td_tudu_user.unique_id), NULL) AS elapsedtime';
        $where   = 'tudu_id = ' . $tuduId . ' AND role = \'to\'';

        if (null != $stepId) {
            $where .= ' AND step_id = ' . $this->_db->quote($stepId);
        }

        $sql = "SELECT {$columns} FROM {$table} WHERE {$where}";

        return $this->_db->fetchAll($sql);
    }

    /**
     * 获取投递的用户信息
     *
     * @param $tuduId
     * @param $uniqueId
     */
    public function getUser($tuduId, $uniqueId)
    {
        $columns = 'unique_id AS uniqueid, tudu_id AS tuduid, is_foreign AS isforeign, is_read AS isread, labels, role, '
                 . 'accepter_info AS accepterinfo, percent, tudu_status, accept_time, forward_info, auth_code AS authcode, '
                 . 'complete_time';
        $table   = 'td_tudu_user';

        $where   = 'tudu_id = ' . $this->_db->quote($tuduId) . ' AND unique_id = ' . $this->_db->quote($uniqueId);

        $sql = "SELECT {$columns} FROM {$table} WHERE {$where} LIMIT 1";

        try {
            $record = $this->_db->fetchRow($sql);

            if (!$record) {
                return null;
            }

            $record['accepterinfo'] = self::formatAddress($record['accepterinfo'], true);
            $record['email']        = !empty($record['accepterinfo'][3]) ? $record['accepterinfo'][3] : null;
            $record['truename']     = !empty($record['accepterinfo'][0]) ? $record['accepterinfo'][0] : null;

            return $record;
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return null;
        }
    }

    /**
     * 增加图度关联用户
     *
     * @param string $tuduId
     * @param string $uniqueId
     * @param array $params
     * @return boolean | string
     */
    public function addUser($tuduId, $uniqueId, $params = null)
    {
        $table = "td_tudu_user";
        $bind  = array(
            'unique_id'  => $uniqueId,
            'tudu_id'    => $tuduId,
            'is_read'    => empty($params['isread']) ? 0 : 1,
            'is_forward' => empty($params['isforward']) ? 0 : 1
            );

        if (isset($params['role'])) {
            $bind['role'] = $params['role'];
        }

        if (isset($params['accepterinfo'])) {
            $bind['accepter_info'] = $params['accepterinfo'];
        }

        if (isset($params['percent'])) {
            $bind['percent'] = (int) $params['percent'];
        }

        if (isset($params['forwardinfo'])) {
            $bind['forward_info'] = $params['forwardinfo'];
        }

        if (isset($params['tudustatus']) && is_int($params['tudustatus'])) {
            $bind['tudu_status'] = $params['tudustatus'];
        }

        if (isset($params['isforeign'])) {
            $bind['is_foreign'] = $params['isforeign'] ? 1 : 0;
        }

        if (isset($params['authcode'])) {
            $bind['auth_code'] = $params['authcode'];
        }

        try {
            $this->_db->insert($table, $bind);
        } catch (Zend_Db_Exception $e) {

            // 主键冲突
            if (23000 === $e->getCode()) {
                //return null;
                $sql = 'SELECT labels FROM td_tudu_user WHERE unique_id = ' . $this->_db->quote($uniqueId) . ' '
                     . 'AND tudu_id = ' . $this->_db->quote($tuduId);

                $record = $this->_db->fetchRow($sql);

                if (!$record) {
                    return false;
                }

                return (string) $record['labels'];
            }

            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 增加图度标签
     *
     * @param string $tuduId
     * @param string $uniqueId
     * @param string $labelId
     * @return boolean
     */
    public function addLabel($tuduId, $uniqueId, $labelId)
    {
        $sql = "call sp_td_add_tudu_label("
             . $this->_db->quote($tuduId) . ","
             . $this->_db->quote($uniqueId) . ","
             . $this->_db->quote($labelId) . ")";

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {

            // 主键冲突
            if (23000 === $e->getCode()) {
                return null;
            }

            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 更新用户图度信息
     *
     * @param $tuduId
     * @param $uniqueId
     * @param $params
     */
    public function updateTuduUser($tuduId, $uniqueId, $params)
    {
        $table = "td_tudu_user";
        $where = "unique_id = " . $this->_db->quote($uniqueId) . " AND tudu_id = " . $this->_db->quote($tuduId);
        $bind  = array();

        if (isset($params['isread'])) {
            $bind['is_read'] = $params['isread'] ? 1 : 0;
        }

        if (isset($params['isforward'])) {
            $bind['is_forward'] = $params['isforward'] ? 1 : 0;
        }

        if (array_key_exists('accepterinfo', $params)) {
            $bind['accepter_info'] = $params['accepterinfo'];
        }

        if (array_key_exists('percent', $params)) {
            $bind['percent'] = $params['percent'];
        }

        if (array_key_exists('tudustatus', $params)) {
            $bind['tudu_status'] = $params['tudustatus'];
        }

        if (array_key_exists('accepttime', $params)) {
            $bind['accept_time'] = $params['accepttime'];
        }

        if (array_key_exists('completetime', $params)) {
            $bind['complete_time'] = $params['completetime'];
        }

        if (array_key_exists('role', $params)) {
            $bind['role'] = $params['role'];
        }

        if (array_key_exists('isforeign', $params)) {
            $bind['is_foreign'] = $params['isforeign'] ? 1 : 0;
        }

        if (isset($params['forwardinfo'])) {
            $bind['forward_info'] = $params['forwardinfo'];
        }

        if (array_key_exists('authcode', $params)) {
            $bind['auth_code'] = $params['authcode'];
        }

        if (isset($params['mark'])) {
            $bind['mark'] = $params['mark'] ? 1 : 0;
        }

        if (empty($bind)) {
            return false;
        }

        try {
            $this->_db->update($table, $bind, $where);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 更新图度的标签标记
     *
     * @param $tuduId
     * @param $uniqueId
     * @param $labels
     */
    public function updateTuduLabels($tuduId, $uniqueId, $labels = null)
    {
        if (null === $labels) {
            $sql = "call sp_td_update_tudu_labels(" . $this->_db->quote($tuduId) . "," . $this->_db->quote($uniqueId) . ")";
        } else {
            $sql = "UPDATE td_tudu_user SET labels = " . $this->_db->quote($labels)
                 . " WHERE unique_id = " . $this->_db->quote($uniqueId)
                 . " AND tudu_id = " . $this->_db->quote($tuduId);
        }
        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 删除图度用户
     *
     * @param string $tuduId
     * @param string $uniqueId
     */
    public function deleteUser($tuduId, $uniqueId)
    {
        $sql = "DELETE FROM td_tudu_user"
             . " WHERE unique_id = " . $this->_db->quote($uniqueId)
             . " AND tudu_id = " . $this->_db->quote($tuduId);

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 移除接受人信息
     *
     * @param $tuduId
     * @param $uniqueId
     */
    public function removeAccepter($tuduId, $uniqueId)
    {
        return $this->updateTuduUser($tuduId, $uniqueId, array(
            'role'         => null,
            'percent'      => null,
            'tudustatus'   => null,
            'accepttime'   => null,
            'forwardinfo'  => null
        ));
    }

    /**
     * 删除图度标签
     *
     * @param string $tuduId
     * @param string $uniqueId
     * @param string $labelId
     * @return boolean
     */
    public function deleteLabel($tuduId, $uniqueId, $labelId)
    {
        $sql = "call sp_td_delete_tudu_label("
             . $this->_db->quote($tuduId) . ","
             . $this->_db->quote($uniqueId) . ","
             . $this->_db->quote($labelId) . ")";

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 递增浏览次数
     *
     * @param $tuduId
     * @return boolean
     */
    public function hit($tuduId)
    {
        $sql = "UPDATE td_tudu SET view_num = view_num + 1 WHERE tudu_id = " . $this->_db->quote($tuduId);
        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     *
     * @param $tuduId
     * @param $uniqueId
     * @return int 返回图度状态
     */
    public function rejectTudu($tuduId, $uniqueId, $isFlow = false)
    {
        if (empty($tuduId) || empty($uniqueId)) {
            return false;
        }

        $tuduId   = $this->_db->quote($tuduId);
        $uniqueId = $this->_db->quote($uniqueId);

        $table = 'td_tudu_user';
        $bind  = array(
            'tudu_status' => self::STATUS_REJECT,
            'accept_time' => null
        );
        $where = "tudu_id = {$tuduId} AND unique_id = {$uniqueId}";

        try {
            $this->_db->update($table, $bind, $where);

            if ($isFlow) {
                $status = self::STATUS_REJECT;
                $this->_db->query("UPDATE td_tudu SET status = {$status} WHERE tudu_id = {$tuduId}");
            } else {
                $sql = "SELECT AVG(tudu_status) AS status, AVG(percent) AS percent FROM td_tudu_user WHERE tudu_id = {$tuduId} AND role = 'to' AND tudu_status <> 3";
                $record = $this->_db->fetchRow($sql);
                $status  = $record['status'];
                $percent = (int) $record['percent'];

                if ('' === trim($status)) {
                    $status = self::STATUS_REJECT;
                } else {
                    $status = (float) $status > 1 ? (int) $status : ($status > 0 ? 1 : 0);
                }

                $this->_db->query("UPDATE td_tudu SET status = {$status}, percent = {$percent} WHERE tudu_id = {$tuduId}");
            }

        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return $status;
    }

    /**
     * 标志已读状态
     *
     * @param string $tuduId
     * @param string $uniqueId
     * @param boolean $isRead
     */
    public function markRead($tuduId, $uniqueId, $isRead = true)
    {
        $tuduId = $this->_db->quote($tuduId);
        $uniqueId = $this->_db->quote($uniqueId);

        if ($isRead) {
            $sql = 'call sp_td_mark_read(' . $tuduId . ',' . $uniqueId . ')';
        } else {
            $sql = 'call sp_td_mark_unread(' . $tuduId . ',' . $uniqueId . ')';
        }

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 设置标签下所有图度为已读
     * 执行后必须重新统计标签的未读数
     *
     * @param string  $labelId
     * @param string  $uniqueId
     * @param boolean $isRead
     */
    public function markLabelRead($labelId, $uniqueId, $isRead = true)
    {
        $labelId  = $this->_db->quote($labelId);
        $uniqueId = $this->_db->quote($uniqueId);
        $isRead   = $isRead ? 1 : 0;

        $sql = "UPDATE td_tudu_user SET is_read = {$isRead} WHERE unique_id = {$uniqueId} "
             . "AND tudu_id IN (SELECT tudu_id FROM td_tudu_label WHERE unique_id = {$uniqueId} AND label_id = {$labelId})";

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 设置所有关联用户为未读状态
     *
     * @param $tuduId
     * @return boolean
     */
    public function markAllUnRead($tuduId)
    {
        $tuduId = $this->_db->quote($tuduId);
        $sql = 'call sp_td_mark_all_unread(' . $tuduId . ')';

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 标志为转发状态
     *
     * @param string $tuduId
     * @param string $uniqueId
     */
    public function markForward($tuduId, $uniqueId)
    {
        $sql = "UPDATE td_tudu_user"
             . " SET is_forward = 1"
             . " WHERE unique_id = " . $this->_db->quote($uniqueId)
             . " AND tudu_id = " . $this->_db->quote($tuduId);

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 接收人更新任务进度
     *
     * @param $tuduId
     * @param $uniqueId
     * @param $percent
     */
    public function updateProgress($tuduId, $uniqueId, $percent)
    {
        $tuduId   = $this->_db->quote($tuduId);
        $uniqueId = $this->_db->quote($uniqueId);
        $percent  = null !== $percent ? min(100, abs((int) $percent)) : 'NULL';
        $sql = "call sp_td_update_tudu_progress({$tuduId}, {$uniqueId}, {$percent})";

        try {
            $totalPercent = (int) $this->_db->fetchOne($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return $totalPercent;
    }

    /**
     * 更新工作流进度
     *
     * @param $tuduId
     * @param $uniqueId
     * @param $percent
     */
    public function updateFlowProgress($tuduId, $uniqueId, $stepId, $percent = null, &$flowPercent = null)
    {
        if ($stepId == '^head' || $stepId == '^break') {
            return true;
        }
        $sql   = "SELECT steps FROM td_tudu_flow WHERE tudu_id = :tuduid";

        $steps = $this->_db->fetchRow($sql, array('tuduid' => $tuduId));

        if (!$steps) {
            return ;
        }
        $steps = json_decode($steps['steps'], true);

        $count = count($steps);
        $currentStep = null;
        $done  = 0;
        $type  = 0;

        foreach ($steps as $step) {
            if ($step['stepid'] == $stepId) {
                $type = $step['type'];

                break;
            }

            $done ++;
        }

        $avg = 100 / $count;
        $base = $avg * $done;

        if (0 == $type) {
            if (null != $uniqueId && is_int($percent)) {
                if ($percent == 100) {
                    $this->_db->query('UPDATE td_tudu_user SET percent = :percent, tudu_status = :status, complete_time = :completetime WHERE tudu_id = :tuduid AND unique_id = :uniqueid', array(
                        'percent' => $percent,
                        'status'  => 2,
                        'completetime' => time(),
                        'tuduid'  => $tuduId,
                        'uniqueid' => $uniqueId
                    ));
                } else {
                    $this->_db->query('UPDATE td_tudu_user SET percent = :percent WHERE tudu_id = :tuduid AND unique_id = :uniqueid', array(
                        'percent' => $percent,
                        'tuduid'  => $tuduId,
                        'uniqueid' => $uniqueId
                    ));
                }
            }

            // 步骤总体进度
            $sql = "SELECT AVG(percent) FROM td_tudu_user WHERE tudu_id = :tuduid AND role = 'to' AND (tudu_status IS NULL OR tudu_status < 3)";

            $percent = (int) $this->_db->fetchOne($sql, array('tuduid' => $tuduId));

            $flowPercent = $base + ($avg * $percent / 100);
        } elseif ($type == 1) {
            $users   = $currentStep['section'][$currentStep['currentSection']];

            if (count($users)) {
                $avgStep = $avg / count($users);

                $acceptCount = 0;
                foreach ($users as $user) {
                    if ($user['status'] == 2) {
                        $acceptCount ++;
                    }
                }
            } else {
                $avgStep = 1;
                $acceptCount = 0;
            }

            $flowPercent = $base + ($avgStep * $acceptCount);
        } else {
            $flowPercent = $base;
        }

        $params = array();
        $params['percent'] = min(100, $flowPercent);
        if ((int) $params['percent'] == 100) {
            $params['status'] = 2;
            $params['complete_time'] = time();
        }
        $this->_db->update('td_tudu', $params, 'tudu_id = ' . $this->_db->quote($tuduId));

        $flowPercent = $params['percent'];
        return $percent;
    }

    /**
     * 更新最后接受时间(更新非接收人看到的图度接受状态)
     *
     * @param string $tuduId
     */
    public function updateLastAcceptTime($tuduId)
    {
        $tuduId = $this->_db->quote($tuduId);

        $sql = "UPDATE td_tudu SET accept_time = (SELECT MAX(accept_time) FROM td_tudu_user WHERE tudu_id = {$tuduId}) "
             . "WHERE tudu_id = {$tuduId}";

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * 计算父级图度的进度
     *
     * @param $tuduId
     */
    public function calParentsProgress($tuduId)
    {
        $tuduId = $this->_db->quote($tuduId);

        $sql = "call sp_td_calculate_parents_progress({$tuduId})";

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * 计算图度已耗时
     *
     * @param $tuduId
     * @return boolean
     */
    public function calcElapsedTime($tuduId)
    {
        $tuduId = $this->_db->quote($tuduId);
        $sql = 'call sp_td_calculate_tudu_elapsed_time(' . $tuduId . ')';

        try {
            $this->_db->query($sql);
        } catch (Zend_Db_Exception $e) {
            $this->_catchException($e, __METHOD__);
            return false;
        }

        return true;
    }

    /**
     * Get tudu by id
     *
     * @param string $tuduId
     * @param string $uniqueId
     * @param array $filter
     * @return Dao_Td_Tudu_Record_Tudu
     */
    public function getTuduById($uniqueId, $tuduId, $filter = null)
    {
        return $this->getTudu(array('uniqueid' => $uniqueId, 'tuduid' => $tuduId), $filter);
    }

    /**
     * 格式化地址
     *
     * 地址以 “邮箱[空格]姓名[换行]邮箱[空格]姓名”格式保存
     * 返回格式
     * array(
     *     address1 => array(name1, userid1, domain1, address1, extend1),
     *     address2 => array(name2, userid2, domain2, address2, extend2),
     *     address3 => array(name3, userid3, domain3, address3, extend3)
     * )
     *
     * @param string $address
     * @param boolean $first 是否仅返回第一条记录,如果发件人仅有一个
     * @return array
     */
    public static function formatAddress($address, $first = false)
    {
        $ret = array();

        $pattern = "/(([\^]?[\w-\.\_]+)(?:@([^ ]+))?)? ([^\n]*)/";

        if ($first) {
            preg_match($pattern, $address, $matches);
            if ($matches) {
                $ret = array($matches[4], $matches[2], $matches[3], $matches[1]);
            }
        } else {
            preg_match_all($pattern, $address, $matches);
            for ($i = 0; $i < count($matches[0]); $i++) {
                if ($matches[1][$i]) {
                    $ret[$matches[1][$i]] = array($matches[4][$i], $matches[2][$i], $matches[3][$i], $matches[1][$i]);
                } else {
                    $ret[] = array($matches[4][$i], $matches[2][$i], $matches[3][$i], $matches[1][$i]);
                }
            }
        }
        return $ret;
    }

    /**
     * 获取图度ID
     *
     * 生成规则:微秒级时间戳转16位 + 0xfffff最大值随机数转16位
     * 格式如 129fcd77e2043a86,类似gmail生成格式
     *
     * @return string
     */
    public static function getTuduId()
    {
        $tuduId = base_convert(substr(microtime(true) * 10000, 0, -1), 10, 16) . str_pad(dechex(mt_rand(0, 0xfffff)), 5, '0', STR_PAD_LEFT);
        return $tuduId;
    }
}
Back to Top