comment.module 91.1 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 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 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
<?php

/**
 * @file
 * Enables users to comment on published content.
 *
 * When enabled, the Drupal comment module creates a discussion
 * board for each Drupal node. Users can post comments to discuss
 * a forum topic, weblog post, story, collaborative book page, etc.
 */

/**
 * Comment is awaiting approval.
 */
define('COMMENT_NOT_PUBLISHED', 0);

/**
 * Comment is published.
 */
define('COMMENT_PUBLISHED', 1);

/**
 * Comments are displayed in a flat list - expanded.
 */
define('COMMENT_MODE_FLAT', 0);

/**
 * Comments are displayed as a threaded list - expanded.
 */
define('COMMENT_MODE_THREADED', 1);

/**
 * Anonymous posters cannot enter their contact information.
 */
define('COMMENT_ANONYMOUS_MAYNOT_CONTACT', 0);

/**
 * Anonymous posters may leave their contact information.
 */
define('COMMENT_ANONYMOUS_MAY_CONTACT', 1);

/**
 * Anonymous posters are required to leave their contact information.
 */
define('COMMENT_ANONYMOUS_MUST_CONTACT', 2);

/**
 * Comment form should be displayed on a separate page.
 */
define('COMMENT_FORM_SEPARATE_PAGE', 0);

/**
 * Comment form should be shown below post or list of comments.
 */
define('COMMENT_FORM_BELOW', 1);

/**
 * Comments for this node are hidden.
 */
define('COMMENT_NODE_HIDDEN', 0);

/**
 * Comments for this node are closed.
 */
define('COMMENT_NODE_CLOSED', 1);

/**
 * Comments for this node are open.
 */
define('COMMENT_NODE_OPEN', 2);

/**
 * Implements hook_help().
 */
