summaryrefslogtreecommitdiff
path: root/modules/node/node.module
blob: db7871d4942a27950a5b96357c3ad2f9e73bbc3a (plain)
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
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
<?php
// $Id$

/**
 * @file
 * The core that allows content to be submitted to the site. Modules and
 * scripts may programmatically submit nodes using the usual form API pattern.
 */

/**
 * Nodes changed before this time are always marked as read.
 *
 * Nodes changed after this time may be marked new, updated, or read, depending
 * on their state for the current user. Defaults to 30 days ago.
 */
define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);

/**
 * Node is being built before being viewed normally.
 */
define('NODE_BUILD_NORMAL', 0);

/**
 * Node is being built before being previewed.
 */
define('NODE_BUILD_PREVIEW', 1);

/**
 * Node is being built before being indexed by search module.
 */
define('NODE_BUILD_SEARCH_INDEX', 2);

/**
 * Node is being built before being displayed as a search result.
 */
define('NODE_BUILD_SEARCH_RESULT', 3);

/**
 * Node is being built before being displayed as part of an RSS feed.
 */
define('NODE_BUILD_RSS', 4);

/**
 * Node is being built before being printed.
 */
define('NODE_BUILD_PRINT', 5);

/**
 * Implementation of hook_help().
 */
function node_help($path, $arg) {
  // Remind site administrators about the {node_access} table being flagged
  // for rebuild. We don't need to issue the message on the confirm form, or
  // while the rebuild is being processed.
  if ($path != 'admin/content/node-settings/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
      && user_access('access administration pages') && node_access_needs_rebuild()) {
    if ($path == 'admin/content/node-settings') {
      $message = t('The content access permissions need to be rebuilt.');
    }
    else {
      $message = t('The content access permissions need to be rebuilt. Please visit <a href="@node_access_rebuild">this page</a>.', array('@node_access_rebuild' => url('admin/content/node-settings/rebuild')));
    }
    drupal_set_message($message, 'error');
  }

  switch ($path) {
    case 'admin/help#node':
      $output = '<p>' . t('The node module manages content on your site, and stores all posts (regardless of type) as a "node" . In addition to basic publishing settings, including whether the post has been published, promoted to the site front page, or should remain present (or sticky) at the top of lists, the node module also records basic information about the author of a post. Optional revision control over edits is available. For additional functionality, the node module is often extended by other modules.') . '</p>';
      $output .= '<p>' . t('Though each post on your site is a node, each post is also of a particular <a href="@content-type">content type</a>. <a href="@content-type">Content types</a> are used to define the characteristics of a post, including the title and description of the fields displayed on its add and edit pages. Each content type may have different default settings for <em>Publishing options</em> and other workflow controls. By default, the two content types in a standard Drupal installation are <em>Page</em> and <em>Story</em>. Use the <a href="@content-type">content types page</a> to add new or edit existing content types. Additional content types also become available as you enable additional core, contributed and custom modules.', array('@content-type' => url('admin/build/types'))) . '</p>';
      $output .= '<p>' . t('The administrative <a href="@content">content page</a> allows you to review and manage your site content. The <a href="@post-settings">post settings page</a> sets certain options for the display of posts. The node module makes a number of permissions available for each content type, which may be set by role on the <a href="@permissions">permissions page</a>.', array('@content' => url('admin/content/node'), '@post-settings' => url('admin/content/node-settings'), '@permissions' => url('admin/user/permissions'))) . '</p>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@node">Node module</a>.', array('@node' => 'http://drupal.org/handbook/modules/node/')) . '</p>';
      return $output;
    case 'admin/content/node':
      return ' '; // Return a non-null value so that the 'more help' link is shown.
    case 'admin/build/types':
      return '<p>' . t('Below is a list of all the content types on your site. All posts that exist on your site are instances of one of these content types.') . '</p>';
    case 'admin/build/types/add':
      return '<p>' . t('To create a new content type, enter the human-readable name, the machine-readable name, and all other relevant fields that are on this page. Once created, users of your site will be able to create posts that are instances of this content type.') . '</p>';
    case 'node/%/revisions':
      return '<p>' . t('The revisions let you track differences between multiple versions of a post.') . '</p>';
    case 'node/%/edit':
      $node = node_load($arg[1]);
      $type = node_get_types('type', $node->type);
      return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
  }

  if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
    $type = node_get_types('type', str_replace('-', '_', $arg[2]));
    return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
  }
}

/**
 * Implementation of hook_theme().
 */
function node_theme() {
  return array(
    'node' => array(
      'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
      'template' => 'node',
    ),
    'node_list' => array(
      'arguments' => array('items' => NULL, 'title' => NULL),
    ),
    'node_search_admin' => array(
      'arguments' => array('form' => NULL),
    ),
    'node_filter_form' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.admin.inc',
    ),
    'node_filters' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.admin.inc',
    ),
    'node_admin_nodes' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.admin.inc',
    ),
    'node_add_list' => array(
      'arguments' => array('content' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_form' => array(
      'arguments' => array('form' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_preview' => array(
      'arguments' => array('node' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_log_message' => array(
      'arguments' => array('log' => NULL),
    ),
    'node_submitted' => array(
      'arguments' => array('node' => NULL),
    ),
    'node_admin_overview' => array(
      'arguments' => array('name' => NULL, 'type' => NULL),
    ),
    'node_links' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

/**
 * Implementation of hook_cron().
 */
function node_cron() {
  db_query('DELETE FROM {history} WHERE timestamp < %d', NODE_NEW_LIMIT);
}

/**
 * Gather a listing of links to nodes.
 *
 * @param $result
 *   A DB result object from a query to fetch node objects. If your query
 *   joins the <code>node_comment_statistics</code> table so that the
 *   <code>comment_count</code> field is available, a title attribute will
 *   be added to show the number of comments.
 * @param $title
 *   A heading for the resulting list.
 *
 * @return
 *   An HTML list suitable as content for a block, or FALSE if no result can
 *   fetch from DB result object.
 */
function node_title_list($result, $title = NULL) {
  $items = array();
  $num_rows = FALSE;
  while ($node = db_fetch_object($result)) {
    $items[] = l($node->title, 'node/' . $node->nid, !empty($node->comment_count) ? array('attributes' => array('title' => format_plural($node->comment_count, '1 comment', '@count comments'))) : array());
    $num_rows = TRUE;
  }

  return $num_rows ? theme('node_list', $items, $title) : FALSE;
}

/**
 * Format a listing of links to nodes.
 *
 * @ingroup themeable
 */
function theme_node_list($items, $title = NULL) {
  return theme('item_list', $items, $title);
}

/**
 * Update the 'last viewed' timestamp of the specified node for current user.
 */
function node_tag_new($nid) {
  global $user;

  if ($user->uid) {
    if (node_last_viewed($nid)) {
      db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', REQUEST_TIME, $user->uid, $nid);
    }
    else {
      @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, REQUEST_TIME);
    }
  }
}

/**
 * Retrieves the timestamp at which the current user last viewed the
 * specified node.
 */
function node_last_viewed($nid) {
  global $user;
  static $history;

  if (!isset($history[$nid])) {
    $history[$nid] = db_fetch_object(db_query("SELECT timestamp FROM {history} WHERE uid = %d AND nid = %d", $user->uid, $nid));
  }

  return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
}

/**
 * Decide on the type of marker to be displayed for a given node.
 *
 * @param $nid
 *   Node ID whose history supplies the "last viewed" timestamp.
 * @param $timestamp
 *   Time which is compared against node's "last viewed" timestamp.
 * @return
 *   One of the MARK constants.
 */
function node_mark($nid, $timestamp) {
  global $user;
  static $cache;

  if (!$user->uid) {
    return MARK_READ;
  }
  if (!isset($cache[$nid])) {
    $cache[$nid] = node_last_viewed($nid);
  }
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;
}

/**
 * See if the user used JS to submit a teaser.
 */
function node_teaser_js(&$form, &$form_state) {
  if (isset($form['#post']['teaser_js'])) {
    // Glue the teaser to the body.
    if (trim($form_state['values']['teaser_js'])) {
      // Space the teaser from the body
      $body = trim($form_state['values']['teaser_js']) . "\r\n<!--break-->\r\n" . trim($form_state['values']['body']);
    }
    else {
      // Empty teaser, no spaces.
      $body = '<!--break-->' . $form_state['values']['body'];
    }
    // Pass updated body value on to preview/submit form processing.
    form_set_value($form['body'], $body, $form_state);
    // Pass updated body value back onto form for those cases
    // in which the form is redisplayed.
    $form['body']['#value'] = $body;
  }
  return $form;
}

/**
 * Ensure value of "teaser_include" checkbox is consistent with other form data.
 *
 * This handles two situations in which an unchecked checkbox is rejected:
 *
 *   1. The user defines a teaser (summary) but it is empty;
 *   2. The user does not define a teaser (summary) (in this case an
 *      unchecked checkbox would cause the body to be empty, or missing
 *      the auto-generated teaser).
 *
 * If JavaScript is active then it is used to force the checkbox to be
 * checked when hidden, and so the second case will not arise.
 *
 * In either case a warning message is output.
 */
function node_teaser_include_verify(&$form, &$form_state) {
  $message = '';

  // $form['#post'] is set only when the form is built for preview/submit.
  if (isset($form['#post']['body']) && isset($form_state['values']['teaser_include']) && !$form_state['values']['teaser_include']) {
    // "teaser_include" checkbox is present and unchecked.
    if (strpos($form_state['values']['body'], '<!--break-->') === 0) {
      // Teaser is empty string.
      $message = t('You specified that the summary should not be shown when this post is displayed in full view. This setting is ignored when the summary is empty.');
    }
    elseif (strpos($form_state['values']['body'], '<!--break-->') === FALSE) {
      // Teaser delimiter is not present in the body.
      $message = t('You specified that the summary should not be shown when this post is displayed in full view. This setting has been ignored since you have not defined a summary for the post. (To define a summary, insert the delimiter "&lt;!--break--&gt;" (without the quotes) in the Body of the post to indicate the end of the summary and the start of the main content.)');
    }

    if (!empty($message)) {
      drupal_set_message($message, 'warning');
      // Pass new checkbox value on to preview/submit form processing.
      form_set_value($form['teaser_include'], 1, $form_state);
      // Pass new checkbox value back onto form for those cases
      // in which form is redisplayed.
      $form['teaser_include']['#value'] = 1;
    }
  }

  return $form;
}

/**
 * Generate a teaser for a node body.
 *
 * If the end of the teaser is not indicated using the <!--break--> delimiter
 * then we generate the teaser automatically, trying to end it at a sensible
 * place such as the end of a paragraph, a line break, or the end of a
 * sentence (in that order of preference).
 *
 * @param $body
 *   The content for which a teaser will be generated.
 * @param $format
 *   The format of the content. If the content contains PHP code, we do not
 *   split it up to prevent parse errors. If the line break filter is present
 *   then we treat newlines embedded in $body as line breaks.
 * @param $size
 *   The desired character length of the teaser. If omitted, the default
 *   value will be used. Ignored if the special delimiter is present
 *   in $body.
 * @return
 *   The generated teaser.
 */
function node_teaser($body, $format = NULL, $size = NULL) {

  if (!isset($size)) {
    $size = variable_get('teaser_length', 600);
  }

  // Find where the delimiter is in the body
  $delimiter = strpos($body, '<!--break-->');

  // If the size is zero, and there is no delimiter, the entire body is the teaser.
  if ($size == 0 && $delimiter === FALSE) {
    return $body;
  }

  // If a valid delimiter has been specified, use it to chop off the teaser.
  if ($delimiter !== FALSE) {
    return substr($body, 0, $delimiter);
  }

  // We check for the presence of the PHP evaluator filter in the current
  // format. If the body contains PHP code, we do not split it up to prevent
  // parse errors.
  if (isset($format)) {
    $filters = filter_list_format($format);
    if (isset($filters['php/0']) && strpos($body, '<?') !== FALSE) {
      return $body;
    }
  }

  // If we have a short body, the entire body is the teaser.
  if (drupal_strlen($body) <= $size) {
    return $body;
  }

  // If the delimiter has not been specified, try to split at paragraph or
  // sentence boundaries.

  // The teaser may not be longer than maximum length specified. Initial slice.
  $teaser = truncate_utf8($body, $size);

  // Store the actual length of the UTF8 string -- which might not be the same
  // as $size.
  $max_rpos = strlen($teaser);

  // How much to cut off the end of the teaser so that it doesn't end in the
  // middle of a paragraph, sentence, or word.
  // Initialize it to maximum in order to find the minimum.
  $min_rpos = $max_rpos;

  // Store the reverse of the teaser. We use strpos on the reversed needle and
  // haystack for speed and convenience.
  $reversed = strrev($teaser);

  // Build an array of arrays of break points grouped by preference.
  $break_points = array();

  // A paragraph near the end of sliced teaser is most preferable.
  $break_points[] = array('</p>' => 0);

  // If no complete paragraph then treat line breaks as paragraphs.
  $line_breaks = array('<br />' => 6, '<br>' => 4);
  // Newline only indicates a line break if line break converter
  // filter is present.
  if (isset($filters['filter/1'])) {
    $line_breaks["\n"] = 1;
  }
  $break_points[] = $line_breaks;

  // If the first paragraph is too long, split at the end of a sentence.
  $break_points[] = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);

  // Iterate over the groups of break points until a break point is found.
  foreach ($break_points as $points) {
    // Look for each break point, starting at the end of the teaser.
    foreach ($points as $point => $offset) {
      // The teaser is already reversed, but the break point isn't.
      $rpos = strpos($reversed, strrev($point));
      if ($rpos !== FALSE) {
        $min_rpos = min($rpos + $offset, $min_rpos);
      }
    }

    // If a break point was found in this group, slice and return the teaser.
    if ($min_rpos !== $max_rpos) {
      // Don't slice with length 0. Length must be <0 to slice from RHS.
      return ($min_rpos === 0) ? $teaser : substr($teaser, 0, 0 - $min_rpos);
    }
  }

  // If a break point was not found, still return a teaser.
  return $teaser;
}

/**
 * Builds a list of available node types, and returns all of part of this list
 * in the specified format.
 *
 * @param $op
 *   The format in which to return the list. When this is set to 'type',
 *   'base', or 'name', only the specified node type is returned. When set to
 *   'types' or 'names', all node types are returned.
 * @param $node
 *   A node object, array, or string that indicates the node type to return.
 *   Leave at default value (NULL) to return a list of all node types.
 * @param $reset
 *   Whether or not to reset this function's internal cache (defaults to
 *   FALSE).
 *
 * @return
 *   Either an array of all available node types, or a single node type, in a
 *   variable format. Returns FALSE if the node type is not found.
 */
function node_get_types($op = 'types', $node = NULL, $reset = FALSE) {
  static $_node_types, $_node_names;

  if ($reset || !isset($_node_types)) {
    list($_node_types, $_node_names) = _node_types_build();
  }

  if ($node) {
    if (is_array($node)) {
      $type = $node['type'];
    }
    elseif (is_object($node)) {
      $type = $node->type;
    }
    elseif (is_string($node)) {
      $type = $node;
    }
    if (!isset($_node_types[$type])) {
      return FALSE;
    }
  }
  switch ($op) {
    case 'types':
      return $_node_types;
    case 'type':
      return isset($_node_types[$type]) ? $_node_types[$type] : FALSE;
    case 'base':
      return isset($_node_types[$type]->base) ? $_node_types[$type]->base : FALSE;
    case 'names':
      return $_node_names;
    case 'name':
      return isset($_node_names[$type]) ? $_node_names[$type] : FALSE;
  }
}

/**
 * Resets the database cache of node types, and saves all new or non-modified
 * module-defined node types to the database.
 */
function node_types_rebuild() {
  _node_types_build();

  $node_types = node_get_types('types', NULL, TRUE);

  foreach ($node_types as $type => $info) {
    if (!empty($info->is_new)) {
      node_type_save($info);
    }
    if (!empty($info->disabled)) {
      node_type_delete($info->type);
    }
  }

  _node_types_build();
}

/**
 * Saves a node type to the database.
 *
 * @param $info
 *   The node type to save, as an object.
 *
 * @return
 *   Status flag indicating outcome of the operation.
 */
function node_type_save($info) {
  $is_existing = FALSE;
  $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
  $is_existing = db_result(db_query("SELECT COUNT(*) FROM {node_type} WHERE type = '%s'", $existing_type));
  $type = node_type_set_defaults($info);

  $fields = array(
    'type' => (string) $type->type,
    'name' => (string) $type->name,
    'base' => (string) $type->base,
    'has_title' => (int) $type->has_title,
    'title_label' => (string) $type->title_label,
    'has_body' => (int) $type->has_body,
    'body_label' => (string) $type->body_label,
    'description' => (string) $type->description,
    'help' => (string) $type->help,
    'min_word_count' => (int) $type->min_word_count,
    'custom' => (int) $type->custom,
    'modified' => (int) $type->modified,
    'locked' => (int) $type->locked,
  );

  if ($is_existing) {
    db_update('node_type')->fields($fields)->condition('type', $existing_type)->execute();

    module_invoke_all('node_type', 'update', $type);
    return SAVED_UPDATED;
  }
  else {
    $fields['orig_type'] = (string) $type->orig_type;
    db_insert('node_type')->fields($fields)->execute();

    module_invoke_all('node_type', 'insert', $type);
    return SAVED_NEW;
  }
}

/**
 * Deletes a node type from the database.
 *
 * @param $type
 *   The machine-readable name of the node type to be deleted.
 */
function node_type_delete($type) {
  $info = node_get_types('type', $type);
  db_query("DELETE FROM {node_type} WHERE type = '%s'", $type);
  module_invoke_all('node_type', 'delete', $info);
}

/**
 * Updates all nodes of one type to be of another type.
 *
 * @param $old_type
 *   The current node type of the nodes.
 * @param $type
 *   The new node type of the nodes.
 *
 * @return
 *   The number of nodes whose node type field was modified.
 */
function node_type_update_nodes($old_type, $type) {
  db_query("UPDATE {node} SET type = '%s' WHERE type = '%s'", $type, $old_type);
  return db_affected_rows();
}

/**
 * Builds and returns the list of available node types.
 *
 * The list of types is built by querying hook_node_info() in all modules, and
 * by comparing this information with the node types in the {node_type} table.
 *
 */
function _node_types_build() {
  $_node_types = array();
  $_node_names = array();

  $info_array = module_invoke_all('node_info');
  foreach ($info_array as $type => $info) {
    $info['type'] = $type;
    $_node_types[$type] = node_type_set_defaults($info);
    $_node_names[$type] = $info['name'];
  }

  $type_result = db_query(db_rewrite_sql('SELECT nt.type, nt.* FROM {node_type} nt ORDER BY nt.type ASC', 'nt', 'type'));
  while ($type_object = db_fetch_object($type_result)) {
    // Check for node types from disabled modules and mark their types for removal.
    // Types defined by the node module in the database (rather than by a separate
    // module using hook_node_info) have a base value of 'node_content'. The isset()
    // check prevents errors on old (pre-Drupal 7) databases.
    if (isset($type_object->base) && $type_object->base != 'node_content' && empty($info_array[$type_object->type])) {
      $type_object->disabled = TRUE;
    }
    if (!isset($_node_types[$type_object->type]) || $type_object->modified) {
      $_node_types[$type_object->type] = $type_object;
      $_node_names[$type_object->type] = $type_object->name;

      if ($type_object->type != $type_object->orig_type) {
        unset($_node_types[$type_object->orig_type]);
        unset($_node_names[$type_object->orig_type]);
      }
    }
  }

  asort($_node_names);

  return array($_node_types, $_node_names);
}

/**
 * Set the default values for a node type.
 *
 * The defaults are for a type defined through hook_node_info().
 * When populating a custom node type $info should have the 'custom'
 * key set to 1.
 *
 * @param $info
 *   An object or array containing values to override the defaults.
 *
 * @return
 *  A node type object.
 */
function node_type_set_defaults($info = array()) {
  static $type;

  if (!isset($type)) {
    $type = new stdClass();
    $type->type = '';
    $type->name = '';
    $type->base = '';
    $type->description = '';
    $type->help = '';
    $type->min_word_count = 0;
    $type->has_title = 1;
    $type->has_body = 1;
    $type->title_label = t('Title');
    $type->body_label = t('Body');
    $type->custom = 0;
    $type->modified = 0;
    $type->locked = 1;
    $type->is_new = 1;
  }

  $new_type = clone $type;
  $info = (array) $info;
  foreach ($info as $key => $data) {
    $new_type->$key = $data;
  }
  // If the type has no title or body, set an empty label.
  if (!$new_type->has_title) {
    $new_type->title_label = '';
  }
  if (!$new_type->has_body) {
    $new_type->body_label = '';
  }
  $new_type->orig_type = isset($info['type']) ? $info['type'] : '';

  return $new_type;
}

/**
 * Determine whether a node hook exists.
 *
 * @param &$node
 *   Either a node object, node array, or a string containing the node type.
 * @param $hook
 *   A string containing the name of the hook.
 * @return
 *   TRUE iff the $hook exists in the node type of $node.
 */
function node_hook(&$node, $hook) {
  $base = node_get_types('base', $node);
  return module_hook($base, $hook);
}

/**
 * Invoke a node hook.
 *
 * @param &$node
 *   Either a node object, node array, or a string containing the node type.
 * @param $hook
 *   A string containing the name of the hook.
 * @param $a2, $a3, $a4
 *   Arguments to pass on to the hook, after the $node argument.
 * @return
 *   The returned value of the invoked hook.
 */
function node_invoke(&$node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
  if (node_hook($node, $hook)) {
    $base = node_get_types('base', $node);
    $function = $base . '_' . $hook;
    return ($function($node, $a2, $a3, $a4));
  }
}

/**
 * Invoke a hook_nodeapi() operation in all modules.
 *
 * @param &$node
 *   A node object.
 * @param $op
 *   A string containing the name of the nodeapi operation.
 * @param $a3, $a4
 *   Arguments to pass on to the hook, after the $node and $op arguments.
 * @return
 *   The returned value of the invoked hooks.
 */
function node_invoke_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  $return = array();
  $hook = 'nodeapi_' . $op;
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    $result = $function($node, $a3, $a4);
    if (isset($result) && is_array($result)) {
      $return = array_merge($return, $result);
    }
    elseif (isset($result)) {
      $return[] = $result;
    }
  }
  return $return;
}