function comment_help($path, $arg) {
  switch ($path) {
    case 'admin/help#comment':
      $output = '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the online handbook entry for <a href="@comment">Comment module</a>.', array('@comment' => 'http://drupal.org/documentation/modules/comment/')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Default and custom settings') . '</dt>';
      $output .= '<dd>' . t("Each <a href='@content-type'>content type</a> can have its own default comment settings configured as: <em>Open</em> to allow new comments, <em>Hidden</em> to hide existing comments and prevent new comments, or <em>Closed</em> to view existing comments, but prevent new comments. These defaults will apply to all new content created (changes to the settings on existing content must be done manually). Other comment settings can also be customized per content type, and can be overridden for any given item of content. When a comment has no replies, it remains editable by its author, as long as the author has a user account and is logged in.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
      $output .= '<dt>' . t('Comment approval') . '</dt>';
      $output .= '<dd>' . t("Comments from users who have the <em>Skip comment approval</em> permission are published immediately. All other comments are placed in the <a href='@comment-approval'>Unapproved comments</a> queue, until a user who has permission to <em>Administer comments</em> publishes or deletes them. Published comments can be bulk managed on the <a href='@admin-comment'>Published comments</a> administration page.", array('@comment-approval' => url('admin/content/comment/approval'), '@admin-comment' => url('admin/content/comment'))) . '</dd>';
      $output .= '</dl>';
      return $output;
  }
}

/**
 * Implements hook_entity_info().
 */
function comment_entity_info() {
  $return = array(
    'comment' => array(
      'label' => t('Comment'),
      'base table' => 'comment',
      'uri callback' => 'comment_uri',
      'fieldable' => TRUE,
      'controller class' => 'CommentController',
      'entity keys' => array(
        'id' => 'cid',
        'bundle' => 'node_type',
        'label' => 'subject',
        'language' => 'language',
      ),
      'bundles' => array(),
      'view modes' => array(
        'full' => array(
          'label' => t('Full comment'),
          'custom settings' => FALSE,
        ),
      ),
      'static cache' => FALSE,
    ),
  );

  foreach (node_type_get_names() as $type => $name) {
    $return['comment']['bundles']['comment_node_' . $type] = array(
      'label' => t('@node_type comment', array('@node_type' => $name)),
      // Provide the node type/bundle name for other modules, so it does not
      // have to be extracted manually from the bundle name.
      'node bundle' => $type,
      'admin' => array(
        // Place the Field UI paths for comments one level below the
        // corresponding paths for nodes, so that they appear in the same set
        // of local tasks. Note that the paths use a different placeholder name
        // and thus a different menu loader callback, so that Field UI page
        // callbacks get a comment bundle name from the node type in the URL.
        // See comment_node_type_load() and comment_menu_alter().
        'path' => 'admin/structure/types/manage/%comment_node_type/comment',
        'bundle argument' => 4,
        'real path' => 'admin/structure/types/manage/' . str_replace('_', '-', $type) . '/comment',
        'access arguments' => array('administer content types'),
      ),
    );
  }

  return $return;
}

/**
 * Menu loader callback for Field UI paths.
 *
 * Return a comment bundle name from a node type in the URL.
 */
function comment_node_type_load($name) {
  if ($type = node_type_get_type(strtr($name, array('-' => '_')))) {
    return 'comment_node_' . $type->type;
  }
}

/**
 * Implements callback_entity_info_uri().
 */
function comment_uri($comment) {
  return array(
    'path' => 'comment/' . $comment->cid,
    'options' => array('fragment' => 'comment-' . $comment->cid),
  );
}

/**
 * Implements hook_field_extra_fields().
 */
function comment_field_extra_fields() {
  $return = array();

  foreach (node_type_get_types() as $type) {
    if (variable_get('comment_subject_field_' . $type->type, 1) == 1) {
      $return['comment']['comment_node_' . $type->type] = array(
        'form' => array(
          'author' => array(
            'label' => t('Author'),
            'description' => t('Author textfield'),
            'weight' => -2,
          ),
          'subject' => array(
            'label' => t('Subject'),
            'description' => t('Subject textfield'),
            'weight' => -1,
          ),
        ),
      );
    }
  }

  return $return;
}

/**
 * Implements hook_theme().
 */
function comment_theme() {
  return array(
    'comment_block' => array(
      'variables' => array(),
    ),
    'comment_preview' => array(
      'variables' => array('comment' => NULL),
    ),
    'comment' => array(
      'template' => 'comment',
      'render element' => 'elements',
    ),
    'comment_post_forbidden' => array(
      'variables' => array('node' => NULL),
    ),
    'comment_wrapper' => array(
      'template' => 'comment-wrapper',
      'render element' => 'content',
    ),
  );
}

/**
 * Implements hook_menu().
 */
function comment_menu() {
  $items['admin/content/comment'] = array(
    'title' => 'Comments',
    'description' => 'List and edit site comments and the comment approval queue.',
    'page callback' => 'comment_admin',
    'access arguments' => array('administer comments'),
    'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
    'file' => 'comment.admin.inc',
  );
  // Tabs begin here.
  $items['admin/content/comment/new'] = array(
    'title' => 'Published comments',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/content/comment/approval'] = array(
    'title' => 'Unapproved comments',
    'title callback' => 'comment_count_unpublished',
    'page arguments' => array('approval'),
    'access arguments' => array('administer comments'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['comment/%'] = array(
    'title' => 'Comment permalink',
    'page callback' => 'comment_permalink',
    'page arguments' => array(1),
    'access arguments' => array('access comments'),
  );
  $items['comment/%/view'] = array(
    'title' => 'View comment',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  // Every other comment path uses %, but this one loads the comment directly,
  // so we don't end up loading it twice (in the page and access callback).
  $items['comment/%comment/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'comment_edit_page',
    'page arguments' => array(1),
    'access callback' => 'comment_access',
    'access arguments' => array('edit', 1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
  );
  $items['comment/%/approve'] = array(
    'title' => 'Approve',
    'page callback' => 'comment_approve',
    'page arguments' => array(1),
    'access arguments' => array('administer comments'),
    'file' => 'comment.pages.inc',
    'weight' => 1,
  );
  $items['comment/%/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'comment_confirm_delete_page',
    'page arguments' => array(1),
    'access arguments' => array('administer comments'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'comment.admin.inc',
    'weight' => 2,
  );
  $items['comment/reply/%node'] = array(
    'title' => 'Add new comment',
    'page callback' => 'comment_reply',
    'page arguments' => array(2),
    'access callback' => 'node_access',
    'access arguments' => array('view', 2),
    'file' => 'comment.pages.inc',
  );

  return $items;
}

/**
 * Implements hook_menu_alter().
 */
function comment_menu_alter(&$items) {
  // Add comments to the description for admin/content.
  $items['admin/content']['description'] = 'Administer content and comments.';

  // Adjust the Field UI tabs on admin/structure/types/manage/[node-type].
  // See comment_entity_info().
  $items['admin/structure/types/manage/%comment_node_type/comment/fields']['title'] = 'Comment fields';
  $items['admin/structure/types/manage/%comment_node_type/comment/fields']['weight'] = 3;
  $items['admin/structure/types/manage/%comment_node_type/comment/display']['title'] = 'Comment display';
  $items['admin/structure/types/manage/%comment_node_type/comment/display']['weight'] = 4;
}

/**
 * Returns a menu title which includes the number of unapproved comments.
 */
function comment_count_unpublished() {
  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE status = :status', array(
    ':status' => COMMENT_NOT_PUBLISHED,
  ))->fetchField();
  return t('Unapproved comments (@count)', array('@count' => $count));
}

/**
 * Implements hook_node_type_insert().
 *
 * Creates a comment body field for a node type created while the comment module
 * is enabled. For node types created before the comment module is enabled,
 * hook_modules_enabled() serves to create the body fields.
 *
 * @see comment_modules_enabled()
 */
function comment_node_type_insert($info) {
  _comment_body_field_create($info);
}

/**
 * Implements hook_node_type_update().
 */
function comment_node_type_update($info) {
  if (!empty($info->old_type) && $info->type != $info->old_type) {
    field_attach_rename_bundle('comment', 'comment_node_' . $info->old_type, 'comment_node_' . $info->type);
  }
}

/**
 * Implements hook_node_type_delete().
 */
function comment_node_type_delete($info) {
  field_attach_delete_bundle('comment', 'comment_node_' . $info->type);
  $settings = array(
    'comment',
    'comment_default_mode',
    'comment_default_per_page',
    'comment_anonymous',
    'comment_subject_field',
    'comment_preview',
    'comment_form_location',
  );
  foreach ($settings as $setting) {
    variable_del($setting . '_' . $info->type);
  }
}

 /**
 * Creates a comment_body field instance for a given node type.
 */
function _comment_body_field_create($info) {
  // Create the field if needed.
  if (!field_read_field('comment_body', array('include_inactive' => TRUE))) {
    $field = array(
      'field_name' => 'comment_body',
      'type' => 'text_long',
      'entity_types' => array('comment'),
    );
    field_create_field($field);
  }
  // Create the instance if needed.
  if (!field_read_instance('comment', 'comment_body', 'comment_node_' . $info->type, array('include_inactive' => TRUE))) {
    field_attach_create_bundle('comment', 'comment_node_' . $info->type);
    // Attaches the body field by default.
    $instance = array(
      'field_name' => 'comment_body',
      'label' => 'Comment',
      'entity_type' => 'comment',
      'bundle' => 'comment_node_' . $info->type,
      'settings' => array('text_processing' => 1),
      'required' => TRUE,
      'display' => array(
        'default' => array(
          'label' => 'hidden',
          'type' => 'text_default',
          'weight' => 0,
        ),
      ),
    );
    field_create_instance($instance);
  }
}

/**
 * Implements hook_permission().
 */
function comment_permission() {
  return array(
    'administer comments' => array(
      'title' => t('Administer comments and comment settings'),
    ),
    'access comments' => array(
      'title' => t('View comments'),
    ),
    'post comments' => array(
      'title' => t('Post comments'),
    ),
    'skip comment approval' => array(
      'title' => t('Skip comment approval'),
    ),
    'edit own comments' => array(
      'title' => t('Edit own comments'),
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function comment_block_info() {
  $blocks['recent']['info'] = t('Recent comments');
  $blocks['recent']['properties']['administrative'] = TRUE;

  return $blocks;
}

/**
 * Implements hook_block_configure().
 */
function comment_block_configure($delta = '') {
  $form['comment_block_count'] = array(
    '#type' => 'select',
    '#title' => t('Number of recent comments'),
    '#default_value' => variable_get('comment_block_count', 10),
    '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30)),
  );

  return $form;
}

/**
 * Implements hook_block_save().
 */
function comment_block_save($delta = '', $edit = array()) {
  variable_set('comment_block_count', (int) $edit['comment_block_count']);
}

/**
 * Implements hook_block_view().
 *
 * Generates a block with the most recent comments.
 */
function comment_block_view($delta = '') {
  if (user_access('access comments')) {
    $block['subject'] = t('Recent comments');
    $block['content'] = theme('comment_block');

    return $block;
  }
}

/**
 * Redirects comment links to the correct page depending on comment settings.
 *
 * Since comments are paged there is no way to guarantee which page a comment
 * appears on. Comment paging and threading settings may be changed at any time.
 * With threaded comments, an individual comment may move between pages as
 * comments can be added either before or after it in the overall discussion.
 * Therefore we use a central routing function for comment links, which
 * calculates the page number based on current comment settings and returns
 * the full comment view with the pager set dynamically.
 *
 * @param $cid
 *   A comment identifier.
 * @return
 *   The comment listing set to the page on which the comment appears.
 */
function comment_permalink($cid) {
  if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {

    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);

    // Set $_GET['q'] and $_GET['page'] ourselves so that the node callback
    // behaves as it would when visiting the page directly.
    $_GET['q'] = 'node/' . $node->nid;
    $_GET['page'] = $page;

    // Return the node view, this will show the correct comment in context.
    return menu_execute_active_handler('node/' . $node->nid, FALSE);
  }
  return MENU_NOT_FOUND;
}

/**
 * Find the most recent comments that are available to the current user.
 *
 * @param integer $number
 *   (optional) The maximum number of comments to find. Defaults to 10.
 *
 * @return
 *   An array of comment objects or an empty array if there are no recent
 *   comments visible to the current user.
 */
function comment_get_recent($number = 10) {
  $query = db_select('comment', 'c');
  $query->innerJoin('node', 'n', 'n.nid = c.nid');
  $query->addTag('node_access');
  $comments = $query
    ->fields('c')
    ->condition('c.status', COMMENT_PUBLISHED)
    ->condition('n.status', NODE_PUBLISHED)
    ->orderBy('c.created', 'DESC')
    // Additionally order by cid to ensure that comments with the same timestamp
    // are returned in the exact order posted.
    ->orderBy('c.cid', 'DESC')
    ->range(0, $number)
    ->execute()
    ->fetchAll();

  return $comments ? $comments : array();
}

/**
 * Calculate page number for first new comment.
 *
 * @param $num_comments
 *   Number of comments.
 * @param $new_replies
 *   Number of new replies.
 * @param $node
 *   The first new comment node.
 * @return
 *   "page=X" if the page number is greater than zero; empty string otherwise.
 */
function comment_new_page_count($num_comments, $new_replies, $node) {
  $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
  $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
  $pagenum = NULL;
  $flat = $mode == COMMENT_MODE_FLAT ? TRUE : FALSE;
  if ($num_comments <= $comments_per_page) {
    // Only one page of comments.
    $pageno = 0;
  }
  elseif ($flat) {
    // Flat comments.
    $count = $num_comments - $new_replies;
    $pageno = $count / $comments_per_page;
  }
  else {
    // Threaded comments: we build a query with a subquery to find the first
    // thread with a new comment.

    // 1. Find all the threads with a new comment.
    $unread_threads_query = db_select('comment')
      ->fields('comment', array('thread'))
      ->condition('nid', $node->nid)
      ->condition('status', COMMENT_PUBLISHED)
      ->orderBy('created', 'DESC')
      ->orderBy('cid', 'DESC')
      ->range(0, $new_replies);

    // 2. Find the first thread.
    $first_thread = db_select($unread_threads_query, 'thread')
      ->fields('thread', array('thread'))
      ->orderBy('SUBSTRING(thread, 1, (LENGTH(thread) - 1))')
      ->range(0, 1)
      ->execute()
      ->fetchField();

    // Remove the final '/'.
    $first_thread = substr($first_thread, 0, -1);

    // Find the number of the first comment of the first unread thread.
    $count = db_query('SELECT COUNT(*) FROM {comment} WHERE nid = :nid AND status = :status AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread', array(
      ':status' => COMMENT_PUBLISHED,
      ':nid' => $node->nid,
      ':thread' => $first_thread,
    ))->fetchField();

    $pageno = $count / $comments_per_page;
  }

  if ($pageno >= 1) {
    $pagenum = array('page' => intval($pageno));
  }

  return $pagenum;
}

/**
 * Returns HTML for a list of recent comments to be displayed in the comment block.
 *
 * @ingroup themeable
 */
function theme_comment_block() {
  $items = array();
  $number = variable_get('comment_block_count', 10);
  foreach (comment_get_recent($number) as $comment) {
    $items[] = l($comment->subject, 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)) . '&nbsp;<span>' . t('@time ago', array('@time' => format_interval(REQUEST_TIME - $comment->changed))) . '</span>';
  }

  if ($items) {
    return theme('item_list', array('items' => $items));
  }
  else {
    return t('No comments available.');
  }
}

/**
 * Implements hook_node_view().
 */
function comment_node_view($node, $view_mode) {
  $links = array();

  if ($node->comment != COMMENT_NODE_HIDDEN) {
    if ($view_mode == 'rss') {
      // Add a comments RSS element which is a URL to the comments of this node.
      $node->rss_elements[] = array(
        'key' => 'comments',
        'value' => url('node/' . $node->nid, array('fragment' => 'comments', 'absolute' => TRUE))
      );
    }
    elseif ($view_mode == 'teaser') {
      // Teaser view: display the number of comments that have been posted,
      // or a link to add new comments if the user has permission, the node
      // is open to new comments, and there currently are none.
      if (user_access('access comments')) {
        if (!empty($node->comment_count)) {
          $links['comment-comments'] = array(
            'title' => format_plural($node->comment_count, '1 comment', '@count comments'),
            'href' => "node/$node->nid",
            'attributes' => array('title' => t('Jump to the first comment of this posting.')),
            'fragment' => 'comments',
            'html' => TRUE,
          );
          // Show a link to the first new comment.
          if ($new = comment_num_new($node->nid)) {
            $links['comment-new-comments'] = array(
              'title' => format_plural($new, '1 new comment', '@count new comments'),
              'href' => "node/$node->nid",
              'query' => comment_new_page_count($node->comment_count, $new, $node),
              'attributes' => array('title' => t('Jump to the first new comment of this posting.')),
              'fragment' => 'new',
              'html' => TRUE,
            );
          }
        }
      }
      if ($node->comment == COMMENT_NODE_OPEN) {
        if (user_access('post comments')) {
          $links['comment-add'] = array(
            'title' => t('Add new comment'),
            'href' => "comment/reply/$node->nid",
            'attributes' => array('title' => t('Add a new comment to this page.')),
            'fragment' => 'comment-form',
          );
        }
        else {
          $links['comment_forbidden'] = array(
            'title' => theme('comment_post_forbidden', array('node' => $node)),
            'html' => TRUE,
          );
        }
      }
    }
    elseif ($view_mode != 'search_index' && $view_mode != 'search_result') {
      // Node in other view modes: add a "post comment" link if the user is
      // allowed to post comments and if this node is allowing new comments.
      // But we don't want this link if we're building the node for search
      // indexing or constructing a search result excerpt.
      if ($node->comment == COMMENT_NODE_OPEN) {
        $comment_form_location = variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW);
        if (user_access('post comments')) {
          // Show the "post comment" link if the form is on another page, or
          // if there are existing comments that the link will skip past.
          if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE || (!empty($node->comment_count) && user_access('access comments'))) {
            $links['comment-add'] = array(
              'title' => t('Add new comment'),
              'attributes' => array('title' => t('Share your thoughts and opinions related to this posting.')),
              'href' => "node/$node->nid",
              'fragment' => 'comment-form',
            );
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
              $links['comment-add']['href'] = "comment/reply/$node->nid";
            }
          }
        }
        else {
          $links['comment_forbidden'] = array(
            'title' => theme('comment_post_forbidden', array('node' => $node)),
            'html' => TRUE,
          );
        }
      }
    }

    $node->content['links']['comment'] = array(
      '#theme' => 'links__node__comment',
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
    );

    // Only append comments when we are building a node on its own node detail
    // page. We compare $node and $page_node to ensure that comments are not
    // appended to other nodes shown on the page, for example a node_reference
    // displayed in 'full' view mode within another node.
    if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
      $node->content['comments'] = comment_node_page_additions($node);
    }
  }
}

/**
 * Build the comment-related elements for node detail pages.
 *
 * @param $node
 *  A node object.
 */
function comment_node_page_additions($node) {
  $additions = array();

  // Only attempt to render comments if the node has visible comments.
  // Unpublished comments are not included in $node->comment_count, so show
  // comments unconditionally if the user is an administrator.
  if (($node->comment_count && user_access('access comments')) || user_access('administer comments')) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
    if ($cids = comment_get_thread($node, $mode, $comments_per_page)) {
      $comments = comment_load_multiple($cids);
      comment_prepare_thread($comments);
      $build = comment_view_multiple($comments, $node);
      $build['pager']['#theme'] = 'pager';
      $additions['comments'] = $build;
    }
  }

  // Append comment form if needed.
  if (user_access('post comments') && $node->comment == COMMENT_NODE_OPEN && (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW) == COMMENT_FORM_BELOW)) {
    $build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));
    $additions['comment_form'] = $build;
  }

  if ($additions) {
    $additions += array(
      '#theme' => 'comment_wrapper__node_' . $node->type,
      '#node' => $node,
      'comments' => array(),
      'comment_form' => array(),
    );
  }

  return $additions;
}