/**
 * Load node objects from the database.
 *
 * This function should be used whenever you need to load more than one node
 * from the database. Nodes are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
 * @param $nids
 *   An array of node IDs.
 * @param $conditions
 *   An array of conditions on the {node} table in the form 'field' => $value.
 * @param $reset
 *   Whether to reset the internal node_load cache.
 *
 * @return
 *   An array of node objects indexed by nid.
 */
function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) {
  static $node_cache = array();
  if ($reset) {
    $node_cache = array();
  }
  $nodes = array();

  // Create a new variable which is either a prepared version of the $nids
  // array for later comparison with the node cache, or FALSE if no $nids were
  // passed. The $nids array is reduced as items are loaded from cache, and we
  // need to know if it's empty for this reason to avoid querying the database
  // when all requested nodes are loaded from cache.
  $passed_nids = !empty($nids) ? array_flip($nids) : FALSE;

  // Revisions are not statically cached, and require a different query to
  // other conditions, so separate vid into its own variable.
  $vid = isset($conditions['vid']) ? $conditions['vid'] : FALSE;
  unset($conditions['vid']);

  // Load any available nodes from the internal cache.
  if ($node_cache && !$vid) {
    if ($nids) {
      $nodes += array_intersect_key($node_cache, $passed_nids);
      // If any nodes were loaded, remove them from the $nids still to load.
      $nids = array_keys(array_diff_key($passed_nids, $nodes));
    }
    // If loading nodes only by conditions, fetch all available nodes from
    // the cache. Nodes which don't match are removed later.
    elseif ($conditions) {
      $nodes = $node_cache;
    }
  }

  // Exclude any nodes loaded from cache if they don't match $conditions.
  // This ensures the same behaviour whether loading from memory or database.
  if ($conditions) {
    foreach ($nodes as $node) {
      $node_values = (array) $node;
      if (array_diff_assoc($conditions, $node_values)) {
        unset($nodes[$node->nid]);
      }
    }
  }

  // Load any remaining nodes from the database. This is the case if there are
  // any $nids left to load, if loading a revision, or if $conditions was
  // passed without $nids.
  if ($nids || $vid || ($conditions && !$passed_nids)) {
    $query = db_select('node', 'n');

    if ($vid) {
      $query->join('node_revision', 'r', 'r.nid = n.nid AND r.vid = :vid', array(':vid' => $vid));
    }
    else {
      $query->join('node_revision', 'r', 'r.vid = n.vid');
    }
    $query->join('users', 'u', 'u.uid = n.uid');

    // Add fields from the {node} table.
    $node_fields = drupal_schema_fields_sql('node');

    // vid and title are provided by node_revision, so remove them.
    unset($node_fields['vid']);
    unset($node_fields['title']);
    $query->fields('n', $node_fields);

    // Add all fields from the {node_revision} table.
    $node_revision_fields = drupal_schema_fields_sql('node_revision');

    // nid is provided by node, so remove it.
    unset($node_revision_fields['nid']);

    // Change timestamp to revision_timestamp before adding it to the query.
    unset($node_revision_fields['timestamp']);
    $query->addField('r', 'timestamp', 'revision_timestamp');
    $query->fields('r', $node_revision_fields);

    // Add fields from the {users} table.
    $user_fields = array('name', 'picture', 'data');
    $query->fields('u', $user_fields);

    if ($nids) {
      $query->condition('n.nid', $nids, 'IN');
    }
    if ($conditions) {
      foreach ($conditions as $field => $value) {
        $query->condition('n.' . $field, $value);
      }
    }
    $queried_nodes = $query->execute()->fetchAllAssoc('nid');
  }

  // Pass all nodes loaded from the database through the node type specific
  // callbacks and hook_nodeapi_load(), then add them to the internal cache.
  if (!empty($queried_nodes)) {
    // Create an array of nodes for each content type and pass this to the
    // node type specific callback.
    $typed_nodes = array();
    foreach ($queried_nodes as $nid => $node) {
      $typed_nodes[$node->type][$nid] = $node;
    }

    // Call node type specific callbacks on each typed array of nodes.
    foreach ($typed_nodes as $type => $nodes_of_type) {
      if (node_hook($type, 'load')) {
        $function = node_get_types('base', $type) . '_load';
        $function($nodes_of_type);
      }
    }

    // Call hook_nodeapi_load(), pass the node types so modules can return early
    // if not acting on types in the array.
    foreach (module_implements('nodeapi_load') as $module) {
      $function = $module . '_nodeapi_load';
      $function($queried_nodes, array_keys($typed_nodes));
    }
    $nodes += $queried_nodes;
    // Add nodes to the cache if we're not loading a revision.
    if (!$vid) {
      $node_cache += $queried_nodes;
    }
  }

  // Ensure that the returned array is ordered the same as the original $nids
  // array if this was passed in and remove any invalid nids.
  if ($passed_nids) {
    // Remove any invalid nids from the array.
    $passed_nids = array_intersect_key($passed_nids, $nodes);
    foreach ($nodes as $node) {
      $passed_nids[$node->nid] = $node;
    }
    $nodes = $passed_nids;
  }

  return $nodes;
}

/**
 * Load a node object from the database.
 *
 * @param $nid
 *   The node ID.
 * @param $vid
 *   The revision ID.
 * @param $reset
 *   Whether to reset the internal node_load cache.
 *
 * @return
 *   A fully-populated node object.
 */
function node_load($nid, $vid = array(), $reset = FALSE) {
  $vid = isset($vid) ? array('vid' => $vid) : NULL;
  $node = node_load_multiple(array($nid), $vid, $reset);

  return $node ? $node[$nid] : FALSE;
}

/**
 * Perform validation checks on the given node.
 */
function node_validate($node, $form = array()) {
  // Convert the node to an object, if necessary.
  $node = (object)$node;
  $type = node_get_types('type', $node);

  // Make sure the body has the minimum number of words.
  // TODO : use a better word counting algorithm that will work in other languages
  if (!empty($type->min_word_count) && isset($node->body) && count(explode(' ', $node->body)) < $type->min_word_count) {
    form_set_error('body', t('The body of your @type is too short. You need at least %words words.', array('%words' => $type->min_word_count, '@type' => $type->name)));
  }

  if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
  }

  if (user_access('administer nodes')) {
    // Validate the "authored by" field.
    if (!empty($node->name) && !($account = user_load(array('name' => $node->name)))) {
      // The use of empty() is mandatory in the context of usernames
      // as the empty string denotes the anonymous user. In case we
      // are dealing with an anonymous user we set the user ID to 0.
      form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
    }

    // Validate the "authored on" field.
    if (!empty($node->date) && strtotime($node->date) === FALSE) {
      form_set_error('date', t('You have to specify a valid date.'));
    }
  }

  // Do node-type-specific validation checks.
  node_invoke($node, 'validate', $form);
  node_invoke_nodeapi($node, 'validate', $form);
}

/**
 * Prepare node for save and allow modules to make changes.
 */
function node_submit($node) {
  global $user;

  // Convert the node to an object, if necessary.
  $node = (object)$node;

  // Generate the teaser, but only if it hasn't been set (e.g. by a
  // module-provided 'teaser' form item).
  if (!isset($node->teaser)) {
    if (isset($node->body)) {
      $node->format = (!empty($node->body_format) ? $node->body_format : FILTER_FORMAT_DEFAULT);
      $node->teaser = node_teaser($node->body, isset($node->format) ? $node->format : NULL);
      // Chop off the teaser from the body if needed. The teaser_include
      // property might not be set (eg. in Blog API postings), so only act on
      // it, if it was set with a given value.
      if (isset($node->teaser_include) && !$node->teaser_include && $node->teaser == substr($node->body, 0, strlen($node->teaser))) {
        $node->body = substr($node->body, strlen($node->teaser));
      }
    }
    else {
      $node->teaser = '';
    }
  }

  if (user_access('administer nodes')) {
    // Populate the "authored by" field.
    if ($account = user_load(array('name' => $node->name))) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }
  $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
  $node->validated = TRUE;

  return $node;
}

/**
 * Save a node object into the database.
 */
function node_save(&$node) {
  // Let modules modify the node before it is saved to the database.
  node_invoke_nodeapi($node, 'presave');
  global $user;

  $node->is_new = FALSE;

  // Apply filters to some default node fields:
  if (empty($node->nid)) {
    // Insert a new node.
    $node->is_new = TRUE;

    // When inserting a node, $node->log must be set because
    // {node_revision}.log does not (and cannot) have a default
    // value. If the user does not have permission to create
    // revisions, however, the form will not contain an element for
    // log so $node->log will be unset at this point.
    if (!isset($node->log)) {
      $node->log = '';
    }

    // For the same reasons, make sure we have $node->teaser and
    // $node->body. We should consider making these fields nullable
    // in a future version since node types are not required to use them.
    if (!isset($node->teaser)) {
      $node->teaser = '';
    }
    if (!isset($node->body)) {
      $node->body = '';
    }
  }
  elseif (!empty($node->revision)) {
    $node->old_vid = $node->vid;
  }
  else {
    // When updating a node, avoid clobberring an existing log entry with an empty one.
    if (empty($node->log)) {
      unset($node->log);
    }
  }

  // Set some required fields:
  if (empty($node->created)) {
    $node->created = REQUEST_TIME;
  }
  // The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
  $node->changed = REQUEST_TIME;

  $node->timestamp = REQUEST_TIME;
  $update_node = TRUE;

  // Generate the node table query and the node_revisions table query.
  if ($node->is_new) {
    drupal_write_record('node', $node);
    _node_save_revision($node, $user->uid);
    $op = 'insert';
  }
  else {
    drupal_write_record('node', $node, 'nid');
    if (!empty($node->revision)) {
      _node_save_revision($node, $user->uid);
    }
    else {
      _node_save_revision($node, $user->uid, 'vid');
      $update_node = FALSE;
    }
    $op = 'update';
  }
  if ($update_node) {
    db_query('UPDATE {node} SET vid = %d WHERE nid = %d', $node->vid, $node->nid);
  }

  // Call the node specific callback (if any). This can be
  // node_invoke($node, 'insert') or
  // node_invoke($node, 'update').
  node_invoke($node, $op);
  node_invoke_nodeapi($node, $op);

  // Update the node access table for this node.
  node_access_acquire_grants($node);

  // Clear the page and block caches.
  cache_clear_all();
}

/**
 * Helper function to save a revision with the uid of the current user.
 *
 * Node is taken by reference, becuse drupal_write_record() updates the
 * $node with the revision id, and we need to pass that back to the caller.
 */
function _node_save_revision(&$node, $uid, $update = NULL) {
  $temp_uid = $node->uid;
  $node->uid = $uid;
  if (isset($update)) {
    drupal_write_record('node_revision', $node, $update);
  }
  else {
    drupal_write_record('node_revision', $node);
  }
  $node->uid = $temp_uid;
}

/**
 * Delete a node.
 */
function node_delete($nid) {

  $node = node_load($nid);

  if (node_access('delete', $node)) {
    db_query('DELETE FROM {node} WHERE nid = %d', $node->nid);
    db_query('DELETE FROM {node_revision} WHERE nid = %d', $node->nid);

    // Call the node-specific callback (if any):
    node_invoke($node, 'delete');
    node_invoke_nodeapi($node, 'delete');

    // Clear the page and block caches.
    cache_clear_all();

    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_wipe($node->nid, 'node');
    }
    watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
    drupal_set_message(t('@type %title has been deleted.', array('@type' => node_get_types('name', $node), '%title' => $node->title)));
  }
}

/**
 * Generate a display of the given node.
 *
 * @param $node
 *   A node array or node object.
 * @param $teaser
 *   Whether to display the teaser only or the full form.
 * @param $page
 *   Whether the node is being displayed by itself as a page.
 * @param $links
 *   Whether or not to display node links. Links are omitted for node previews.
 *
 * @return
 *   An HTML representation of the themed node.
 */
function node_view($node, $teaser = FALSE, $page = FALSE) {
  $node = (object)$node;

  $node = node_build_content($node, $teaser, $page);

  return theme('node', $node, $teaser, $page);
}

/**
 * Apply filters and build the node's standard elements.
 */
function node_prepare($node, $teaser = FALSE) {
  // First we'll overwrite the existing node teaser and body with
  // the filtered copies! Then, we'll stick those into the content
  // array and set the read more flag if appropriate.
  $node->readmore = (strlen($node->teaser) < strlen($node->body));

  if ($teaser == FALSE) {
    $node->body = check_markup($node->body, $node->format, $node->language, FALSE);
  }
  else {
    $node->teaser = check_markup($node->teaser, $node->format, $node->language, FALSE);
  }

  $node->content['body'] = array(
    '#markup' => $teaser ? $node->teaser : $node->body,
    '#weight' => 0,
  );

  return $node;
}

/**
 * Builds a structured array representing the node's content.
 *
 * @param $node
 *   A node object.
 * @param $teaser
 *   Whether to display the teaser only, as on the main page.
 * @param $page
 *   Whether the node is being displayed by itself as a page.
 *
 * @return
 *   An structured array containing the individual elements
 *   of the node's body.
 */
function node_build_content($node, $teaser = FALSE, $page = FALSE) {

  // The build mode identifies the target for which the node is built.
  if (!isset($node->build_mode)) {
    $node->build_mode = NODE_BUILD_NORMAL;
  }

  // Remove the delimiter (if any) that separates the teaser from the body.
  $node->body = isset($node->body) ? str_replace('<!--break-->', '', $node->body) : '';

  // The 'view' hook can be implemented to overwrite the default function
  // to display nodes.
  if (node_hook($node, 'view')) {
    $node = node_invoke($node, 'view', $teaser, $page);
  }
  else {
    $node = node_prepare($node, $teaser);
  }

  // Allow modules to make their own additions to the node.
  node_invoke_nodeapi($node, 'view', $teaser, $page);
  
  // Allow modules to modify the structured node.
  drupal_alter('node_view', $node, $teaser, $page);

  return $node;
}

/**
 * Generate a page displaying a single node, along with its comments.
 */
function node_show($node, $cid, $message = FALSE) {
  if ($message) {
    drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
  }

  $output = node_view($node, FALSE, TRUE);

  if (function_exists('comment_render') && $node->comment) {
    $output .= comment_render($node, $cid);
  }

  // Update the history table, stating that this user viewed this node.
  node_tag_new($node->nid);

  return $output;
}

/**
 * Theme a log message.
 *
 * @ingroup themeable
 */
function theme_node_log_message($log) {
  return '<div class="log"><div class="title">' . t('Log') . ':</div>' . $log . '</div>';
}

/**
 * Implementation of hook_perm().
 */