/**
 * Retrieve comments for a thread.
 *
 * @param $node
 *   The node whose comment(s) needs rendering.
 * @param $mode
 *   The comment display mode; COMMENT_MODE_FLAT or COMMENT_MODE_THREADED.
 * @param $comments_per_page
 *   The amount of comments to display per page.
 *
 * To display threaded comments in the correct order we keep a 'thread' field
 * and order by that value. This field keeps this data in
 * a way which is easy to update and convenient to use.
 *
 * A "thread" value starts at "1". If we add a child (A) to this comment,
 * we assign it a "thread" = "1.1". A child of (A) will have "1.1.1". Next
 * brother of (A) will get "1.2". Next brother of the parent of (A) will get
 * "2" and so on.
 *
 * First of all note that the thread field stores the depth of the comment:
 * depth 0 will be "X", depth 1 "X.X", depth 2 "X.X.X", etc.
 *
 * Now to get the ordering right, consider this example:
 *
 * 1
 * 1.1
 * 1.1.1
 * 1.2
 * 2
 *
 * If we "ORDER BY thread ASC" we get the above result, and this is the
 * natural order sorted by time. However, if we "ORDER BY thread DESC"
 * we get:
 *
 * 2
 * 1.2
 * 1.1.1
 * 1.1
 * 1
 *
 * Clearly, this is not a natural way to see a thread, and users will get
 * confused. The natural order to show a thread by time desc would be:
 *
 * 2
 * 1
 * 1.2
 * 1.1
 * 1.1.1
 *
 * which is what we already did before the standard pager patch. To achieve
 * this we simply add a "/" at the end of each "thread" value. This way, the
 * thread fields will look like this:
 *
 * 1/
 * 1.1/
 * 1.1.1/
 * 1.2/
 * 2/
 *
 * we add "/" since this char is, in ASCII, higher than every number, so if
 * now we "ORDER BY thread DESC" we get the correct order. However this would
 * spoil the reverse ordering, "ORDER BY thread ASC" -- here, we do not need
 * to consider the trailing "/" so we use a substring only.
 */
function comment_get_thread($node, $mode, $comments_per_page) {
  $query = db_select('comment', 'c')->extend('PagerDefault');
  $query->addField('c', 'cid');
  $query
    ->condition('c.nid', $node->nid)
    ->addTag('node_access')
    ->addTag('comment_filter')
    ->addMetaData('node', $node)
    ->limit($comments_per_page);

  $count_query = db_select('comment', 'c');
  $count_query->addExpression('COUNT(*)');
  $count_query
    ->condition('c.nid', $node->nid)
    ->addTag('node_access')
    ->addTag('comment_filter')
    ->addMetaData('node', $node);

  if (!user_access('administer comments')) {
    $query->condition('c.status', COMMENT_PUBLISHED);
    $count_query->condition('c.status', COMMENT_PUBLISHED);
  }
  if ($mode === COMMENT_MODE_FLAT) {
    $query->orderBy('c.cid', 'ASC');
  }
  else {
    // See comment above. Analysis reveals that this doesn't cost too
    // much. It scales much much better than having the whole comment
    // structure.
    $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
    $query->orderBy('torder', 'ASC');
  }

  $query->setCountQuery($count_query);
  $cids = $query->execute()->fetchCol();

  return $cids;
}

/**
 * Loop over comment thread, noting indentation level.
 *
 * @param array $comments
 *   An array of comment objects, keyed by cid.
 * @return
 *   The $comments argument is altered by reference with indentation information.
 */
function comment_prepare_thread(&$comments) {
  // A flag stating if we are still searching for first new comment on the thread.
  $first_new = TRUE;

  // A counter that helps track how indented we are.
  $divs = 0;

  foreach ($comments as $key => $comment) {
    if ($first_new && $comment->new != MARK_READ) {
      // Assign the anchor only for the first new comment. This avoids duplicate
      // id attributes on a page.
      $first_new = FALSE;
      $comment->first_new = TRUE;
    }

    // The $divs element instructs #prefix whether to add an indent div or
    // close existing divs (a negative value).
    $comment->depth = count(explode('.', $comment->thread)) - 1;
    if ($comment->depth > $divs) {
      $comment->divs = 1;
      $divs++;
    }
    else {
      $comment->divs = $comment->depth - $divs;
      while ($comment->depth < $divs) {
        $divs--;
      }
    }
    $comments[$key] = $comment;
  }

  // The final comment must close up some hanging divs
  $comments[$key]->divs_final = $divs;
}

/**
 * Generate an array for rendering the given comment.
 *
 * @param $comment
 *   A comment object.
 * @param $node
 *   The node the comment is attached to.
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
 * @return
 *   An array as expected by drupal_render().
 */
function comment_view($comment, $node, $view_mode = 'full', $langcode = NULL) {
  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  // Populate $comment->content with a render() array.
  comment_build_content($comment, $node, $view_mode, $langcode);

  $build = $comment->content;
  // We don't need duplicate rendering info in comment->content.
  unset($comment->content);

  $build += array(
    '#theme' => 'comment__node_' . $node->type,
    '#comment' => $comment,
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  if (empty($comment->in_preview)) {
    $prefix = '';
    $is_threaded = isset($comment->divs) && variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED) == COMMENT_MODE_THREADED;

    // Add 'new' anchor if needed.
    if (!empty($comment->first_new)) {
      $prefix .= "<a id=\"new\"></a>\n";
    }

    // Add indentation div or close open divs as needed.
    if ($is_threaded) {
      $prefix .= $comment->divs <= 0 ? str_repeat('</div>', abs($comment->divs)) : "\n" . '<div class="indented">';
    }

    // Add anchor for each comment.
    $prefix .= "<a id=\"comment-$comment->cid\"></a>\n";
    $build['#prefix'] = $prefix;

    // Close all open divs.
    if ($is_threaded && !empty($comment->divs_final)) {
      $build['#suffix'] = str_repeat('</div>', $comment->divs_final);
    }
  }

  // Allow modules to modify the structured comment.
  $type = 'comment';
  drupal_alter(array('comment_view', 'entity_view'), $build, $type);

  return $build;
}

/**
 * Builds a structured array representing the comment's content.
 *
 * The content built for the comment (field values, comments, file attachments or
 * other comment components) will vary depending on the $view_mode parameter.
 *
 * @param $comment
 *   A comment object.
 * @param $node
 *   The node the comment is attached to.
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 */
function comment_build_content($comment, $node, $view_mode = 'full', $langcode = NULL) {
  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  // Remove previously built content, if exists.
  $comment->content = array();

  // Allow modules to change the view mode.
  $view_mode = key(entity_view_mode_prepare('comment', array($comment->cid => $comment), $view_mode, $langcode));

  // Build fields content.
  field_attach_prepare_view('comment', array($comment->cid => $comment), $view_mode, $langcode);
  entity_prepare_view('comment', array($comment->cid => $comment), $langcode);
  $comment->content += field_attach_view('comment', $comment, $view_mode, $langcode);

  $comment->content['links'] = array(
    '#theme' => 'links__comment',
    '#pre_render' => array('drupal_pre_render_links'),
    '#attributes' => array('class' => array('links', 'inline')),
  );
  if (empty($comment->in_preview)) {
    $comment->content['links']['comment'] = array(
      '#theme' => 'links__comment__comment',
      '#links' => comment_links($comment, $node),
      '#attributes' => array('class' => array('links', 'inline')),
    );
  }

  // Allow modules to make their own additions to the comment.
  module_invoke_all('comment_view', $comment, $view_mode, $langcode);
  module_invoke_all('entity_view', $comment, 'comment', $view_mode, $langcode);

  // Make sure the current view mode is stored if no module has already
  // populated the related key.
  $comment->content += array('#view_mode' => $view_mode);
}

/**
 * Helper function, build links for an individual comment.
 *
 * Adds reply, edit, delete etc. depending on the current user permissions.
 *
 * @param $comment
 *   The comment object.
 * @param $node
 *   The node the comment is attached to.
 * @return
 *   A structured array of links.
 */
function comment_links($comment, $node) {
  $links = array();
  if ($node->comment == COMMENT_NODE_OPEN) {
    if (user_access('administer comments') && user_access('post comments')) {
      $links['comment-delete'] = array(
        'title' => t('delete'),
        'href' => "comment/$comment->cid/delete",
        'html' => TRUE,
      );
      $links['comment-edit'] = array(
        'title' => t('edit'),
        'href' => "comment/$comment->cid/edit",
        'html' => TRUE,
      );
      $links['comment-reply'] = array(
        'title' => t('reply'),
        'href' => "comment/reply/$comment->nid/$comment->cid",
        'html' => TRUE,
      );
      if ($comment->status == COMMENT_NOT_PUBLISHED) {
        $links['comment-approve'] = array(
          'title' => t('approve'),
          'href' => "comment/$comment->cid/approve",
          'html' => TRUE,
          'query' => array('token' => drupal_get_token("comment/$comment->cid/approve")),
        );
      }
    }
    elseif (user_access('post comments')) {
      if (comment_access('edit', $comment)) {
        $links['comment-edit'] = array(
          'title' => t('edit'),
          'href' => "comment/$comment->cid/edit",
          'html' => TRUE,
        );
      }
      $links['comment-reply'] = array(
        'title' => t('reply'),
        'href' => "comment/reply/$comment->nid/$comment->cid",
        'html' => TRUE,
      );
    }
    else {
      $links['comment_forbidden']['title'] = theme('comment_post_forbidden', array('node' => $node));
      $links['comment_forbidden']['html'] = TRUE;
    }
  }
  return $links;
}