function node_perm() {
  $perms = array(
    'administer content types' => array(
      'title' => t('Administer content types'),
      'description' => t('Manage content types and content type administration settings.'),
    ),
    'administer nodes' => array(
      'title' => t('Administer nodes'),
      'description' => t('Manage all information associated with site content, such as author, publication date and current revision. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
    ),
    'access content' => array(
      'title' => t('Access content'),
      'description' => t('View published content.'),
    ),
    'bypass node access' => array(
      'title' => t('Bypass node access'),
      'description' => t('View, edit and delete all site content. Users with this permission will bypass any content-related access control. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
    ),
    'view revisions' => array(
      'title' => t('View revisions'),
      'description' => t('View content revisions.'),
    ),
    'revert revisions' => array(
      'title' => t('Revert revisions'),
      'description' => t('Replace content with an older revision.'),
    ),
    'delete revisions' => array(
      'title' => t('Delete revisions'),
      'description' => t('Delete content revisions.'),
    ),
  );

  foreach (node_get_types() as $type) {
    if ($type->base == 'node_content') {
      $perms += node_list_permissions($type);
    }
  }

  return $perms;
}

/**
 * Gather the rankings from the the hook_ranking implementations.
 */
function _node_rankings() {
  $rankings = array(
    'total' => 0, 'join' => array(), 'score' => array(), 'args' => array(),
  );
  if ($ranking = module_invoke_all('ranking')) {
    foreach ($ranking as $rank => $values) {
      if ($node_rank = variable_get('node_rank_'. $rank, 0)) {
        // If the table defined in the ranking isn't already joined, then add it.
        if (isset($values['join']) && !isset($rankings['join'][$values['join']])) {
          $rankings['join'][$values['join']] = $values['join'];
        }

        // Add the rankings weighted score multiplier value, handling NULL gracefully.
        $rankings['score'][] = 'CAST(%f AS DECIMAL) * COALESCE(('. $values['score'] .'), 0)';

        // Add the the administrator's weighted score multiplier value for this ranking.
        $rankings['total'] += $node_rank;
        $rankings['arguments'][] = $node_rank;

        // Add any additional arguments used by this ranking.
        if (isset($values['arguments'])) {
          $rankings['arguments'] = array_merge($rankings['arguments'], $values['arguments']);
        }
      }
    }
  }
  return $rankings;
}


/**
 * Implementation of hook_search().
 */
function node_search($op = 'search', $keys = NULL) {
  switch ($op) {
    case 'name':
      return t('Content');

    case 'reset':
      db_query("UPDATE {search_dataset} SET reindex = %d WHERE type = 'node'", REQUEST_TIME);
      return;

    case 'status':
      $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
      $remaining = db_result(db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE n.status = 1 AND d.sid IS NULL OR d.reindex <> 0"));
      return array('remaining' => $remaining, 'total' => $total);

    case 'admin':
      $form = array();
      // Output form for defining rank factor weights.
      $form['content_ranking'] = array(
        '#type' => 'fieldset',
        '#title' => t('Content ranking'),
      );
      $form['content_ranking']['#theme'] = 'node_search_admin';
      $form['content_ranking']['info'] = array(
        '#value' => '<em>' . t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em>'
      );

      // Note: reversed to reflect that higher number = higher ranking.
      $options = drupal_map_assoc(range(0, 10));
      foreach (module_invoke_all('ranking') as $var => $values) {
        $form['content_ranking']['factors']['node_rank_'. $var] = array(
          '#title' => $values['title'],
          '#type' => 'select',
          '#options' => $options,
          '#default_value' => variable_get('node_rank_'. $var, 0),
        );
      }
      return $form;

    case 'search':
      // Build matching conditions
      list($join1, $where1) = _db_rewrite_sql();
      $arguments1 = array();
      $conditions1 = 'n.status = 1';

      if ($type = search_query_extract($keys, 'type')) {
        $types = array();
        foreach (explode(',', $type) as $t) {
          $types[] = "n.type = '%s'";
          $arguments1[] = $t;
        }
        $conditions1 .= ' AND (' . implode(' OR ', $types) . ')';
        $keys = search_query_insert($keys, 'type');
      }

      if ($term = search_query_extract($keys, 'term')) {
        $terms = array();
        foreach (explode(',', $term) as $c) {
          $terms[] = "tn.tid = %d";
          $arguments1[] = $c;
        }
        $conditions1 .= ' AND (' . implode(' OR ', $terms) . ')';
        $join1 .= ' INNER JOIN {term_node} tn ON n.vid = tn.vid';
        $keys = search_query_insert($keys, 'term');
      }

      if ($languages = search_query_extract($keys, 'language')) {
        $terms = array();
        foreach (explode(',', $languages) as $l) {
          $terms[] = "n.language = '%s'";
          $arguments1[] = $l;
        }
        $conditions1 .= ' AND (' . implode(' OR ', $terms) . ')';
        $keys = search_query_insert($keys, 'language');
      }

      // Get the ranking expressions.
      $rankings = _node_rankings();

      // When all search factors are disabled (ie they have a weight of zero),
      // The default score is based only on keyword relevance.
      if ($rankings['total'] == 0) {
        $total = 1;
        $arguments2 = array();
        $join2 = '';
        $select2 = 'SUM(i.relevance) AS calculated_score';
      }
      else {
        $total = $rankings['total'];
        $arguments2 = $rankings['arguments'];
        $join2 = implode(' ', $rankings['join']);
        $select2 = 'SUM('. implode(' + ', $rankings['score']) .') AS calculated_score';
      }

      // Do search.
      $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid ' . $join1, $conditions1 . (empty($where1) ? '' : ' AND ' . $where1), $arguments1, $select2, $join2, $arguments2);

      // Load results.
      $results = array();
      foreach ($find as $item) {
        // Build the node body.
        $node = node_load($item->sid);
        $node->build_mode = NODE_BUILD_SEARCH_RESULT;
        $node = node_build_content($node, FALSE, FALSE);
        $node->body = drupal_render($node->content);

        // Fetch comments for snippet.
        $node->body .= module_invoke('comment', 'nodeapi', $node, 'update_index');
        // Fetch terms for snippet.
        $node->body .= module_invoke('taxonomy', 'nodeapi', $node, 'update_index');

        $extra = node_invoke_nodeapi($node, 'search_result');

        $results[] = array(
          'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
          'type' => check_plain(node_get_types('name', $node)),
          'title' => $node->title,
          'user' => theme('username', $node),
          'date' => $node->changed,
          'node' => $node,
          'extra' => $extra,
          'score' => $total ? ($item->calculated_score / $total) : 0,
          'snippet' => search_excerpt($keys, $node->body),
        );
      }
      return $results;
  }
}

/**
 * Implementation of hook_ranking().
 */
function node_ranking() {
  // Create the ranking array and add the basic ranking options.
  $ranking = array(
    'relevance' => array(
      'title' => t('Keyword relevance'),
      // Average relevance values hover around 0.15
      'score' => 'i.relevance',
    ),
    'sticky' => array(
      'title' => t('Content is sticky at top of lists'),
      // The sticky flag is either 0 or 1, which is automatically normalized.
      'score' => 'n.sticky',
    ),
    'promote' => array(
      'title' => t('Content is promoted to the front page'),
      // The promote flag is either 0 or 1, which is automatically normalized.
      'score' => 'n.promote',
    ),
  );

  // Add relevance based on creation or changed date.
  if ($node_cron_last = variable_get('node_cron_last', 0)) {
    $ranking['recent'] = array(
      'title' => t('Recently posted'),
      // Exponential decay with half-life of 6 months, starting at last indexed node
      'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - %d) * 6.43e-8)',
      'arguments' => array($node_cron_last),
    );
  }
  return $ranking;
}

/**
 * Implementation of hook_user_delete().
 */
function node_user_delete(&$edit, &$user) {
  db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
  db_query('UPDATE {node_revision} SET uid = 0 WHERE uid = %d', $user->uid);
}

/**
 * Theme the content ranking part of the search settings admin page.
 *
 * @ingroup themeable
 */
function theme_node_search_admin($form) {
  $output = drupal_render($form['info']);

  $header = array(t('Factor'), t('Weight'));
  foreach (element_children($form['factors']) as $key) {
    $row = array();
    $row[] = $form['factors'][$key]['#title'];
    unset($form['factors'][$key]['#title']);
    $row[] = drupal_render($form['factors'][$key]);
    $rows[] = $row;
  }
  $output .= theme('table', $header, $rows);

  $output .= drupal_render($form);
  return $output;
}

/**
 * Retrieve the comment mode for the given node ID (none, read, or read/write).
 */
function node_comment_mode($nid) {
  $node = node_load($nid);
  return $node->comment;
}

/**
 * Implementation of hook_link().
 */
function node_link($type, $node = NULL, $teaser = FALSE) {
  $links = array();

  if ($type == 'node') {
    if ($teaser == 1 && $node->teaser && !empty($node->readmore)) {
      $links['node_read_more'] = array(
        'title' => t('Read more'),
        'href' => "node/$node->nid",
        // The title attribute gets escaped when the links are processed, so
        // there is no need to escape here.
        'attributes' => array('title' => t('Read the rest of !title.', array('!title' => $node->title)))
      );
    }
  }

  return $links;
}

function _node_revision_access($node, $op = 'view') {
  static $access = array();
  if (!isset($access[$node->vid])) {
    $node_current_revision = node_load($node->nid);
    $is_current_revision = $node_current_revision->vid == $node->vid;
    // There should be at least two revisions. If the vid of the given node
    // and the vid of the current revision differs, then we already have two
    // different revisions so there is no need for a separate database check.
    // Also, if you try to revert to or delete the current revision, that's
    // not good.
    if ($is_current_revision && (db_result(db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = %d', $node->nid)) == 1 || $op == 'update' || $op == 'delete')) {
      $access[$node->vid] = FALSE;
    }
    elseif (user_access('administer nodes')) {
      $access[$node->vid] = TRUE;
    }
    else {
      $map = array('view' => 'view revisions', 'update' => 'revert revisions', 'delete' => 'delete revisions');
      // First check the user permission, second check the access to the
      // current revision and finally, if the node passed in is not the current
      // revision then access to that, too.
      $access[$node->vid] = isset($map[$op]) && user_access($map[$op]) && node_access($op, $node_current_revision) && ($is_current_revision || node_access($op, $node));
    }
  }
  return $access[$node->vid];
}

function _node_add_access() {
  $types = node_get_types();
  foreach ($types as $type) {
    if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Implementation of hook_menu().
 */
function node_menu() {
  $items['admin/content/node'] = array(
    'title' => 'Content',
    'description' => "View, edit, and delete your site's content.",
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_admin_content'),
    'access arguments' => array('administer nodes'),
  );

  $items['admin/content/node/overview'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/content/node-settings'] = array(
    'title' => 'Post settings',
    'description' => 'Control posting behavior, such as teaser length, requiring previews before posting, and the number of posts on the front page.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_configure'),
    'access arguments' => array('administer nodes'),
  );
  $items['admin/content/node-settings/rebuild'] = array(
    'title' => 'Rebuild permissions',
    'page arguments' => array('node_configure_rebuild_confirm'),
    // Any user than can potentially trigger a node_acess_needs_rebuild(TRUE)
    // has to be allowed access to the 'node access rebuild' confirm form.
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );

  $items['admin/build/types'] = array(
    'title' => 'Content types',
    'description' => 'Manage posts by content type, including default status, front page promotion, comment settings, etc.',
    'page callback' => 'node_overview_types',
    'access arguments' => array('administer content types'),
  );
  $items['admin/build/types/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/build/types/add'] = array(
    'title' => 'Add content type',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_type_form'),
    'access arguments' => array('administer content types'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['node'] = array(
    'title' => 'Content',
    'page callback' => 'node_page_default',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['node/add'] = array(
    'title' => 'Create content',
    'page callback' => 'node_add_page',
    'access callback' => '_node_add_access',
    'weight' => 1,
  );
  $items['rss.xml'] = array(
    'title' => 'RSS feed',
    'page callback' => 'node_feed',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  foreach (node_get_types('types', NULL, TRUE) as $type) {
    $type_url_str = str_replace('_', '-', $type->type);
    $items['node/add/' . $type_url_str] = array(
      'title' => $type->name,
      'title callback' => 'check_plain',
      'page callback' => 'node_add',
      'page arguments' => array(2),
      'access callback' => 'node_access',
      'access arguments' => array('create', $type->type),
      'description' => $type->description,
    );
    $items['admin/build/node-type/' . $type_url_str] = array(
      'title' => $type->name,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('node_type_form', $type),
      'access arguments' => array('administer content types'),
      'type' => MENU_CALLBACK,
    );
    $items['admin/build/node-type/' . $type_url_str . '/edit'] = array(
      'title' => 'Edit',
      'type' => MENU_DEFAULT_LOCAL_TASK,
    );
    $items['admin/build/node-type/' . $type_url_str . '/delete'] = array(
      'title' => 'Delete',
      'page arguments' => array('node_type_delete_confirm', $type),
      'access arguments' => array('administer content types'),
      'type' => MENU_CALLBACK,
    );
  }
  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'type' => MENU_CALLBACK);
  $items['node/%node/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10);
  $items['node/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'node_page_edit',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 1,
    'type' => MENU_LOCAL_TASK,
  );
  $items['node/%node/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_delete_confirm', 1),
    'access callback' => 'node_access',
    'access arguments' => array('delete', 1),
    'weight' => 1,
    'type' => MENU_CALLBACK);
  $items['node/%node/revisions'] = array(
    'title' => 'Revisions',
    'page callback' => 'node_revision_overview',
    'page arguments' => array(1),
    'access callback' => '_node_revision_access',
    'access arguments' => array(1),
    'weight' => 2,
    'type' => MENU_LOCAL_TASK,
  );
  $items['node/%node/revisions/%/view'] = array(
    'title' => 'Revisions',
    'load arguments' => array(3),
    'page callback' => 'node_show',
    'page arguments' => array(1, NULL, TRUE),
    'access callback' => '_node_revision_access',
    'access arguments' => array(1),
    'type' => MENU_CALLBACK,
  );
  $items['node/%node/revisions/%/revert'] = array(
    'title' => 'Revert to earlier revision',
    'load arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_revision_revert_confirm', 1),
    'access callback' => '_node_revision_access',
    'access arguments' => array(1, 'update'),
    'type' => MENU_CALLBACK,
  );
  $items['node/%node/revisions/%/delete'] = array(
    'title' => 'Delete earlier revision',
    'load arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_revision_delete_confirm', 1),
    'access callback' => '_node_revision_access',
    'access arguments' => array(1, 'delete'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Title callback.
 */
function node_page_title($node) {
  return $node->title;
}

/**
 * Implementation of hook_init().
 */
function node_init() {
  drupal_add_css(drupal_get_path('module', 'node') . '/node.css');
}

function node_last_changed($nid) {
  $node = db_fetch_object(db_query('SELECT changed FROM {node} WHERE nid = %d', $nid));
  return ($node->changed);
}

/**
 * Return a list of all the existing revision numbers.
 */
function node_revision_list($node) {
  $revisions = array();
  $result = db_query('SELECT r.vid, r.title, r.log, r.uid, n.vid AS current_vid, r.timestamp, u.name FROM {node_revision} r LEFT JOIN {node} n ON n.vid = r.vid INNER JOIN {users} u ON u.uid = r.uid WHERE r.nid = %d ORDER BY r.timestamp DESC', $node->nid);
  while ($revision = db_fetch_object($result)) {
    $revisions[$revision->vid] = $revision;
  }

  return $revisions;
}

/**
 * Implementation of hook_block_list().
 */
function node_block_list() {
  $blocks['syndicate']['info'] = t('Syndicate');
  // Not worth caching.
  $blocks['syndicate']['cache'] = BLOCK_NO_CACHE;
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function node_block_view($delta = '') {
  $block['subject'] = t('Syndicate');
  $block['content'] = theme('feed_icon', url('rss.xml'), t('Syndicate'));

  return $block;
}

/**
 * A generic function for generating RSS feeds from a set of nodes.
 *
 * @param $nids
 *   An array of node IDs (nid). Defaults to FALSE so empty feeds can be
 *   generated with passing an empty array, if no items are to be added
 *   to the feed.
 * @param $channel
 *   An associative array containing title, link, description and other keys.
 *   The link should be an absolute URL.
 */
function node_feed($nids = FALSE, $channel = array()) {
  global $base_url, $language;

  if ($nids === FALSE) {
    $nids = db_query_range(db_rewrite_sql('SELECT n.nid, n.created FROM {node} n WHERE n.promote = 1 AND n.status = 1 ORDER BY n.created DESC'), 0, variable_get('feed_default_items', 10))->fetchCol();
  }

  $item_length = variable_get('feed_item_length', 'teaser');
  $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');

  // Load all nodes to be rendered.
  $nodes = node_load_multiple($nids);
  $items = '';
  foreach ($nodes as $item) {
    $item->build_mode = NODE_BUILD_RSS;
    $item->link = url("node/$item->nid", array('absolute' => TRUE));

    if ($item_length != 'title') {
      $teaser = ($item_length == 'teaser');

      // Filter and prepare node teaser
      if (node_hook($item, 'view')) {
        $item = node_invoke($item, 'view', $teaser, FALSE);
      }
      else {
        $item = node_prepare($item, $teaser);
      }

      // Allow modules to change $node->teaser before viewing.
      node_invoke_nodeapi($item, 'view', $teaser, FALSE);
    }

    // Allow modules to add additional item fields and/or modify $item
    $extra = node_invoke_nodeapi($item, 'rss_item');
    $extra = array_merge($extra, array(array('key' => 'pubDate', 'value' => gmdate('r', $item->created)), array('key' => 'dc:creator', 'value' => $item->name), array('key' => 'guid', 'value' => $item->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))));
    foreach ($extra as $element) {
      if (isset($element['namespace'])) {
        $namespaces = array_merge($namespaces, $element['namespace']);
      }
    }

    // Prepare the item description
    switch ($item_length) {
      case 'fulltext':
        $item_text = $item->body;
        break;
      case 'teaser':
        $item_text = $item->teaser;
        if (!empty($item->readmore)) {
          $item_text .= '<p>' . l(t('read more'), 'node/' . $item->nid, array('absolute' => TRUE, 'attributes' => array('target' => '_blank'))) . '</p>';
        }
        break;
      case 'title':
        $item_text = '';
        break;
    }

    $items .= format_rss_item($item->title, $item->link, $item_text, $extra);
  }

  $channel_defaults = array(
    'version'     => '2.0',
    'title'       => variable_get('site_name', 'Drupal'),
    'link'        => $base_url,
    'description' => variable_get('site_mission', ''),
    'language'    => $language->language
  );
  $channel = array_merge($channel_defaults, $channel);

  $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $output .= "<rss version=\"" . $channel["version"] . "\" xml:base=\"" . $base_url . "\" " . drupal_attributes($namespaces) . ">\n";
  $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language']);
  $output .= "</rss>\n";

  drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');
  print $output;
}

/**
 * Menu callback; Generate a listing of promoted nodes.
 */
function node_page_default() {
  $nids = pager_query(db_rewrite_sql('SELECT n.nid FROM {node} n WHERE n.promote = 1 AND n.status = 1 ORDER BY n.sticky DESC, n.created DESC'), variable_get('default_nodes_main', 10))->fetchCol();
  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $output = '';
    foreach ($nodes as $node) {
      $output .= node_view($node, TRUE);
    }

    $feed_url = url('rss.xml', array('absolute' => TRUE));
    drupal_add_feed($feed_url, variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
    $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
  }
  else {
    $default_message = '<h1 class="title">' . t('Welcome to your new Drupal website!') . '</h1>';
    $default_message .= '<p>' . t('Please follow these steps to set up and start using your website:') . '</p>';
    $default_message .= '<ol>';
    $default_message .= '<li>' . t('<strong>Configure your website</strong> Once logged in, visit the <a href="@admin">administration section</a>, where you can <a href="@config">customize and configure</a> all aspects of your website.', array('@admin' => url('admin'), '@config' => url('admin/settings'))) . '</li>';
    $default_message .= '<li>' . t('<strong>Enable additional functionality</strong> Next, visit the <a href="@modules">module list</a> and enable features which suit your specific needs. You can find additional modules in the <a href="@download_modules">Drupal modules download section</a>.', array('@modules' => url('admin/build/modules'), '@download_modules' => 'http://drupal.org/project/modules')) . '</li>';
    $default_message .= '<li>' . t('<strong>Customize your website design</strong> To change the "look and feel" of your website, visit the <a href="@themes">themes section</a>. You may choose from one of the included themes or download additional themes from the <a href="@download_themes">Drupal themes download section</a>.', array('@themes' => url('admin/build/themes'), '@download_themes' => 'http://drupal.org/project/themes')) . '</li>';
    $default_message .= '<li>' . t('<strong>Start posting content</strong> Finally, you can <a href="@content">create content</a> for your website. This message will disappear once you have promoted a post to the front page.', array('@content' => url('node/add'))) . '</li>';
    $default_message .= '</ol>';
    $default_message .= '<p>' . t('For more information, please refer to the <a href="@help">help section</a>, or the <a href="@handbook">online Drupal handbooks</a>. You may also post at the <a href="@forum">Drupal forum</a>, or view the wide range of <a href="@support">other support options</a> available.', array('@help' => url('admin/help'), '@handbook' => 'http://drupal.org/handbooks', '@forum' => 'http://drupal.org/forum', '@support' => 'http://drupal.org/support')) . '</p>';

    $output = '<div id="first-time">' . $default_message . '</div>';
  }
  drupal_set_title('');

  return $output;
}

/**
 * Menu callback; view a single node.
 */
function node_page_view($node, $cid = NULL) {
  drupal_set_title($node->title);
  return node_show($node, $cid);
}

/**
 * Implementation of hook_update_index().
 */
function node_update_index() {
  $limit = (int)variable_get('search_cron_limit', 100);

  // Store the maximum possible comments per thread (used for ranking by reply count)
  variable_set('node_cron_comments_scale', 1.0 / max(1, db_result(db_query('SELECT MAX(comment_count) FROM {node_comment_statistics}'))));
  variable_set('node_cron_views_scale', 1.0 / max(1, db_result(db_query('SELECT MAX(totalcount) FROM {node_counter}'))));

  $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit);

  while ($node = db_fetch_object($result)) {
    _node_index_node($node);
  }
}

/**
 * Index a single node.
 *
 * @param $node
 *   The node to index.
 */
function _node_index_node($node) {
  $node = node_load($node->nid);

  // save the changed time of the most recent indexed node, for the search results half-life calculation
  variable_set('node_cron_last', $node->changed);

  // Build the node body.
  $node->build_mode = NODE_BUILD_SEARCH_INDEX;
  $node = node_build_content($node, FALSE, FALSE);
  $node->body = drupal_render($node->content);

  $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->body;

  // Fetch extra data normally not visible
  $extra = node_invoke_nodeapi($node, 'update_index');
  foreach ($extra as $t) {
    $text .= $t;
  }

  // Update index
  search_index($node->nid, 'node', $text);
}

/**
 * Implementation of hook_form_alter().
 */
function node_form_alter(&$form, $form_state, $form_id) {
  // Advanced node search form
  if ($form_id == 'search_form' && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
    // Keyword boxes:
    $form['advanced'] = array(
      '#type' => 'fieldset',
      '#title' => t('Advanced search'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#attributes' => array('class' => 'search-advanced'),
    );
    $form['advanced']['keywords'] = array(
      '#prefix' => '<div class="criterion">',
      '#suffix' => '</div>',
    );
    $form['advanced']['keywords']['or'] = array(
      '#type' => 'textfield',
      '#title' => t('Containing any of the words'),
      '#size' => 30,
      '#maxlength' => 255,
    );
    $form['advanced']['keywords']['phrase'] = array(
      '#type' => 'textfield',
      '#title' => t('Containing the phrase'),
      '#size' => 30,
      '#maxlength' => 255,
    );
    $form['advanced']['keywords']['negative'] = array(
      '#type' => 'textfield',
      '#title' => t('Containing none of the words'),
      '#size' => 30,
      '#maxlength' => 255,
    );

    // Taxonomy box:
    if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) {
      $form['advanced']['term'] = array(
        '#type' => 'select',
        '#title' => t('Only in the term(s)'),
        '#prefix' => '<div class="criterion">',
        '#size' => 10,
        '#suffix' => '</div>',
        '#options' => $taxonomy,
        '#multiple' => TRUE,
      );
    }

    // Node types:
    $types = array_map('check_plain', node_get_types('names'));
    $form['advanced']['type'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Only of the type(s)'),
      '#prefix' => '<div class="criterion">',
      '#suffix' => '</div>',
      '#options' => $types,
    );
    $form['advanced']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Advanced search'),
      '#prefix' => '<div class="action">',
      '#suffix' => '</div>',
    );

    // Languages:
    $language_options = array();
    foreach (language_list('language') as $key => $object) {
      $language_options[$key] = $object->name;
    }
    if (count($language_options) > 1) {
      $form['advanced']['language'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Languages'),
        '#prefix' => '<div class="criterion">',
        '#suffix' => '</div>',
        '#options' => $language_options,
      );
    }


    $form['#validate'][] = 'node_search_validate';
  }
}

/**
 * Form API callback for the search form. Registered in node_form_alter().
 */
function node_search_validate($form, &$form_state) {
  // Initialise using any existing basic search keywords.
  $keys = $form_state['values']['processed_keys'];

  // Insert extra restrictions into the search keywords string.
  if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
    // Retrieve selected types - Forms API sets the value of unselected checkboxes to 0.
    $form_state['values']['type'] = array_filter($form_state['values']['type']);
    if (count($form_state['values']['type'])) {
      $keys = search_query_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
    }
  }

  if (isset($form_state['values']['term']) && is_array($form_state['values']['term'])) {
    $keys = search_query_insert($keys, 'term', implode(',', $form_state['values']['term']));
  }
  if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
    $keys = search_query_insert($keys, 'language', implode(',', array_filter($form_state['values']['language'])));
  }
  if ($form_state['values']['or'] != '') {
    if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
      $keys .= ' ' . implode(' OR ', $matches[1]);
    }
  }
  if ($form_state['values']['negative'] != '') {
    if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
      $keys .= ' -' . implode(' -', $matches[1]);
    }
  }
  if ($form_state['values']['phrase'] != '') {
    $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
  }
  if (!empty($keys)) {
    form_set_value($form['basic']['inline']['processed_keys'], trim($keys), $form_state);
  }
}

/**
 * @defgroup node_access Node access rights
 * @{
 * The node access system determines who can do what to which nodes.
 *
 * In determining access rights for a node, node_access() first checks
 * whether the user has the "administer nodes" permission. Such users have
 * unrestricted access to all nodes. Then the node module's hook_access()
 * is called, and a TRUE or FALSE return value will grant or deny access.
 * This allows, for example, the blog module to always grant access to the
 * blog author, and for the book module to always deny editing access to
 * PHP pages.
 *
 * If node module does not intervene (returns NULL), then the
 * node_access table is used to determine access. All node access
 * modules are queried using hook_node_grants() to assemble a list of
 * "grant IDs" for the user. This list is compared against the table.
 * If any row contains the node ID in question (or 0, which stands for "all
 * nodes"), one of the grant IDs returned, and a value of TRUE for the
 * operation in question, then access is granted. Note that this table is a
 * list of grants; any matching row is sufficient to grant access to the
 * node.
 *
 * In node listings, the process above is followed except that
 * hook_access() is not called on each node for performance reasons and for
 * proper functioning of the pager system. When adding a node listing to your
 * module, be sure to use db_rewrite_sql() to add
 * the appropriate clauses to your query for access checks.
 *
 * To see how to write a node access module of your own, see
 * node_access_example.module.
 */

/**
 * Determine whether the current user may perform the given operation on the
 * specified node.
 *
 * @param $op
 *   The operation to be performed on the node. Possible values are:
 *   - "view"
 *   - "update"
 *   - "delete"
 *   - "create"
 * @param $node
 *   The node object (or node array) on which the operation is to be performed,
 *   or node type (e.g. 'forum') for "create" operation.
 * @param $account
 *   Optional, a user object representing the user for whom the operation is to
 *   be performed. Determines access for a user other than the current user.
 * @return
 *   TRUE if the operation may be performed.
 */
function node_access($op, $node, $account = NULL) {
  global $user;

  if (!$node) {
    return FALSE;
  }
  // Convert the node to an object if necessary:
  if ($op != 'create') {
    $node = (object)$node;
  }
  // If no user object is supplied, the access check is for the current user.
  if (empty($account)) {
    $account = $user;
  }
  // If the node is in a restricted format, disallow editing.
  if ($op == 'update' && !filter_access($node->format)) {
    return FALSE;
  }

  if (user_access('bypass node access', $account)) {
    return TRUE;
  }

  if (!user_access('access content', $account)) {
    return FALSE;
  }

  // Can't use node_invoke('access', $node), because the access hook takes the
  // $op parameter before the $node parameter.
  $base = node_get_types('base', $node);
  $access = module_invoke($base, 'access', $op, $node, $account);
  if (!is_null($access)) {
    return $access;
  }

  // If the module did not override the access rights, use those set in the
  // node_access table.
  if ($op != 'create' && $node->nid && $node->status) {
    $grants = array();
    foreach (node_access_grants($op, $account) as $realm => $gids) {
      foreach ($gids as $gid) {
        $grants[] = "(gid = $gid AND realm = '$realm')";
      }
    }

    $grants_sql = '';
    if (count($grants)) {
      $grants_sql = 'AND (' . implode(' OR ', $grants) . ')';
    }

    $sql = "SELECT COUNT(*) FROM {node_access} WHERE (nid = 0 OR nid = %d) $grants_sql AND grant_$op >= 1";
    $result = db_query($sql, $node->nid);
    return (db_result($result));
  }

  // Let authors view their own nodes.
  if ($op == 'view' && $account->uid == $node->uid && $account->uid != 0) {
    return TRUE;
  }

  return FALSE;
}

/**
 * Generate an SQL join clause for use in fetching a node listing.
 *
 * @param $node_alias
 *   If the node table has been given an SQL alias other than the default
 *   "n", that must be passed here.
 * @param $node_access_alias
 *   If the node_access table has been given an SQL alias other than the default
 *   "na", that must be passed here.
 * @return
 *   An SQL join clause.
 */
function _node_access_join_sql($node_alias = 'n', $node_access_alias = 'na') {
  if (user_access('bypass node access')) {
    return '';
  }

  return 'INNER JOIN {node_access} ' . $node_access_alias . ' ON ' . $node_access_alias . '.nid = ' . $node_alias . '.nid';
}

/**
 * Generate an SQL where clause for use in fetching a node listing.
 *
 * @param $op
 *   The operation that must be allowed to return a node.
 * @param $node_access_alias
 *   If the node_access table has been given an SQL alias other than the default
 *   "na", that must be passed here.
 * @param $account
 *   The user object for the user performing the operation. If omitted, the
 *   current user is used.
 * @return
 *   An SQL where clause.
 */
function _node_access_where_sql($op = 'view', $node_access_alias = 'na', $account = NULL) {
  if (user_access('bypass node access')) {
    return;
  }

  $grants = array();
  foreach (node_access_grants($op, $account) as $realm => $gids) {
    foreach ($gids as $gid) {
      $grants[] = "($node_access_alias.gid = $gid AND $node_access_alias.realm = '$realm')";
    }
  }

  $grants_sql = '';
  if (count($grants)) {
    $grants_sql = 'AND (' . implode(' OR ', $grants) . ')';
  }

  $sql = "$node_access_alias.grant_$op >= 1 $grants_sql";
  return $sql;
}

/**
 * Fetch an array of permission IDs granted to the given user ID.
 *
 * The implementation here provides only the universal "all" grant. A node
 * access module should implement hook_node_grants() to provide a grant
 * list for the user.
 *
 * @param $op
 *   The operation that the user is trying to perform.
 * @param $account
 *   The user object for the user performing the operation. If omitted, the
 *   current user is used.
 * @return
 *   An associative array in which the keys are realms, and the values are
 *   arrays of grants for those realms.
 */
function node_access_grants($op, $account = NULL) {

  if (!isset($account)) {
    $account = $GLOBALS['user'];
  }

  return array_merge(array('all' => array(0)), module_invoke_all('node_grants', $account, $op));
}

/**
 * Determine whether the user has a global viewing grant for all nodes.
 */
function node_access_view_all_nodes() {
  static $access;

  if (!isset($access)) {
    $grants = array();
    foreach (node_access_grants('view') as $realm => $gids) {
      foreach ($gids as $gid) {
        $grants[] = "(gid = $gid AND realm = '$realm')";
      }
    }

    $grants_sql = '';
    if (count($grants)) {
      $grants_sql = 'AND (' . implode(' OR ', $grants) . ')';
    }

    $sql = "SELECT COUNT(*) FROM {node_access} WHERE nid = 0 $grants_sql AND grant_view >= 1";
    $result = db_query($sql);
    $access = db_result($result);
  }

  return $access;
}

/**
 * Implementation of hook_db_rewrite_sql().
 */
function node_db_rewrite_sql($query, $primary_table, $primary_field) {
  if ($primary_field == 'nid' && !node_access_view_all_nodes()) {
    $return['join'] = _node_access_join_sql($primary_table);
    $return['where'] = _node_access_where_sql();
    $return['distinct'] = 1;
    return $return;
  }
}


/**
 * Implementation of hook_query_alter().
 * @todo This doesn't quite work yet.
 */
function DISABLED_node_query_alter(Query $query) {
  if ($query->hasTag('node_access')) {
    if (! user_access('administer nodes')) {
      $query->distinct();
      $access_alias = $query->join('node_access', 'na', 'na.nid = n.nid');
      dsm('hello');
      _node_query_alter_where($query, 'view', $access_alias);
    }
  }
}

function _node_query_alter_where($query, $op = 'view', $node_access_alias = 'na', $account = NULL) {
  $or = db_or();
  foreach (node_access_grants($op, $account) as $realm => $gids) {
    foreach ($gids as $gid) {
      $or->condition("{$node_access_alias}.gid = :gid AND {$node_access_alias}.realm = :realm", array(':gid' => $gid, ':realm' => $realm));
    }
  }

  if (count($or->conditions())) {
    $query->condition($or);
  }

  $query->condition("$node_access_alias.grant_$op", '>=', 1);
}

/**
 * This function will call module invoke to get a list of grants and then
 * write them to the database. It is called at node save, and should be
 * called by modules whenever something other than a node_save causes
 * the permissions on a node to change.
 *
 * This function is the only function that should write to the node_access
 * table.
 *
 * @param $node
 *   The $node to acquire grants for.
 */
function node_access_acquire_grants($node) {
  $grants = module_invoke_all('node_access_records', $node);
  if (empty($grants)) {
    $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
  }
  else {
    // retain grants by highest priority
    $grant_by_priority = array();
    foreach ($grants as $g) {
      $grant_by_priority[intval($g['priority'])][] = $g;
    }
    krsort($grant_by_priority);
    $grants = array_shift($grant_by_priority);
  }

  node_access_write_grants($node, $grants);
}

/**
 * This function will write a list of grants to the database, deleting
 * any pre-existing grants. If a realm is provided, it will only
 * delete grants from that realm, but it will always delete a grant
 * from the 'all' realm. Modules which utilize node_access can
 * use this function when doing mass updates due to widespread permission
 * changes.
 *
 * @param $node
 *   The $node being written to. All that is necessary is that it contain a nid.
 * @param $grants
 *   A list of grants to write. Each grant is an array that must contain the
 *   following keys: realm, gid, grant_view, grant_update, grant_delete.
 *   The realm is specified by a particular module; the gid is as well, and
 *   is a module-defined id to define grant privileges. each grant_* field
 *   is a boolean value.
 * @param $realm
 *   If provided, only read/write grants for that realm.
 * @param $delete
 *   If false, do not delete records. This is only for optimization purposes,
 *   and assumes the caller has already performed a mass delete of some form.
 */
function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE) {
  if ($delete) {
    $query = db_delete('node_access')->condition('nid', $node->nid);
    if ($realm) {
      $query->condition('realm', array($realm, 'all'), 'IN');
    }
    $query->execute();
  }

  // Only perform work when node_access modules are active.
  if (count(module_implements('node_grants'))) {
    foreach ($grants as $grant) {
      if ($realm && $realm != $grant['realm']) {
        continue;
      }
      // Only write grants; denies are implicit.
      if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
        db_query("INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (%d, '%s', %d, %d, %d, %d)", $node->nid, $grant['realm'], $grant['gid'], $grant['grant_view'], $grant['grant_update'], $grant['grant_delete']);
      }
    }
  }
}

/**
 * Flag / unflag the node access grants for rebuilding, or read the current
 * value of the flag.
 *
 * When the flag is set, a message is displayed to users with 'access
 * administration pages' permission, pointing to the 'rebuild' confirm form.
 * This can be used as an alternative to direct node_access_rebuild calls,
 * allowing administrators to decide when they want to perform the actual
 * (possibly time consuming) rebuild.
 * When unsure the current user is an adminisrator, node_access_rebuild
 * should be used instead.
 *
 * @param $rebuild
 *   (Optional) The boolean value to be written.
  * @return
 *   (If no value was provided for $rebuild) The current value of the flag.
 */
function node_access_needs_rebuild($rebuild = NULL) {
  if (!isset($rebuild)) {
    return variable_get('node_access_needs_rebuild', FALSE);
  }
  elseif ($rebuild) {
    variable_set('node_access_needs_rebuild', TRUE);
  }
  else {
    variable_del('node_access_needs_rebuild');
  }
}

/**
 * Rebuild the node access database. This is occasionally needed by modules
 * that make system-wide changes to access levels.
 *
 * When the rebuild is required by an admin-triggered action (e.g module
 * settings form), calling node_access_needs_rebuild(TRUE) instead of
 * node_access_rebuild() lets the user perform his changes and actually
 * rebuild only once he is done.
 *
 * Note : As of Drupal 6, node access modules are not required to (and actually
 * should not) call node_access_rebuild() in hook_enable/disable anymore.
 *
 * @see node_access_needs_rebuild()
 *
 * @param $batch_mode
 *   Set to TRUE to process in 'batch' mode, spawning processing over several
 *   HTTP requests (thus avoiding the risk of PHP timeout if the site has a
 *   large number of nodes).
 *   hook_update_N and any form submit handler are safe contexts to use the
 *   'batch mode'. Less decidable cases (such as calls from hook_user,
 *   hook_taxonomy, hook_node_type...) might consider using the non-batch mode.
 */
function node_access_rebuild($batch_mode = FALSE) {
  db_query("DELETE FROM {node_access}");
  // Only recalculate if the site is using a node_access module.
  if (count(module_implements('node_grants'))) {
    if ($batch_mode) {
      $batch = array(
        'title' => t('Rebuilding content access permissions'),
        'operations' => array(
          array('_node_access_rebuild_batch_operation', array()),
        ),
        'finished' => '_node_access_rebuild_batch_finished'
      );
      batch_set($batch);
    }
    else {
      // If not in 'safe mode', increase the maximum execution time.
      if (!ini_get('safe_mode')) {
        set_time_limit(240);
      }
      $result = db_query("SELECT nid FROM {node}");
      while ($node = db_fetch_object($result)) {
        $loaded_node = node_load($node->nid, NULL, TRUE);
        // To preserve database integrity, only aquire grants if the node
        // loads successfully.
        if (!empty($loaded_node)) {
          node_access_acquire_grants($loaded_node);
        }
      }
    }
  }
  else {
    // Not using any node_access modules. Add the default grant.
    db_query("INSERT INTO {node_access} VALUES (0, 0, 'all', 1, 0, 0)");
  }

  if (!isset($batch)) {
    drupal_set_message(t('Content permissions have been rebuilt.'));
    node_access_needs_rebuild(FALSE);
    cache_clear_all();
  }
}

/**
 * Batch operation for node_access_rebuild_batch.
 *
 * This is a mutlistep operation : we go through all nodes by packs of 20.
 * The batch processing engine interrupts processing and sends progress
 * feedback after 1 second execution time.
 */
function _node_access_rebuild_batch_operation(&$context) {
  if (empty($context['sandbox'])) {
    // Initiate multistep processing.
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;
    $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT nid) FROM {node}'));
  }

  // Process the next 20 nodes.
  $limit = 20;
  $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);
  while ($row = db_fetch_array($result)) {
    $loaded_node = node_load($row['nid'], NULL, TRUE);
    // To preserve database integrity, only aquire grants if the node
    // loads successfully.
    if (!empty($loaded_node)) {
      node_access_acquire_grants($loaded_node);
    }
    $context['sandbox']['progress']++;
    $context['sandbox']['current_node'] = $loaded_node->nid;
  }

  // Multistep processing : report progress.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 * Post-processing for node_access_rebuild_batch.
 */
function _node_access_rebuild_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('The content access permissions have been rebuilt.'));
    node_access_needs_rebuild(FALSE);
  }
  else {
    drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
  }
  cache_clear_all();
}

/**
 * @} End of "defgroup node_access".
 */


/**
 * @defgroup node_content Hook implementations for user-created content types.
 * @{
 */

/**
 * Implementation of hook_access().
 *
 * Named so as not to conflict with node_access()
 */
function node_content_access($op, $node, $account) {
  $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);

  if ($op == 'create') {
    return user_access('create ' . $type . ' content', $account);
  }

  if ($op == 'update') {
    if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
      return TRUE;
    }
  }

  if ($op == 'delete') {
    if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
      return TRUE;
    }
  }
}

/**
 * Implementation of hook_form().
 */
function node_content_form($node, $form_state) {
  $type = node_get_types('type', $node);
  $form = array();

  if ($type->has_title) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => check_plain($type->title_label),
      '#required' => TRUE,
      '#default_value' => $node->title,
      '#maxlength' => 255,
      '#weight' => -5,
    );
  }

  if ($type->has_body) {
    $form['body_field'] = node_body_field($node, $type->body_label, $type->min_word_count);
  }

  return $form;
}

/**
 * @} End of "defgroup node_content".
 */

/**
 * Implementation of hook_forms(). All node forms share the same form handler
 */
function node_forms() {
  $forms = array();
  if ($types = node_get_types()) {
    foreach (array_keys($types) as $type) {
      $forms[$type . '_node_form']['callback'] = 'node_form';
    }
  }
  return $forms;
}