/**
 * Construct a drupal_render() style array from an array of loaded comments.
 *
 * @param $comments
 *   An array of comments as returned by comment_load_multiple().
 * @param $node
 *   The node the comments are attached to.
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param $weight
 *   An integer representing the weight of the first comment in the list.
 * @param $langcode
 *   A string indicating the language field values are to be shown in. If no
 *   language is provided the current content language is used.
 *
 * @return
 *   An array in the format expected by drupal_render().
 */
function comment_view_multiple($comments, $node, $view_mode = 'full', $weight = 0, $langcode = NULL) {
  $build = array();
  $entities_by_view_mode = entity_view_mode_prepare('comment', $comments, $view_mode, $langcode);
  foreach ($entities_by_view_mode as $entity_view_mode => $entities) {
    field_attach_prepare_view('comment', $entities, $entity_view_mode, $langcode);
    entity_prepare_view('comment', $entities, $langcode);

    foreach ($entities as $entity) {
      $build[$entity->cid] = comment_view($entity, $node, $entity_view_mode, $langcode);
    }
  }

  foreach ($comments as $comment) {
    $build[$comment->cid]['#weight'] = $weight;
    $weight++;
  }
  // Sort here, to preserve the input order of the entities that were passed to
  // this function.
  uasort($build, 'element_sort');
  $build['#sorted'] = TRUE;

  return $build;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function comment_form_node_type_form_alter(&$form, $form_state) {
  if (isset($form['type'])) {
    $form['comment'] = array(
      '#type' => 'fieldset',
      '#title' => t('Comment settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
      '#attributes' => array(
        'class' => array('comment-node-type-settings-form'),
      ),
      '#attached' => array(
        'js' => array(drupal_get_path('module', 'comment') . '/comment-node-form.js'),
      ),
    );
    // Unlike coment_form_node_form_alter(), all of these settings are applied
    // as defaults to all new nodes. Therefore, it would be wrong to use #states
    // to hide the other settings based on the primary comment setting.
    $form['comment']['comment'] = array(
      '#type' => 'select',
      '#title' => t('Default comment setting for new content'),
      '#default_value' => variable_get('comment_' . $form['#node_type']->type, COMMENT_NODE_OPEN),
      '#options' => array(
        COMMENT_NODE_OPEN => t('Open'),
        COMMENT_NODE_CLOSED => t('Closed'),
        COMMENT_NODE_HIDDEN => t('Hidden'),
      ),
    );
    $form['comment']['comment_default_mode'] = array(
      '#type' => 'checkbox',
      '#title' => t('Threading'),
      '#default_value' => variable_get('comment_default_mode_' . $form['#node_type']->type, COMMENT_MODE_THREADED),
      '#description' => t('Show comment replies in a threaded list.'),
    );
    $form['comment']['comment_default_per_page'] = array(
      '#type' => 'select',
      '#title' => t('Comments per page'),
      '#default_value' => variable_get('comment_default_per_page_' . $form['#node_type']->type, 50),
      '#options' => _comment_per_page(),
    );
    $form['comment']['comment_anonymous'] = array(
      '#type' => 'select',
      '#title' => t('Anonymous commenting'),
      '#default_value' => variable_get('comment_anonymous_' . $form['#node_type']->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT),
      '#options' => array(
        COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'),
        COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'),
        COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information'),
      ),
      '#access' => user_access('post comments', drupal_anonymous_user()),
    );
    $form['comment']['comment_subject_field'] = array(
      '#type' => 'checkbox',
      '#title' => t('Allow comment title'),
      '#default_value' => variable_get('comment_subject_field_' . $form['#node_type']->type, 1),
    );
    $form['comment']['comment_form_location'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show reply form on the same page as comments'),
      '#default_value' => variable_get('comment_form_location_' . $form['#node_type']->type, COMMENT_FORM_BELOW),
    );
    $form['comment']['comment_preview'] = array(
      '#type' => 'radios',
      '#title' => t('Preview comment'),
      '#default_value' => variable_get('comment_preview_' . $form['#node_type']->type, DRUPAL_OPTIONAL),
      '#options' => array(
        DRUPAL_DISABLED => t('Disabled'),
        DRUPAL_OPTIONAL => t('Optional'),
        DRUPAL_REQUIRED => t('Required'),
      ),
    );
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function comment_form_node_form_alter(&$form, $form_state) {
  $node = $form['#node'];
  $form['comment_settings'] = array(
    '#type' => 'fieldset',
    '#access' => user_access('administer comments'),
    '#title' => t('Comment settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'additional_settings',
    '#attributes' => array(
      'class' => array('comment-node-settings-form'),
    ),
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'comment') . '/comment-node-form.js'),
     ),
    '#weight' => 30,
  );
  $comment_count = isset($node->nid) ? db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField() : 0;
  $comment_settings = ($node->comment == COMMENT_NODE_HIDDEN && empty($comment_count)) ? COMMENT_NODE_CLOSED : $node->comment;
  $form['comment_settings']['comment'] = array(
    '#type' => 'radios',
    '#title' => t('Comments'),
    '#title_display' => 'invisible',
    '#parents' => array('comment'),
    '#default_value' => $comment_settings,
    '#options' => array(
      COMMENT_NODE_OPEN => t('Open'),
      COMMENT_NODE_CLOSED => t('Closed'),
      COMMENT_NODE_HIDDEN => t('Hidden'),
    ),
    COMMENT_NODE_OPEN => array(
      '#description' => t('Users with the "Post comments" permission can post comments.'),
    ),
    COMMENT_NODE_CLOSED => array(
      '#description' => t('Users cannot post comments, but existing comments will be displayed.'),
    ),
    COMMENT_NODE_HIDDEN => array(
      '#description' => t('Comments are hidden from view.'),
    ),
  );
  // If the node doesn't have any comments, the "hidden" option makes no
  // sense, so don't even bother presenting it to the user.
  if (empty($comment_count)) {
    $form['comment_settings']['comment'][COMMENT_NODE_HIDDEN]['#access'] = FALSE;
    // Also adjust the description of the "closed" option.
    $form['comment_settings']['comment'][COMMENT_NODE_CLOSED]['#description'] = t('Users cannot post comments.');
  }
}

/**
 * Implements hook_node_load().
 */
function comment_node_load($nodes, $types) {
  $comments_enabled = array();

  // Check if comments are enabled for each node. If comments are disabled,
  // assign values without hitting the database.
  foreach ($nodes as $node) {
    // Store whether comments are enabled for this node.
    if ($node->comment != COMMENT_NODE_HIDDEN) {
      $comments_enabled[] = $node->nid;
    }
    else {
      $node->cid = 0;
      $node->last_comment_timestamp = $node->created;
      $node->last_comment_name = '';
      $node->last_comment_uid = $node->uid;
      $node->comment_count = 0;
    }
  }

  // For nodes with comments enabled, fetch information from the database.
  if (!empty($comments_enabled)) {
    $result = db_query('SELECT nid, cid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count FROM {node_comment_statistics} WHERE nid IN (:comments_enabled)', array(':comments_enabled' => $comments_enabled));
    foreach ($result as $record) {
      $nodes[$record->nid]->cid = $record->cid;
      $nodes[$record->nid]->last_comment_timestamp = $record->last_comment_timestamp;
      $nodes[$record->nid]->last_comment_name = $record->last_comment_name;
      $nodes[$record->nid]->last_comment_uid = $record->last_comment_uid;
      $nodes[$record->nid]->comment_count = $record->comment_count;
    }
  }
}

/**
 * Implements hook_node_prepare().
 */
function comment_node_prepare($node) {
  if (!isset($node->comment)) {
    $node->comment = variable_get("comment_$node->type", COMMENT_NODE_OPEN);
  }
}

/**
 * Implements hook_node_insert().
 */
function comment_node_insert($node) {
  // Allow bulk updates and inserts to temporarily disable the
  // maintenance of the {node_comment_statistics} table.
  if (variable_get('comment_maintain_node_statistics', TRUE)) {
    db_insert('node_comment_statistics')
      ->fields(array(
        'nid' => $node->nid,
        'cid' => 0,
        'last_comment_timestamp' => $node->changed,
        'last_comment_name' => NULL,
        'last_comment_uid' => $node->uid,
        'comment_count' => 0,
      ))
      ->execute();
  }
}

/**
 * Implements hook_node_delete().
 */
function comment_node_delete($node) {
  $cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchCol();
  comment_delete_multiple($cids);
  db_delete('node_comment_statistics')
    ->condition('nid', $node->nid)
    ->execute();
}

/**
 * Implements hook_node_update_index().
 */
function comment_node_update_index($node) {
  $index_comments = &drupal_static(__FUNCTION__);

  if ($index_comments === NULL) {
    // Find and save roles that can 'access comments' or 'search content'.
    $perms = array('access comments' => array(), 'search content' => array());
    $result = db_query("SELECT rid, permission FROM {role_permission} WHERE permission IN ('access comments', 'search content')");
    foreach ($result as $record) {
      $perms[$record->permission][$record->rid] = $record->rid;
    }

    // Prevent indexing of comments if there are any roles that can search but
    // not view comments.
    $index_comments = TRUE;
    foreach ($perms['search content'] as $rid) {
      if (!isset($perms['access comments'][$rid]) && ($rid <= DRUPAL_AUTHENTICATED_RID || !isset($perms['access comments'][DRUPAL_AUTHENTICATED_RID]))) {
        $index_comments = FALSE;
        break;
      }
    }
  }

  if ($index_comments) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
    if ($node->comment && $cids = comment_get_thread($node, $mode, $comments_per_page)) {
      $comments = comment_load_multiple($cids);
      comment_prepare_thread($comments);
      $build = comment_view_multiple($comments, $node);
      return drupal_render($build);
    }
  }
  return '';
}

/**
 * Implements hook_update_index().
 */
function comment_update_index() {
  // Store the maximum possible comments per thread (used for ranking by reply count)
  variable_set('node_cron_comments_scale', 1.0 / max(1, db_query('SELECT MAX(comment_count) FROM {node_comment_statistics}')->fetchField()));
}

/**
 * Implements hook_node_search_result().
 *
 * Formats a comment count string and returns it, for display with search
 * results.
 */
function comment_node_search_result($node) {
  // Do not make a string if comments are hidden.
  if (user_access('access comments') && $node->comment != COMMENT_NODE_HIDDEN) {
    $comments = db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array('nid' => $node->nid))->fetchField();
    // Do not make a string if comments are closed and there are currently
    // zero comments.
    if ($node->comment != COMMENT_NODE_CLOSED || $comments > 0) {
      return array('comment' => format_plural($comments, '1 comment', '@count comments'));
    }
  }
}