/**
 * Format the "Submitted by username on date/time" for each node
 *
 * @ingroup themeable
 */
function theme_node_submitted($node) {
  return t('Submitted by !username on @datetime',
    array(
      '!username' => theme('username', $node),
      '@datetime' => format_date($node->created),
    ));
}

/**
 * Implementation of hook_hook_info().
 */
function node_hook_info() {
  return array(
    'node' => array(
      'nodeapi' => array(
        'presave' => array(
          'runs when' => t('When either saving a new post or updating an existing post'),
        ),
        'insert' => array(
          'runs when' => t('After saving a new post'),
        ),
        'update' => array(
          'runs when' => t('After saving an updated post'),
        ),
        'delete' => array(
          'runs when' => t('After deleting a post')
        ),
        'view' => array(
          'runs when' => t('When content is viewed by an authenticated user')
        ),
      ),
    ),
  );
}

/**
 * Implementation of hook_action_info().
 */
function node_action_info() {
  return array(
    'node_publish_action' => array(
      'type' => 'node',
      'description' => t('Publish post'),
      'configurable' => FALSE,
      'behavior' => array('changes_node_property'),
      'hooks' => array(
        'nodeapi' => array('presave'),
        'comment' => array('insert', 'update'),
      ),
    ),
    'node_unpublish_action' => array(
      'type' => 'node',
      'description' => t('Unpublish post'),
      'configurable' => FALSE,
      'behavior' => array('changes_node_property'),
      'hooks' => array(
        'nodeapi' => array('presave'),
        'comment' => array('delete', 'insert', 'update'),
      ),
    ),
    'node_make_sticky_action' => array(
      'type' => 'node',
      'description' => t('Make post sticky'),
      'configurable' => FALSE,
      'behavior' => array('changes_node_property'),
      'hooks' => array(
        'nodeapi' => array('presave'),
        'comment' => array('insert', 'update'),
      ),
    ),
    'node_make_unsticky_action' => array(
      'type' => 'node',
      'description' => t('Make post unsticky'),
      'configurable' => FALSE,
      'behavior' => array('changes_node_property'),
      'hooks' => array(
        'nodeapi' => array('presave'),
        'comment' => array('delete', 'insert', 'update'),
      ),
    ),
    'node_promote_action' => array(
      'type' => 'node',
      'description' => t('Promote post to front page'),
      'configurable' => FALSE,
      'behavior' => array('changes_node_property'),
      'hooks' => array(
        'nodeapi' => array('presave'),
        'comment' => array('insert', 'update'),
      ),
    ),
    'node_unpromote_action' => array(
      'type' => 'node',
      'description' => t('Remove post from front page'),
      'configurable' => FALSE,
      'behavior' => array('changes_node_property'),
      'hooks' => array(
        'nodeapi' => array('presave'),
        'comment' => array('delete', 'insert', 'update'),
      ),
    ),
    'node_assign_owner_action' => array(
      'type' => 'node',
      'description' => t('Change the author of a post'),
      'configurable' => TRUE,
      'behavior' => array('changes_node_property'),
      'hooks' => array(
        'any' => TRUE,
        'nodeapi' => array('presave'),
        'comment' => array('delete', 'insert', 'update'),
      ),
    ),
    'node_save_action' => array(
      'type' => 'node',
      'description' => t('Save post'),
      'configurable' => FALSE,
      'hooks' => array(
        'comment' => array('delete', 'insert', 'update'),
      ),
    ),
    'node_unpublish_by_keyword_action' => array(
      'type' => 'node',
      'description' => t('Unpublish post containing keyword(s)'),
      'configurable' => TRUE,
      'hooks' => array(
        'nodeapi' => array('presave', 'insert', 'update'),
      ),
    ),
  );
}