/**
 * Implements hook_user_cancel().
 */
function comment_user_cancel($edit, $account, $method) {
  switch ($method) {
    case 'user_cancel_block_unpublish':
      $comments = comment_load_multiple(array(), array('uid' => $account->uid));
      foreach ($comments as $comment) {
        $comment->status = 0;
        comment_save($comment);
      }
      break;

    case 'user_cancel_reassign':
      $comments = comment_load_multiple(array(), array('uid' => $account->uid));
      foreach ($comments as $comment) {
        $comment->uid = 0;
        comment_save($comment);
      }
      break;
  }
}

/**
 * Implements hook_user_delete().
 */
function comment_user_delete($account) {
  $cids = db_query('SELECT c.cid FROM {comment} c WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
  comment_delete_multiple($cids);
}

/**
 * Determines whether the current user has access to a particular comment.
 *
 * Authenticated users can edit their comments as long they have not been
 * replied to. This prevents people from changing or revising their statements
 * based on the replies to their posts.
 *
 * @param $op
 *   The operation that is to be performed on the comment. Only 'edit' is
 *   recognized now.
 * @param $comment
 *   The comment object.
 * @return
 *   TRUE if the current user has acces to the comment, FALSE otherwise.
 */
function comment_access($op, $comment) {
  global $user;

  if ($op == 'edit') {
    return ($user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
  }
}

/**
 * Accepts a submission of new or changed comment content.
 *
 * @param $comment
 *   A comment object.
 */
function comment_save($comment) {
  global $user;

  $transaction = db_transaction();
  try {
    $defaults = array(
      'mail' => '',
      'homepage' => '',
      'name' => '',
      'status' => user_access('skip comment approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED,
    );
    foreach ($defaults as $key => $default) {
      if (!isset($comment->$key)) {
        $comment->$key = $default;
      }
    }
    // Make sure we have a bundle name.
    if (!isset($comment->node_type)) {
      $node = node_load($comment->nid);
      $comment->node_type = 'comment_node_' . $node->type;
    }

    // Load the stored entity, if any.
    if (!empty($comment->cid) && !isset($comment->original)) {
      $comment->original = entity_load_unchanged('comment', $comment->cid);
    }

    field_attach_presave('comment', $comment);

    // Allow modules to alter the comment before saving.
    module_invoke_all('comment_presave', $comment);
    module_invoke_all('entity_presave', $comment, 'comment');

    if ($comment->cid) {

      drupal_write_record('comment', $comment, 'cid');

      // Ignore slave server temporarily to give time for the
      // saved comment to be propagated to the slave.
      db_ignore_slave();

      // Update the {node_comment_statistics} table prior to executing hooks.
      _comment_update_node_statistics($comment->nid);

      field_attach_update('comment', $comment);
      // Allow modules to respond to the updating of a comment.
      module_invoke_all('comment_update', $comment);
      module_invoke_all('entity_update', $comment, 'comment');
    }
    else {
      // Add the comment to database. This next section builds the thread field.
      // Also see the documentation for comment_view().
      if (!empty($comment->thread)) {
        // Allow calling code to set thread itself.
        $thread = $comment->thread;
      }
      elseif ($comment->pid == 0) {
        // This is a comment with no parent comment (depth 0): we start
        // by retrieving the maximum thread level.
        $max = db_query('SELECT MAX(thread) FROM {comment} WHERE nid = :nid', array(':nid' => $comment->nid))->fetchField();
        // Strip the "/" from the end of the thread.
        $max = rtrim($max, '/');
        // We need to get the value at the correct depth.
        $parts = explode('.', $max);
        $firstsegment = $parts[0];
        // Finally, build the thread field for this new comment.
        $thread = int2vancode(vancode2int($firstsegment) + 1) . '/';
      }
      else {
        // This is a comment with a parent comment, so increase the part of the
        // thread value at the proper depth.

        // Get the parent comment:
        $parent = comment_load($comment->pid);
        // Strip the "/" from the end of the parent thread.
        $parent->thread = (string) rtrim((string) $parent->thread, '/');
        // Get the max value in *this* thread.
        $max = db_query("SELECT MAX(thread) FROM {comment} WHERE thread LIKE :thread AND nid = :nid", array(
          ':thread' => $parent->thread . '.%',
          ':nid' => $comment->nid,
        ))->fetchField();

        if ($max == '') {
          // First child of this parent.
          $thread = $parent->thread . '.' . int2vancode(0) . '/';
        }
        else {
          // Strip the "/" at the end of the thread.
          $max = rtrim($max, '/');
          // Get the value at the correct depth.
          $parts = explode('.', $max);
          $parent_depth = count(explode('.', $parent->thread));
          $last = $parts[$parent_depth];
          // Finally, build the thread field for this new comment.
          $thread = $parent->thread . '.' . int2vancode(vancode2int($last) + 1) . '/';
        }
      }

      if (empty($comment->created)) {
        $comment->created = REQUEST_TIME;
      }

      if (empty($comment->changed)) {
        $comment->changed = $comment->created;
      }

      if ($comment->uid === $user->uid && isset($user->name)) { // '===' Need to modify anonymous users as well.
        $comment->name = $user->name;
      }

      // Ensure the parent id (pid) has a value set.
      if (empty($comment->pid)) {
        $comment->pid = 0;
      }

      // Add the values which aren't passed into the function.
      $comment->thread = $thread;
      $comment->hostname = ip_address();

      drupal_write_record('comment', $comment);

      // Ignore slave server temporarily to give time for the
      // created comment to be propagated to the slave.
      db_ignore_slave();

      // Update the {node_comment_statistics} table prior to executing hooks.
      _comment_update_node_statistics($comment->nid);

      field_attach_insert('comment', $comment);

      // Tell the other modules a new comment has been submitted.
      module_invoke_all('comment_insert', $comment);
      module_invoke_all('entity_insert', $comment, 'comment');
    }
    if ($comment->status == COMMENT_PUBLISHED) {
      module_invoke_all('comment_publish', $comment);
    }
    unset($comment->original);
  }
  catch (Exception $e) {
    $transaction->rollback('comment');
    watchdog_exception('comment', $e);
    throw $e;
  }

}

/**
 * Delete a comment and all its replies.
 *
 * @param $cid
 *   The comment to delete.
 */
function comment_delete($cid) {
  comment_delete_multiple(array($cid));
}

/**
 * Delete comments and all their replies.
 *
 * @param $cids
 *   The comment to delete.
 */
function comment_delete_multiple($cids) {
  $comments = comment_load_multiple($cids);
  if ($comments) {
    $transaction = db_transaction();
    try {
      // Delete the comments.
      db_delete('comment')
        ->condition('cid', array_keys($comments), 'IN')
        ->execute();
      foreach ($comments as $comment) {
        field_attach_delete('comment', $comment);
        module_invoke_all('comment_delete', $comment);
        module_invoke_all('entity_delete', $comment, 'comment');

        // Delete the comment's replies.
        $child_cids = db_query('SELECT cid FROM {comment} WHERE pid = :cid', array(':cid' => $comment->cid))->fetchCol();
        comment_delete_multiple($child_cids);
        _comment_update_node_statistics($comment->nid);
      }
    }
    catch (Exception $e) {
      $transaction->rollback();
      watchdog_exception('comment', $e);
      throw $e;
    }
  }
}

/**
 * Load comments from the database.
 *
 * @param $cids
 *   An array of comment IDs.
 * @param $conditions
 *   (deprecated) An associative array of conditions on the {comments}
 *   table, where the keys are the database fields and the values are the
 *   values those fields must have. Instead, it is preferable to use
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
 *   this function.
 * @param $reset
 *   Whether to reset the internal static entity cache. Note that the static
 *   cache is disabled in comment_entity_info() by default.
 *
 * @return
 *   An array of comment objects, indexed by comment ID.
 *
 * @see entity_load()
 * @see EntityFieldQuery
 *
 * @todo Remove $conditions in Drupal 8.
 */
function comment_load_multiple($cids = array(), $conditions = array(), $reset = FALSE) {
  return entity_load('comment', $cids, $conditions, $reset);
}

/**
 * Load the entire comment by cid.
 *
 * @param $cid
 *   The identifying comment id.
 * @param $reset
 *   Whether to reset the internal static entity cache. Note that the static
 *   cache is disabled in comment_entity_info() by default.
 *
 * @return
 *   The comment object.
 */
function comment_load($cid, $reset = FALSE) {
  $comment = comment_load_multiple(array($cid), array(), $reset);
  return $comment ? $comment[$cid] : FALSE;
}

/**
 * Controller class for comments.
 *
 * This extends the DrupalDefaultEntityController class, adding required
 * special handling for comment objects.
 */
class CommentController extends DrupalDefaultEntityController {

  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
    $query = parent::buildQuery($ids, $conditions, $revision_id);
    // Specify additional fields from the user and node tables.
    $query->innerJoin('node', 'n', 'base.nid = n.nid');
    $query->addField('n', 'type', 'node_type');
    $query->innerJoin('users', 'u', 'base.uid = u.uid');
    $query->addField('u', 'name', 'registered_name');
    $query->fields('u', array('uid', 'signature', 'signature_format', 'picture'));
    return $query;
  }

  protected function attachLoad(&$comments, $revision_id = FALSE) {
    // Setup standard comment properties.
    foreach ($comments as $key => $comment) {
      $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
      $comment->new = node_mark($comment->nid, $comment->changed);
      $comment->node_type = 'comment_node_' . $comment->node_type;
      $comments[$key] = $comment;
    }
    parent::attachLoad($comments, $revision_id);
  }
}

/**
 * Get number of new comments for current user and specified node.
 *
 * @param $nid
 *   Node-id to count comments for.
 * @param $timestamp
 *   Time to count from (defaults to time of last user access
 *   to node).
 * @return The result or FALSE on error.
 */
function comment_num_new($nid, $timestamp = 0) {
  global $user;

  if ($user->uid) {
    // Retrieve the timestamp at which the current user last viewed this node.
    if (!$timestamp) {
      $timestamp = node_last_viewed($nid);
    }
    $timestamp = ($timestamp > NODE_NEW_LIMIT ? $timestamp : NODE_NEW_LIMIT);

    // Use the timestamp to retrieve the number of new comments.
    return db_query('SELECT COUNT(cid) FROM {comment} WHERE nid = :nid AND created > :timestamp AND status = :status', array(
      ':nid' => $nid,
      ':timestamp' => $timestamp,
      ':status' => COMMENT_PUBLISHED,
      ))->fetchField();
  }
  else {
    return FALSE;
  }

}

/**
 * Get the display ordinal for a comment, starting from 0.
 *
 * Count the number of comments which appear before the comment we want to
 * display, taking into account display settings and threading.
 *
 * @param $cid
 *   The comment ID.
 * @param $node_type
 *   The node type of the comment's parent.
 * @return
 *   The display ordinal for the comment.
 * @see comment_get_display_page()
 */
function comment_get_display_ordinal($cid, $node_type) {
  // Count how many comments (c1) are before $cid (c2) in display order. This is
  // the 0-based display ordinal.
  $query = db_select('comment', 'c1');
  $query->innerJoin('comment', 'c2', 'c2.nid = c1.nid');
  $query->addExpression('COUNT(*)', 'count');
  $query->condition('c2.cid', $cid);
  if (!user_access('administer comments')) {
    $query->condition('c1.status', COMMENT_PUBLISHED);
  }
  $mode = variable_get('comment_default_mode_' . $node_type, COMMENT_MODE_THREADED);

  if ($mode == COMMENT_MODE_FLAT) {
    // For flat comments, cid is used for ordering comments due to
    // unpredicatable behavior with timestamp, so we make the same assumption
    // here.
    $query->condition('c1.cid', $cid, '<');
  }
  else {
    // For threaded comments, the c.thread column is used for ordering. We can
    // use the vancode for comparison, but must remove the trailing slash.
    // See comment_view_multiple().
    $query->where('SUBSTRING(c1.thread, 1, (LENGTH(c1.thread) -1)) < SUBSTRING(c2.thread, 1, (LENGTH(c2.thread) -1))');
  }

  return $query->execute()->fetchField();
}

/**
 * Return the page number for a comment.
 *
 * Finds the correct page number for a comment taking into account display
 * and paging settings.
 *
 * @param $cid
 *   The comment ID.
 * @param $node_type
 *   The node type the comment is attached to.
 * @return
 *   The page number.
 */
function comment_get_display_page($cid, $node_type) {
  $ordinal = comment_get_display_ordinal($cid, $node_type);
  $comments_per_page = variable_get('comment_default_per_page_' . $node_type, 50);
  return floor($ordinal / $comments_per_page);
}

/**
 * Page callback for comment editing.
 */
function comment_edit_page($comment) {
  drupal_set_title(t('Edit comment %comment', array('%comment' => $comment->subject)), PASS_THROUGH);
  $node = node_load($comment->nid);
  return drupal_get_form("comment_node_{$node->type}_form", $comment);
}

/**
 * Implements hook_forms().
 */
function comment_forms() {
  $forms = array();
  foreach (node_type_get_types() as $type) {
    $forms["comment_node_{$type->type}_form"]['callback'] = 'comment_form';
  }
  return $forms;
}

/**
 * Generate the basic commenting form, for appending to a node or display on a separate page.
 *
 * @see comment_form_validate()
 * @see comment_form_submit()
 *
 * @ingroup forms
 */
function comment_form($form, &$form_state, $comment) {
  global $user;

  // During initial form build, add the comment entity to the form state for
  // use during form building and processing. During a rebuild, use what is in
  // the form state.
  if (!isset($form_state['comment'])) {
    $defaults = array(
      'name' => '',
      'mail' => '',
      'homepage' => '',
      'subject' => '',
      'comment' => '',
      'cid' => NULL,
      'pid' => NULL,
      'language' => LANGUAGE_NONE,
      'uid' => 0,
    );
    foreach ($defaults as $key => $value) {
      if (!isset($comment->$key)) {
        $comment->$key = $value;
      }
    }
    $form_state['comment'] = $comment;
  }
  else {
    $comment = $form_state['comment'];
  }

  $node = node_load($comment->nid);
  $form['#node'] = $node;

  // Use #comment-form as unique jump target, regardless of node type.
  $form['#id'] = drupal_html_id('comment_form');
  $form['#attributes']['class'][] = 'comment-form';
  $form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');

  $anonymous_contact = variable_get('comment_anonymous_' . $node->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT);
  $is_admin = (!empty($comment->cid) && user_access('administer comments'));

  if (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
    $form['#attached']['library'][] = array('system', 'jquery.cookie');
    $form['#attributes']['class'][] = 'user-info-from-cookie';
  }

  // If not replying to a comment, use our dedicated page callback for new
  // comments on nodes.
  if (empty($comment->cid) && empty($comment->pid)) {
    $form['#action'] = url('comment/reply/' . $comment->nid);
  }

  if (isset($form_state['comment_preview'])) {
    $form += $form_state['comment_preview'];
  }

  // Display author information in a fieldset for comment moderators.
  if ($is_admin) {
    $form['author'] = array(
      '#type' => 'fieldset',
      '#title' => t('Administration'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#weight' => -2,
    );
  }
  else {
    // Sets the author form elements above the subject.
    $form['author'] = array(
      '#weight' => -2,
    );
  }

  // Prepare default values for form elements.
  if ($is_admin) {
    $author = (!$comment->uid && $comment->name ? $comment->name : $comment->registered_name);
    $status = (isset($comment->status) ? $comment->status : COMMENT_NOT_PUBLISHED);
    $date = (!empty($comment->date) ? $comment->date : format_date($comment->created, 'custom', 'Y-m-d H:i O'));
  }
  else {
    if ($user->uid) {
      $author = $user->name;
    }
    else {
      $author = ($comment->name ? $comment->name : '');
    }
    $status = (user_access('skip comment approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED);
    $date = '';
  }

  // Add the author name field depending on the current user.
  if ($is_admin) {
    $form['author']['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Authored by'),
      '#default_value' => $author,
      '#maxlength' => 60,
      '#size' => 30,
      '#description' => t('Leave blank for %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous')))),
      '#autocomplete_path' => 'user/autocomplete',
    );
  }
  elseif ($user->uid) {
    $form['author']['_author'] = array(
      '#type' => 'item',
      '#title' => t('Your name'),
      '#markup' => theme('username', array('account' => $user)),
    );
    $form['author']['name'] = array(
      '#type' => 'value',
      '#value' => $author,
    );
  }
  else {
    $form['author']['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Your name'),
      '#default_value' => $author,
      '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
      '#maxlength' => 60,
      '#size' => 30,
    );
  }

  // Add author e-mail and homepage fields depending on the current user.
  $form['author']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail'),
    '#default_value' => $comment->mail,
    '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
    '#maxlength' => 64,
    '#size' => 30,
    '#description' => t('The content of this field is kept private and will not be shown publicly.'),
    '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  );
  $form['author']['homepage'] = array(
    '#type' => 'textfield',
    '#title' => t('Homepage'),
    '#default_value' => $comment->homepage,
    '#maxlength' => 255,
    '#size' => 30,
    '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  );

  // Add administrative comment publishing options.
  $form['author']['date'] = array(
    '#type' => 'textfield',
    '#title' => t('Authored on'),
    '#default_value' => $date,
    '#maxlength' => 25,
    '#size' => 20,
    '#access' => $is_admin,
  );
  $form['author']['status'] = array(
    '#type' => 'radios',
    '#title' => t('Status'),
    '#default_value' => $status,
    '#options' => array(
      COMMENT_PUBLISHED => t('Published'),
      COMMENT_NOT_PUBLISHED => t('Not published'),
    ),
    '#access' => $is_admin,
  );

  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#maxlength' => 64,
    '#default_value' => $comment->subject,
    '#access' => variable_get('comment_subject_field_' . $node->type, 1) == 1,
    '#weight' => -1,
  );

  // Used for conditional validation of author fields.
  $form['is_anonymous'] = array(
    '#type' => 'value',
    '#value' => ($comment->cid ? !$comment->uid : !$user->uid),
  );

  // Add internal comment properties.
  foreach (array('cid', 'pid', 'nid', 'language', 'uid') as $key) {
    $form[$key] = array('#type' => 'value', '#value' => $comment->$key);
  }
  $form['node_type'] = array('#type' => 'value', '#value' => 'comment_node_' . $node->type);

  // Only show the save button if comment previews are optional or if we are
  // already previewing the submission.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#access' => ($comment->cid && user_access('administer comments')) || variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || isset($form_state['comment_preview']),
    '#weight' => 19,
  );
  $form['actions']['preview'] = array(
    '#type' => 'submit',
    '#value' => t('Preview'),
    '#access' => (variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED),
    '#weight' => 20,
    '#submit' => array('comment_form_build_preview'),
  );

  // Attach fields.
  $comment->node_type = 'comment_node_' . $node->type;
  $langcode = entity_language('comment', $comment);
  field_attach_form('comment', $comment, $form, $form_state, $langcode);

  return $form;
}

/**
 * Build a preview from submitted form values.
 */
function comment_form_build_preview($form, &$form_state) {
  $comment = comment_form_submit_build_comment($form, $form_state);
  $form_state['comment_preview'] = comment_preview($comment);
  $form_state['rebuild'] = TRUE;
}

/**
 * Generate a comment preview.
 */
function comment_preview($comment) {
  global $user;

  drupal_set_title(t('Preview comment'), PASS_THROUGH);

  $node = node_load($comment->nid);

  if (!form_get_errors()) {
    $comment_body = field_get_items('comment', $comment, 'comment_body');
    $comment->format = $comment_body[0]['format'];
    // Attach the user and time information.
    if (!empty($comment->name)) {
      $account = user_load_by_name($comment->name);
    }
    elseif ($user->uid && empty($comment->is_anonymous)) {
      $account = $user;
    }

    if (!empty($account->uid)) {
      $comment->uid = $account->uid;
      $comment->name = check_plain($account->name);
      $comment->signature = $account->signature;
      $comment->signature_format = $account->signature_format;
      $comment->picture = $account->picture;
    }
    elseif (empty($comment->name)) {
      $comment->name = variable_get('anonymous', t('Anonymous'));
    }

    $comment->created = !empty($comment->created) ? $comment->created : REQUEST_TIME;
    $comment->changed = REQUEST_TIME;
    $comment->in_preview = TRUE;
    $comment_build = comment_view($comment, $node);
    $comment_build['#weight'] = -100;

    $form['comment_preview'] = $comment_build;
  }

  if ($comment->pid) {
    $build = array();
    if ($comments = comment_load_multiple(array($comment->pid), array('status' => COMMENT_PUBLISHED))) {
      $parent_comment = $comments[$comment->pid];
      $build = comment_view($parent_comment, $node);
    }
  }
  else {
    $build = node_view($node);
  }

  $form['comment_output_below'] = $build;
  $form['comment_output_below']['#weight'] = 100;

  return $form;
}