/**
 * Implementation of a Drupal action.
 * Sets the status of a node to 1, meaning published.
 */
function node_publish_action(&$node, $context = array()) {
  $node->status = 1;
  watchdog('action', 'Set @type %title to published.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
}

/**
 * Implementation of a Drupal action.
 * Sets the status of a node to 0, meaning unpublished.
 */
function node_unpublish_action(&$node, $context = array()) {
  $node->status = 0;
  watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
}

/**
 * Implementation of a Drupal action.
 * Sets the sticky-at-top-of-list property of a node to 1.
 */
function node_make_sticky_action(&$node, $context = array()) {
  $node->sticky = 1;
  watchdog('action', 'Set @type %title to sticky.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
}

/**
 * Implementation of a Drupal action.
 * Sets the sticky-at-top-of-list property of a node to 0.
 */
function node_make_unsticky_action(&$node, $context = array()) {
  $node->sticky = 0;
  watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
}

/**
 * Implementation of a Drupal action.
 * Sets the promote property of a node to 1.
 */
function node_promote_action(&$node, $context = array()) {
  $node->promote = 1;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
}

/**
 * Implementation of a Drupal action.
 * Sets the promote property of a node to 0.
 */
function node_unpromote_action(&$node, $context = array()) {
  $node->promote = 0;
  watchdog('action', 'Removed @type %title from front page.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
}

/**
 * Implementation of a Drupal action.
 * Saves a node.
 */
function node_save_action($node) {
  node_save($node);
  watchdog('action', 'Saved @type %title', array('@type' => node_get_types('name', $node), '%title' => $node->title));
}

/**
 * Implementation of a configurable Drupal action.
 * Assigns ownership of a node to a user.
 */
function node_assign_owner_action(&$node, $context) {
  $node->uid = $context['owner_uid'];
  $owner_name = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $context['owner_uid']));
  watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' => node_get_types('type', $node), '%title' => $node->title, '%name' => $owner_name));
}

function node_assign_owner_action_form($context) {
  $description = t('The username of the user to which you would like to assign ownership.');
  $count = db_result(db_query("SELECT COUNT(*) FROM {users}"));
  $owner_name = '';
  if (isset($context['owner_uid'])) {
    $owner_name = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $context['owner_uid']));
  }

  // Use dropdown for fewer than 200 users; textbox for more than that.
  if (intval($count) < 200) {
    $options = array();
    $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name");
    while ($data = db_fetch_object($result)) {
      $options[$data->name] = $data->name;
    }
    $form['owner_name'] = array(
      '#type' => 'select',
      '#title' => t('Username'),
      '#default_value' => $owner_name,
      '#options' => $options,
      '#description' => $description,
    );
  }
  else {
    $form['owner_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Username'),
      '#default_value' => $owner_name,
      '#autocomplete_path' => 'user/autocomplete',
      '#size' => '6',
      '#maxlength' => '7',
      '#description' => $description,
    );
  }
  return $form;
}

function node_assign_owner_action_validate($form, $form_state) {
  $count = db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s'", $form_state['values']['owner_name']));
  if (intval($count) != 1) {
    form_set_error('owner_name', t('Please enter a valid username.'));
  }
}

function node_assign_owner_action_submit($form, $form_state) {
  // Username can change, so we need to store the ID, not the username.
  $uid = db_result(db_query("SELECT uid from {users} WHERE name = '%s'", $form_state['values']['owner_name']));
  return array('owner_uid' => $uid);
}

function node_unpublish_by_keyword_action_form($context) {
  $form['keywords'] = array(
    '#title' => t('Keywords'),
    '#type' => 'textarea',
    '#description' => t('The post will be unpublished if it contains any of the character sequences above. Use a comma-separated list of character sequences. Example: funny, bungee jumping, "Company, Inc." . Character sequences are case-sensitive.'),
    '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  );
  return $form;
}

function node_unpublish_by_keyword_action_submit($form, $form_state) {
  return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
}

/**
 * Implementation of a configurable Drupal action.
 * Unpublish a node if it contains a certain string.
 *
 * @param $context
 *   An array providing more information about the context of the call to this action.
 * @param $comment
 *   A node object.
 */
function node_unpublish_by_keyword_action($node, $context) {
  foreach ($context['keywords'] as $keyword) {
    if (strstr(node_view(clone $node), $keyword) || strstr($node->title, $keyword)) {
      $node->status = 0;
      watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
      break;
    }
  }
}

/**
 * Helper function to generate standard node permission list for a given type.
 *
 * @param $type
 *   The machine-readable name of the node type.
 * @return array
 *   An array of permission names and descriptions.
 */
function node_list_permissions($type) {
  $info = node_get_types('type', $type);
  $type = check_plain($info->type);

  // Build standard list of node permissions for this type.
  $perms = array(
    "create $type content" => array(
      'title' => t('Create %type_name content', array('%type_name' => $info->name)),
      'description' => t('Create new %type_name content.', array('%type_name' => $info->name)),
    ),
    "edit own $type content" => array(
      'title' => t('Edit own %type_name content', array('%type_name' => $info->name)),
      'description' => t('Edit %type_name content created by the user.', array('%type_name' => $info->name)),
    ),
    "edit any $type content" => array(
      'title' => t('Edit any %type_name content', array('%type_name' => $info->name)),
      'description' => t('Edit any %type_name content, regardless of its author.', array('%type_name' => $info->name)),
    ),
    "delete own $type content" => array(
      'title' => t('Delete own %type_name content', array('%type_name' => $info->name)),
      'description' => t('Delete %type_name content created by the user.', array('%type_name' => $info->name)),
    ),
    "delete any $type content" => array(
      'title' => t('Delete any %type_name content', array('%type_name' => $info->name)),
      'description' => t('Delete any %type_name content, regardless of its author.', array('%type_name' => $info->name)),
    ),
  );

  return $perms;
}

/**
 * Implementation of hook_elements().
 */
function node_elements() {
  $type['node_links'] = array();
  
  return $type;
}

/**
 * Format a set of node links.
 *
 * @param $element
 *   An associative array containing the properties of the element.
 *   Properties used:  value
 * @return
 *   A themed HTML string representing the links.
 *
 * @ingroup themeable
 */
function theme_node_links($element) {
  return theme('links', $element['#value'],  array('class' => 'links inline'));
}