/**
 * Validate comment form submissions.
 */
function comment_form_validate($form, &$form_state) {
  global $user;

  entity_form_field_validate('comment', $form, $form_state);

  if (!empty($form_state['values']['cid'])) {
    // Verify the name in case it is being changed from being anonymous.
    $account = user_load_by_name($form_state['values']['name']);
    $form_state['values']['uid'] = $account ? $account->uid : 0;

    if ($form_state['values']['date'] && strtotime($form_state['values']['date']) === FALSE) {
      form_set_error('date', t('You have to specify a valid date.'));
    }
    if ($form_state['values']['name'] && !$form_state['values']['is_anonymous'] && !$account) {
      form_set_error('name', t('You have to specify a valid author.'));
    }
  }
  elseif ($form_state['values']['is_anonymous']) {
    // Validate anonymous comment author fields (if given). If the (original)
    // author of this comment was an anonymous user, verify that no registered
    // user with this name exists.
    if ($form_state['values']['name']) {
      $query = db_select('users', 'u');
      $query->addField('u', 'uid', 'uid');
      $taken = $query
        ->condition('name', db_like($form_state['values']['name']), 'LIKE')
        ->countQuery()
        ->execute()
        ->fetchField();
      if ($taken) {
        form_set_error('name', t('The name you used belongs to a registered user.'));
      }
    }
  }
  if ($form_state['values']['mail'] && !valid_email_address($form_state['values']['mail'])) {
    form_set_error('mail', t('The e-mail address you specified is not valid.'));
  }
  if ($form_state['values']['homepage'] && !valid_url($form_state['values']['homepage'], TRUE)) {
    form_set_error('homepage', t('The URL of your homepage is not valid. Remember that it must be fully qualified, i.e. of the form <code>http://example.com/directory</code>.'));
  }
}

/**
 * Prepare a comment for submission.
 */
function comment_submit($comment) {
  // @todo Legacy support. Remove in Drupal 8.
  if (is_array($comment)) {
    $comment += array('subject' => '');
    $comment = (object) $comment;
  }

  if (empty($comment->date)) {
    $comment->date = 'now';
  }
  $comment->created = strtotime($comment->date);
  $comment->changed = REQUEST_TIME;

  // If the comment was posted by a registered user, assign the author's ID.
  // @todo Too fragile. Should be prepared and stored in comment_form() already.
  if (!$comment->is_anonymous && !empty($comment->name) && ($account = user_load_by_name($comment->name))) {
    $comment->uid = $account->uid;
  }
  // If the comment was posted by an anonymous user and no author name was
  // required, use "Anonymous" by default.
  if ($comment->is_anonymous && (!isset($comment->name) || $comment->name === '')) {
    $comment->name = variable_get('anonymous', t('Anonymous'));
  }

  // Validate the comment's subject. If not specified, extract from comment body.
  if (trim($comment->subject) == '') {
    // The body may be in any format, so:
    // 1) Filter it into HTML
    // 2) Strip out all HTML tags
    // 3) Convert entities back to plain-text.
    $field = field_info_field('comment_body');
    $langcode = field_is_translatable('comment', $field) ? entity_language('comment', $comment) : LANGUAGE_NONE;
    $comment_body = $comment->comment_body[$langcode][0];
    if (isset($comment_body['format'])) {
      $comment_text = check_markup($comment_body['value'], $comment_body['format']);
    }
    else {
      $comment_text = check_plain($comment_body['value']);
    }
    $comment->subject = truncate_utf8(trim(decode_entities(strip_tags($comment_text))), 29, TRUE);
    // Edge cases where the comment body is populated only by HTML tags will
    // require a default subject.
    if ($comment->subject == '') {
      $comment->subject = t('(No subject)');
    }
  }
  return $comment;
}

/**
 * Updates the form state's comment entity by processing this submission's values.
 *
 * This is the default builder function for the comment form. It is called
 * during the "Save" and "Preview" submit handlers to retrieve the entity to
 * save or preview. This function can also be called by a "Next" button of a
 * wizard to update the form state's entity with the current step's values
 * before proceeding to the next step.
 *
 * @see comment_form()
 */
function comment_form_submit_build_comment($form, &$form_state) {
  $comment = $form_state['comment'];
  entity_form_submit_build_entity('comment', $comment, $form, $form_state);
  comment_submit($comment);
  return $comment;
}

/**
 * Process comment form submissions; prepare the comment, store it, and set a redirection target.
 */
function comment_form_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $comment = comment_form_submit_build_comment($form, $form_state);
  if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
    // Save the anonymous user information to a cookie for reuse.
    if (user_is_anonymous()) {
      user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
    }

    comment_save($comment);
    $form_state['values']['cid'] = $comment->cid;

    // Add an entry to the watchdog log.
    watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)));

    // Explain the approval queue if necessary.
    if ($comment->status == COMMENT_NOT_PUBLISHED) {
      if (!user_access('administer comments')) {
        drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
      }
    }
    else {
      drupal_set_message(t('Your comment has been posted.'));
    }
    $query = array();
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    if ($page > 0) {
      $query['page'] = $page;
    }
    // Redirect to the newly posted comment.
    $redirect = array('node/' . $node->nid, array('query' => $query, 'fragment' => 'comment-' . $comment->cid));
  }
  else {
    watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject), WATCHDOG_WARNING);
    drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject)), 'error');
    // Redirect the user to the node they are commenting on.
    $redirect = 'node/' . $node->nid;
  }
  $form_state['redirect'] = $redirect;
  // Clear the block and page caches so that anonymous users see the comment
  // they have posted.
  cache_clear_all();
}

/**
 * Process variables for comment.tpl.php.
 *
 * @see comment.tpl.php
 */
function template_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $node = $variables['elements']['#node'];
  $variables['comment']   = $comment;
  $variables['node']      = $node;
  $variables['author']    = theme('username', array('account' => $comment));

  $variables['created']   = format_date($comment->created);

  // Avoid calling format_date() twice on the same timestamp.
  if ($comment->changed == $comment->created) {
    $variables['changed'] = $variables['created'];
  }
  else {
    $variables['changed'] = format_date($comment->changed);
  }

  $variables['new']       = !empty($comment->new) ? t('new') : '';
  $variables['picture']   = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $comment)) : '';
  $variables['signature'] = $comment->signature;

  $uri = entity_uri('comment', $comment);
  $uri['options'] += array('attributes' => array('class' => array('permalink'), 'rel' => 'bookmark'));

  $variables['title']     = l($comment->subject, $uri['path'], $uri['options']);
  $variables['permalink'] = l(t('Permalink'), $uri['path'], $uri['options']);
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['author'], '!datetime' => $variables['created']));

  // Preprocess fields.
  field_attach_preprocess('comment', $comment, $variables['elements'], $variables);

  // Helpful $content variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  // Set status to a string representation of comment->status.
  if (isset($comment->in_preview)) {
    $variables['status'] = 'comment-preview';
  }
  else {
    $variables['status'] = ($comment->status == COMMENT_NOT_PUBLISHED) ? 'comment-unpublished' : 'comment-published';
  }

  // Gather comment classes.
  // 'comment-published' class is not needed, it is either 'comment-preview' or
  // 'comment-unpublished'.
  if ($variables['status'] != 'comment-published') {
    $variables['classes_array'][] = $variables['status'];
  }
  if ($variables['new']) {
    $variables['classes_array'][] = 'comment-new';
  }
  if (!$comment->uid) {
    $variables['classes_array'][] = 'comment-by-anonymous';
  }
  else {
    if ($comment->uid == $variables['node']->uid) {
      $variables['classes_array'][] = 'comment-by-node-author';
    }
    if ($comment->uid == $variables['user']->uid) {
      $variables['classes_array'][] = 'comment-by-viewer';
    }
  }
}

/**
 * Returns HTML for a "you can't post comments" notice.
 *
 * @param $variables
 *   An associative array containing:
 *   - node: The comment node.
 *
 * @ingroup themeable
 */
function theme_comment_post_forbidden($variables) {
  $node = $variables['node'];
  global $user;

  // Since this is expensive to compute, we cache it so that a page with many
  // comments only has to query the database once for all the links.
  $authenticated_post_comments = &drupal_static(__FUNCTION__, NULL);

  if (!$user->uid) {
    if (!isset($authenticated_post_comments)) {
      // We only output a link if we are certain that users will get permission
      // to post comments by logging in.
      $comment_roles = user_roles(TRUE, 'post comments');
      $authenticated_post_comments = isset($comment_roles[DRUPAL_AUTHENTICATED_RID]);
    }

    if ($authenticated_post_comments) {
      // We cannot use drupal_get_destination() because these links
      // sometimes appear on /node and taxonomy listing pages.
      if (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW) == COMMENT_FORM_SEPARATE_PAGE) {
        $destination = array('destination' => "comment/reply/$node->nid#comment-form");
      }
      else {
        $destination = array('destination' => "node/$node->nid#comment-form");
      }

      if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
        // Users can register themselves.
        return t('<a href="@login">Log in</a> or <a href="@register">register</a> to post comments', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination))));
      }
      else {
        // Only admins can add new users, no public registration.
        return t('<a href="@login">Log in</a> to post comments', array('@login' => url('user/login', array('query' => $destination))));
      }
    }
  }
}

/**
 * Process variables for comment-wrapper.tpl.php.
 *
 * @see comment-wrapper.tpl.php
 */
function template_preprocess_comment_wrapper(&$variables) {
  // Provide contextual information.
  $variables['node'] = $variables['content']['#node'];
  $variables['display_mode'] = variable_get('comment_default_mode_' . $variables['node']->type, COMMENT_MODE_THREADED);
  // The comment form is optional and may not exist.
  $variables['content'] += array('comment_form' => array());
}

/**
 * Return an array of viewing modes for comment listings.
 *
 * We can't use a global variable array because the locale system
 * is not initialized yet when the comment module is loaded.
 */
function _comment_get_modes() {
  return array(
    COMMENT_MODE_FLAT => t('Flat list'),
    COMMENT_MODE_THREADED => t('Threaded list')
  );
}

/**
 * Return an array of "comments per page" settings from which the user
 * can choose.
 */
function _comment_per_page() {
  return drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300));
}

/**
 * Updates the comment statistics for a given node. This should be called any
 * time a comment is added, deleted, or updated.
 *
 * The following fields are contained in the node_comment_statistics table.
 * - last_comment_timestamp: the timestamp of the last comment for this node or the node create stamp if no comments exist for the node.
 * - last_comment_name: the name of the anonymous poster for the last comment
 * - last_comment_uid: the uid of the poster for the last comment for this node or the node authors uid if no comments exists for the node.
 * - comment_count: the total number of approved/published comments on this node.
 */
function _comment_update_node_statistics($nid) {
  // Allow bulk updates and inserts to temporarily disable the
  // maintenance of the {node_comment_statistics} table.
  if (!variable_get('comment_maintain_node_statistics', TRUE)) {
    return;
  }

  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE nid = :nid AND status = :status', array(
    ':nid' => $nid,
    ':status' => COMMENT_PUBLISHED,
  ))->fetchField();

  if ($count > 0) {
    // Comments exist.
    $last_reply = db_query_range('SELECT cid, name, changed, uid FROM {comment} WHERE nid = :nid AND status = :status ORDER BY cid DESC', 0, 1, array(
      ':nid' => $nid,
      ':status' => COMMENT_PUBLISHED,
    ))->fetchObject();
    db_update('node_comment_statistics')
      ->fields(array(
        'cid' => $last_reply->cid,
        'comment_count' => $count,
        'last_comment_timestamp' => $last_reply->changed,
        'last_comment_name' => $last_reply->uid ? '' : $last_reply->name,
        'last_comment_uid' => $last_reply->uid,
      ))
      ->condition('nid', $nid)
      ->execute();
  }
  else {
    // Comments do not exist.
    $node = db_query('SELECT uid, created FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();
    db_update('node_comment_statistics')
      ->fields(array(
        'cid' => 0,
        'comment_count' => 0,
        'last_comment_timestamp' => $node->created,
        'last_comment_name' => '',
        'last_comment_uid' => $node->uid,
      ))
      ->condition('nid', $nid)
      ->execute();
  }
}

/**
 * Generate vancode.
 *
 * Consists of a leading character indicating length, followed by N digits
 * with a numerical value in base 36. Vancodes can be sorted as strings
 * without messing up numerical order.
 *
 * It goes:
 * 00, 01, 02, ..., 0y, 0z,
 * 110, 111, ... , 1zy, 1zz,
 * 2100, 2101, ..., 2zzy, 2zzz,
 * 31000, 31001, ...
 */
function int2vancode($i = 0) {
  $num = base_convert((int) $i, 10, 36);
  $length = strlen($num);

  return chr($length + ord('0') - 1) . $num;
}

/**
 * Decode vancode back to an integer.
 */
function vancode2int($c = '00') {
  return base_convert(substr($c, 1), 36, 10);
}

/**
 * Implements hook_action_info().
 */
function comment_action_info() {
  return array(
    'comment_publish_action' => array(
      'label' => t('Publish comment'),
      'type' => 'comment',
      'configurable' => FALSE,
      'behavior' => array('changes_property'),
      'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
    ),
    'comment_unpublish_action' => array(
      'label' => t('Unpublish comment'),
      'type' => 'comment',
      'configurable' => FALSE,
      'behavior' => array('changes_property'),
      'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
    ),
    'comment_unpublish_by_keyword_action' => array(
      'label' => t('Unpublish comment containing keyword(s)'),
      'type' => 'comment',
      'configurable' => TRUE,
      'behavior' => array('changes_property'),
      'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
    ),
    'comment_save_action' => array(
      'label' => t('Save comment'),
      'type' => 'comment',
      'configurable' => FALSE,
      'triggers' => array('comment_insert', 'comment_update'),
    ),
  );
}

/**
 * Publishes a comment.
 *
 * @param $comment
 *   An optional comment object.
 * @param array $context
 *   Array with components:
 *   - 'cid': Comment ID. Required if $comment is not given.
 *
 * @ingroup actions
 */
function comment_publish_action($comment, $context = array()) {
  if (isset($comment->subject)) {
    $subject = $comment->subject;
    $comment->status = COMMENT_PUBLISHED;
  }
  else {
    $cid = $context['cid'];
    $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(':cid' => $cid))->fetchField();
    db_update('comment')
      ->fields(array('status' => COMMENT_PUBLISHED))
      ->condition('cid', $cid)
      ->execute();
  }
  watchdog('action', 'Published comment %subject.', array('%subject' => $subject));
}

/**
 * Unpublishes a comment.
 *
 * @param $comment
 *   An optional comment object.
 * @param array $context
 *   Array with components:
 *   - 'cid': Comment ID. Required if $comment is not given.
 *
 * @ingroup actions
 */
function comment_unpublish_action($comment, $context = array()) {
  if (isset($comment->subject)) {
    $subject = $comment->subject;
    $comment->status = COMMENT_NOT_PUBLISHED;
  }
  else {
    $cid = $context['cid'];
    $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(':cid' => $cid))->fetchField();
    db_update('comment')
      ->fields(array('status' => COMMENT_NOT_PUBLISHED))
      ->condition('cid', $cid)
      ->execute();
  }
  watchdog('action', 'Unpublished comment %subject.', array('%subject' => $subject));
}

/**
 * Unpublishes a comment if it contains certain keywords.
 *
 * @param object $comment
 *   Comment object to modify.
 * @param array $context
 *   Array with components:
 *   - 'keywords': Keywords to look for. If the comment contains at least one
 *     of the keywords, it is unpublished.
 *
 * @ingroup actions
 * @see comment_unpublish_by_keyword_action_form()
 * @see comment_unpublish_by_keyword_action_submit()
 */
function comment_unpublish_by_keyword_action($comment, $context) {
  $node = node_load($comment->nid);
  $build = comment_view($comment, $node);
  $text = drupal_render($build);
  foreach ($context['keywords'] as $keyword) {
    if (strpos($text, $keyword) !== FALSE) {
      $comment->status = COMMENT_NOT_PUBLISHED;
      comment_save($comment);
      watchdog('action', 'Unpublished comment %subject.', array('%subject' => $comment->subject));
      break;
    }
  }
}

/**
 * Form builder; Prepare a form for blacklisted keywords.
 *
 * @ingroup forms
 * @see comment_unpublish_by_keyword_action()
 * @see comment_unpublish_by_keyword_action_submit()
 */
function comment_unpublish_by_keyword_action_form($context) {
  $form['keywords'] = array(
    '#title' => t('Keywords'),
    '#type' => 'textarea',
    '#description' => t('The comment will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
    '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  );

  return $form;
}

/**
 * Process comment_unpublish_by_keyword_action_form form submissions.
 *
 * @see comment_unpublish_by_keyword_action()
 */
function comment_unpublish_by_keyword_action_submit($form, $form_state) {
  return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
}

/**
 * Saves a comment.
 *
 * @ingroup actions
 */
function comment_save_action($comment) {
  comment_save($comment);
  cache_clear_all();
  watchdog('action', 'Saved comment %title', array('%title' => $comment->subject));
}

/**
 * Implements hook_ranking().
 */
function comment_ranking() {
  return array(
    'comments' => array(
      'title' => t('Number of comments'),
      'join' => array(
        'type' => 'LEFT',
        'table' => 'node_comment_statistics',
        'alias' => 'node_comment_statistics',
        'on' => 'node_comment_statistics.nid = i.sid',
      ),
      // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
      'score' => '2.0 - 2.0 / (1.0 + node_comment_statistics.comment_count * CAST(:scale AS DECIMAL))',
      'arguments' => array(':scale' => variable_get('node_cron_comments_scale', 0)),
    ),
  );
}

/**
 * Implements hook_rdf_mapping().
 */
function comment_rdf_mapping() {
  return array(
    array(
      'type' => 'comment',
      'bundle' => RDF_DEFAULT_BUNDLE,
      'mapping' => array(
        'rdftype' => array('sioc:Post', 'sioct:Comment'),
        'title' => array(
          'predicates' => array('dc:title'),
        ),
        'created' => array(
          'predicates' => array('dc:date', 'dc:created'),
          'datatype' => 'xsd:dateTime',
          'callback' => 'date_iso8601',
        ),
        'changed' => array(
          'predicates' => array('dc:modified'),
          'datatype' => 'xsd:dateTime',
          'callback' => 'date_iso8601',
        ),
        'comment_body' => array(
          'predicates' => array('content:encoded'),
        ),
        'pid' => array(
          'predicates' => array('sioc:reply_of'),
          'type' => 'rel',
        ),
        'uid' => array(
          'predicates' => array('sioc:has_creator'),
          'type' => 'rel',
        ),
        'name' => array(
          'predicates' => array('foaf:name'),
        ),
      ),
    ),
  );
}

/**
 * Implements hook_file_download_access().
 */
function comment_file_download_access($field, $entity_type, $entity) {
  if ($entity_type == 'comment') {
    if (user_access('access comments') && $entity->status == COMMENT_PUBLISHED || user_access('administer comments')) {
      $node = node_load($entity->nid);
      return node_access('view', $node);
    }
    return FALSE;
  }
}