summaryrefslogtreecommitdiffstats
path: root/modules/node.module
blob: 827fbde166c0b869b778829a5e62da928a636a50 (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
<?php

/**
 * @file
 * The core that allows content to be submitted to the site.
 */

define('NODE_NEW_LIMIT', time() - 30 * 24 * 60 * 60);

/**
 * Implementation of hook_help().
 */
function node_help($section) {
  switch ($section) {
    case 'admin/help#node':
      $output = '<p>'. t('All content in a website is stored and treated as <b>nodes</b>. Therefore nodes are any postings such as blogs, stories, polls and forums. The node module manages these content types and is one of the strengths of Drupal over other content management systems.') .'</p>';
      $output .= '<p>'. t('Treating all content as nodes allows the flexibility of creating new types of content. It also allows you to painlessly apply new features or changes to all content. Comments are not stored as nodes but are always associated with a node.') .'</p>';
      $output .= t('<p>Node module features</p>
<ul>
<li>The list tab provides an interface to search and sort all content on your site.</li>
<li>The configure settings tab has basic settings for content on your site.</li>
<li>The configure content types tab lists all content types for your site and lets you configure their default workflow.</li>
<li>The search tab lets you search all content on your site</li>
</ul>
');
      $output .= t('<p>You can</p>
<ul>
<li>search for content at <a href="%search">search</a>.</li>
<li>administer nodes at <a href="%admin-settings-content-types">administer &gt;&gt; settings &gt;&gt; content types</a>.</li>
</ul>
', array('%search' => url('search'), '%admin-settings-content-types' => url('admin/settings/content-types')));
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%node">Node page</a>.', array('%node' => 'http://drupal.org/handbook/modules/node/')) .'</p>';
      return $output;
    case 'admin/modules#description':
      return t('Allows content to be submitted to the site and displayed on pages.');
    case 'admin/node/configure':
    case 'admin/node/configure/settings':
      return t('<p>Settings for the core of Drupal. Almost everything is a node so these settings will affect most of the site.</p>');
    case 'admin/node':
      return t('<p>Below is a list of all of the posts on your site. Other forms of content are listed elsewhere (e.g. <a href="%comments">comments</a>).</p><p>Clicking a title views the post, while clicking an author\'s name views their user information.</p>', array('%comments' => url('admin/comment')));
    case 'admin/node/search':
      return t('<p>Enter a simple pattern to search for a post. This can include the wildcard character *.<br />For example, a search for "br*" might return "bread bakers", "our daily bread" and "brenda".</p>');
  }

  if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'revisions' && !arg(3)) {
    return t('The revisions let you track differences between multiple versions of a post.');
  }

  if (arg(0) == 'node' && arg(1) == 'add' && $type = arg(2)) {
    return filter_xss_admin(variable_get($type .'_help', ''));
  }
}

/**
 * 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.
 */
function node_title_list($result, $title = NULL) {
  while ($node = db_fetch_object($result)) {
    $items[] = l($node->title, 'node/'. $node->nid, $node->comment_count ? array('title' => format_plural($node->comment_count, '1 comment', '%count comments')) : '');
  }

  return theme('node_list', $items, $title);
}

/**
 * Format a listing of links to nodes.
 */
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', time(), $user->uid, $nid);
    }
    else {
      @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, 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 = '$user->uid' AND nid = %d", $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;
}

/**
 * Automatically generate a teaser for a node body in a given format.
 */
function node_teaser($body, $format = NULL) {

  $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['filter/1']) && strpos($body, '<?') !== FALSE) {
      return $body;
    }
  }

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

  // The teaser may not be longer than maximum length specified. Initial slice.
  $teaser = truncate_utf8($body, $size);
  $position = 0;
  // Cache the reverse of the teaser.
  $reversed = strrev($teaser);

  // In some cases, no delimiter has been specified. In this case, we try to
  // split at paragraph boundaries.
  $breakpoints = array('</p>' => 0, '<br />' => 6, '<br>' => 4, "\n" => 1);
  // We use strpos on the reversed needle and haystack for speed.
  foreach ($breakpoints as $point => $offset) {
    $length = strpos($reversed, strrev($point));
    if ($length !== FALSE) {
      $position = - $length - $offset;
      return ($position == 0) ? $teaser : substr($teaser, 0, $position);
    }
  }

  // When even the first paragraph is too long, we try to split at the end of
  // the last full sentence.
  $breakpoints = array('. ' => 1, '! ' => 1, '? ' => 1, '' => 0, '؟ ' => 1);
  $min_length = strlen($reversed);
  foreach ($breakpoints as $point => $offset) {
    $length = strpos($reversed, strrev($point));
    if ($length !== FALSE) {
      $min_length = min($length, $min_length);
      $position = 0 - $length - $offset;
    }
  }
  return ($position == 0) ? $teaser : substr($teaser, 0, $position);
}

function _node_names($op = '', $node = NULL) {
  static $node_names = array();
  static $node_list = array();

  if (empty($node_names)) {
    $node_names = module_invoke_all('node_info');
    foreach ($node_names as $type => $value) {
      $node_list[$type] = $value['name'];
    }
  }
  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_names[$type])) {
      return FALSE;
    }
  }
  switch ($op) {
    case 'base':
      return $node_names[$type]['base'];
    case 'list':
      return $node_list;
    case 'name':
      return $node_list[$type];
  }
}

/**
 * Determine the basename for hook_load etc.
 *
 * @param $node
 *   Either a node object, a node array, or a string containing the node type.
 * @return
 *   The basename for hook_load, hook_nodeapi etc.
 */
function node_get_base($node) {
  return _node_names('base', $node);
}

/**
 * Determine the human readable name for a given type.
 *
 * @param $node
 *   Either a node object, a node array, or a string containing the node type.
 * @return
 *   The human readable name of the node type.
 */
function node_get_name($node) {
  return _node_names('name', $node);
}

/**
 * Return the list of available node types.
 *
 * @return
 *   An array consisting ('#type' => name) pairs.
 */
function node_get_types() {
  return _node_names('list');
}

/**
 * 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) {
  return module_hook(node_get_base($node), $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)) {
    $function = node_get_base($node) ."_$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();
  foreach (module_implements('nodeapi') as $name) {
    $function = $name .'_nodeapi';
    $result = $function($node, $op, $a3, $a4);
    if (isset($result) && is_array($result)) {
      $return = array_merge($return, $result);
    }
    else if (isset($result)) {
      $return[] = $result;
    }
  }
  return $return;
}

/**
 * Load a node object from the database.
 *
 * @param $param
 *   Either the nid of the node or an array of conditions to match against in the database query
 * @param $revision
 *   Which numbered revision to load. Defaults to the current version.
 * @param $reset
 *   Whether to reset the internal node_load cache.
 *
 * @return
 *   A fully-populated node object.
 */
function node_load($param = array(), $revision = NULL, $reset = NULL) {
  static $nodes = array();

  if ($reset) {
    $nodes = array();
  }

  $cachable = ($revision == NULL);
  $arguments = array();
  if (is_numeric($param)) {
    if ($cachable && isset($nodes[$param])) {
      return is_object($nodes[$param]) ? drupal_clone($nodes[$param]) : $nodes[$param];
    }
    $cond = 'n.nid = %d';
    $arguments[] = $param;
  }
  else {
    // Turn the conditions into a query.
    foreach ($param as $key => $value) {
      $cond[] = 'n.'. db_escape_string($key) ." = '%s'";
      $arguments[] = $value;
    }
    $cond = implode(' AND ', $cond);
  }

  // Retrieve the node.
  // No db_rewrite_sql is applied so as to get complete indexing for search.
  if ($revision) {
    array_unshift($arguments, $revision);
    $node = db_fetch_object(db_query('SELECT n.nid, r.vid, n.type, n.status, n.created, n.changed, n.comment, n.promote, n.moderate, n.sticky, r.timestamp AS revision_timestamp, r.title, r.body, r.teaser, r.log, r.format, u.uid, u.name, u.picture, u.data FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.nid = n.nid AND r.vid = %d WHERE '. $cond, $arguments));
  }
  else {
    $node = db_fetch_object(db_query('SELECT n.nid, n.vid, n.type, n.status, n.created, n.changed, n.comment, n.promote, n.moderate, n.sticky, r.timestamp AS revision_timestamp, r.title, r.body, r.teaser, r.log, r.format, u.uid, u.name, u.picture, u.data FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE '. $cond, $arguments));
  }

  if ($node->nid) {
    // Call the node specific callback (if any) and piggy-back the
    // results to the node or overwrite some values.
    if ($extra = node_invoke($node, 'load')) {
      foreach ($extra as $key => $value) {
        $node->$key = $value;
      }
    }

    if ($extra = node_invoke_nodeapi($node, 'load')) {
      foreach ($extra as $key => $value) {
        $node->$key = $value;
      }
    }
    if ($cachable) {
      $nodes[$node->nid] = is_object($node) ? drupal_clone($node) : $node;
    }
  }

  return $node;
}

/**
 * Save a node object into the database.
 */
function node_save(&$node) {
  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;

    $node->nid = db_next_id('{node}_nid');
    $node->vid = db_next_id('{node_revisions}_vid');;
  }
  else {
    // We need to ensure that all node fields are filled.
    $node_current = node_load($node->nid);
    foreach ($node as $field => $data) {
      $node_current->$field = $data;
    }
    $node = $node_current;

    if ($node->revision) {
      $node->old_vid = $node->vid;
      $node->vid = db_next_id('{node_revisions}_vid');
    }
  }

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

  // Split off revisions data to another structure
  $revisions_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
                     'title' => $node->title, 'body' => $node->body,
                     'teaser' => $node->teaser, 'log' => $node->log, 'timestamp' => $node->changed,
                     'uid' => $user->uid, 'format' => $node->format);
  $revisions_table_types = array('nid' => '%d', 'vid' => '%d',
                     'title' => "'%s'", 'body' => "'%s'",
                     'teaser' => "'%s'", 'log' => "'%s'", 'timestamp' => '%d',
                     'uid' => '%d', 'format' => '%d');
  $node_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
                    'title' => $node->title, 'type' => $node->type, 'uid' => $node->uid,
                    'status' => $node->status, 'created' => $node->created,
                    'changed' => $node->changed, 'comment' => $node->comment,
                    'promote' => $node->promote, 'moderate' => $node->moderate,
                    'sticky' => $node->sticky);
  $node_table_types = array('nid' => '%d', 'vid' => '%d',
                    'title' => "'%s'", 'type' => "'%s'", 'uid' => '%d',
                    'status' => '%d', 'created' => '%d',
                    'changed' => '%d', 'comment' => '%d',
                    'promote' => '%d', 'moderate' => '%d',
                    'sticky' => '%d');

  //Generate the node table query and the
  //the node_revisions table query
  if ($node->is_new) {
    $node_query = 'INSERT INTO {node} ('. implode(', ', array_keys($node_table_types)) .') VALUES ('. implode(', ', $node_table_types) .')';
    $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
  }
  else {
    $arr = array();
    foreach ($node_table_types as $key => $value) {
      $arr[] = $key .' = '. $value;
    }
    $node_table_values[] = $node->nid;
    $node_query = 'UPDATE {node} SET '. implode(', ', $arr) .' WHERE nid = %d';
    if ($node->revision) {
      $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
    }
    else {
      $arr = array();
      foreach ($revisions_table_types as $key => $value) {
        $arr[] = $key .' = '. $value;
      }
      $revisions_table_values[] = $node->vid;
      $revisions_query = 'UPDATE {node_revisions} SET '. implode(', ', $arr) .' WHERE vid = %d';
    }
  }

  // Insert the node into the database:
  db_query($node_query, $node_table_values);
  db_query($revisions_query, $revisions_table_values);

  // Call the node specific callback (if any):
  if ($node->is_new) {
    node_invoke($node, 'insert');
    node_invoke_nodeapi($node, 'insert');
  }
  else {
    node_invoke($node, 'update');
    node_invoke_nodeapi($node, 'update');
  }

  // Clear the cache so an anonymous poster can see the node being added or updated.
  cache_clear_all();
}

/**
 * Generate a display of the given node.
 *
 * @param $node
 *   A node array or 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.
 * @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, $links = TRUE) {
  $node = (object)$node;

  // Remove the delimiter (if any) that separates the teaser from the body.
  // TODO: this strips legitimate uses of '<!--break-->' also.
  $node->body = str_replace('<!--break-->', '', $node->body);

  if ($node->log != '' && !$teaser && $node->moderate) {
    $node->body .= '<div class="log"><div class="title">'. t('Log') .':</div>'. filter_xss($node->log) .'</div>';
  }

  // The 'view' hook can be implemented to overwrite the default function
  // to display nodes.
  if (node_hook($node, 'view')) {
    node_invoke($node, 'view', $teaser, $page);
  }
  else {
    $node = node_prepare($node, $teaser);
  }
  // Allow modules to change $node->body before viewing.
  node_invoke_nodeapi($node, 'view', $teaser, $page);
  if ($links) {
    $node->links = module_invoke_all('link', 'node', $node, !$page);
  }
  // unset unused $node part so that a bad theme can not open a security hole
  if ($teaser) {
    unset($node->body);
  }
  else {
    unset($node->teaser);
  }

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

/**
 * Apply filters to a node in preparation for theming.
 */
function node_prepare($node, $teaser = FALSE) {
  $node->readmore = (strlen($node->teaser) < strlen($node->body));
  if ($teaser == FALSE) {
    $node->body = check_markup($node->body, $node->format, FALSE);
  }
  else {
    $node->teaser = check_markup($node->teaser, $node->format, FALSE);
  }
  return $node;
}

/**
 * Generate a page displaying a single node, along with its comments.
 */
function node_show($node, $cid) {
  $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;
}

/**
 * Implementation of hook_perm().
 */
function node_perm() {
  return array('administer nodes', 'access content', 'view revisions', 'revert revisions');
}

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

    case 'reset':
      variable_del('node_cron_last');
      variable_del('node_cron_last_nid');
      return;

    case 'status':
      $last = variable_get('node_cron_last', 0);
      $last_nid = variable_get('node_cron_last_nid', 0);
      $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
      $remaining = db_result(db_query('SELECT COUNT(*) FROM {node} n LEFT JOIN {node_comment_statistics} c ON n.nid = c.nid WHERE n.status = 1 AND ((GREATEST(n.created, n.changed, c.last_comment_timestamp) = %d AND n.nid > %d ) OR (n.created > %d OR n.changed > %d OR c.last_comment_timestamp > %d))', $last, $last_nid, $last, $last, $last));
      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('#type' => 'markup', '#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>');

      $ranking = array('node_rank_relevance' => t('Keyword relevance'),
                       'node_rank_recent' => t('Recently posted'));
      if (module_exist('comment')) {
        $ranking['node_rank_comments'] = t('Number of comments');
      }
      if (module_exist('statistics') && variable_get('statistics_count_content_views', 0)) {
        $ranking['node_rank_views'] = t('Number of views');
      }

      // Note: reversed to reflect that higher number = higher ranking.
      $options = drupal_map_assoc(range(0, 10));
      foreach ($ranking as $var => $title) {
        $form['content_ranking']['factors'][$var] = array('#title' => $title, '#type' => 'select', '#options' => $options, '#default_value' => variable_get($var, 5));
      }
      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 ($category = search_query_extract($keys, 'category')) {
        $categories = array();
        foreach (explode(',', $category) as $c) {
          $categories[] = "tn.tid = %d";
          $arguments1[] = $c;
        }
        $conditions1 .= ' AND ('. implode(' OR ', $categories) .')';
        $join1 .= ' INNER JOIN {term_node} tn ON n.nid = tn.nid';
        $keys = search_query_insert($keys, 'category');
      }

      // Build ranking expression (we try to map each parameter to a
      // uniform distribution in the range 0..1).
      $ranking = array();
      $arguments2 = array();
      $join2 = '';
      $total = 0;
      // Used to avoid joining on node_comment_statistics twice
      $stats_join = false;
      if ($weight = (int)variable_get('node_rank_relevance', 5)) {
        // Average relevance values hover around 0.15
        $ranking[] = '%d * i.relevance';
        $arguments2[] = $weight;
        $total += $weight;
      }
      if ($weight = (int)variable_get('node_rank_recent', 5)) {
        // Exponential decay with half-life of 6 months, starting at last indexed node
        $ranking[] = '%d * POW(2, (GREATEST(n.created, n.changed, c.last_comment_timestamp) - %d) * 6.43e-8)';
        $arguments2[] = $weight;
        $arguments2[] = (int)variable_get('node_cron_last', 0);
        $join2 .= ' INNER JOIN {node} n ON n.nid = i.sid LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
        $stats_join = true;
        $total += $weight;
      }
      if (module_exist('comment') && $weight = (int)variable_get('node_rank_comments', 5)) {
        // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
        $scale = variable_get('node_cron_comments_scale', 0.0);
        $ranking[] = '%d * (2.0 - 2.0 / (1.0 + c.comment_count * %f))';
        $arguments2[] = $weight;
        $arguments2[] = $scale;
        if (!$stats_join) {
          $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
        }
        $total += $weight;
      }
      if (module_exist('statistics') && variable_get('statistics_count_content_views', 0) &&
          $weight = (int)variable_get('node_rank_views', 5)) {
        // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
        $scale = variable_get('node_cron_views_scale', 0.0);
        $ranking[] = '%d * (2.0 - 2.0 / (1.0 + nc.totalcount * %f))';
        $arguments2[] = $weight;
        $arguments2[] = $scale;
        $join2 .= ' LEFT JOIN {node_counter} nc ON nc.nid = i.sid';
        $total += $weight;
      }
      $select2 = (count($ranking) ? implode(' + ', $ranking) : 'i.relevance') . ' AS score';

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

      // Load results
      $results = array();
      foreach ($find as $item) {
        $node = node_load($item->sid);

        // Get node output (filtered and with module-specific fields).
        if (node_hook($node, 'view')) {
          node_invoke($node, 'view', false, false);
        }
        else {
          $node = node_prepare($node, false);
        }
        // Allow modules to change $node->body before viewing.
        node_invoke_nodeapi($node, 'view', false, false);

        // 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),
                           'type' => node_get_name($node),
                           'title' => $node->title,
                           'user' => theme('username', $node),
                           'date' => $node->changed,
                           'node' => $node,
                           'extra' => $extra,
                           'score' => $item->score / $total,
                           'snippet' => search_excerpt($keys, $node->body));
      }
      return $results;
  }
}

/**
 * Implementation of hook_user().
 */
function node_user($op, &$edit, &$user) {
  if ($op == 'delete') {
    db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
    db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
  }
}

function theme_node_search_admin($form) {
  $output = form_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[] = form_render($form['factors'][$key]);
    $rows[] = $row;
  }
  $output .= theme('table', $header, $rows);

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

/**
 * Menu callback; presents general node configuration options.
 */
function node_configure() {

  $form['default_nodes_main'] = array(
    '#type' => 'select', '#title' => t('Number of posts on main page'), '#default_value' => variable_get('default_nodes_main', 10),
    '#options' =>  drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)),
    '#description' => t('The default maximum number of posts to display per page on overview pages such as the main page.')
  );

  $form['teaser_length'] = array(
    '#type' => 'select', '#title' => t('Length of trimmed posts'), '#default_value' => variable_get('teaser_length', 600),
    '#options' => array(0 => t('Unlimited'), 200 => t('200 characters'), 400 => t('400 characters'), 600 => t('600 characters'),
      800 => t('800 characters'), 1000 => t('1000 characters'), 1200 => t('1200 characters'), 1400 => t('1400 characters'),
      1600 => t('1600 characters'), 1800 => t('1800 characters'), 2000 => t('2000 characters')),
    '#description' => t("The maximum number of characters used in the trimmed version of a post.  Drupal will use this setting to determine at which offset long posts should be trimmed.  The trimmed version of a post is typically used as a teaser when displaying the post on the main page, in XML feeds, etc.  To disable teasers, set to 'Unlimited'. Note that this setting will only affect new or updated content and will not affect existing teasers.")
  );

  $form['node_preview'] = array(
    '#type' => 'radios', '#title' => t('Preview post'), '#default_value' => variable_get('node_preview', 0),
    '#options' => array(t('Optional'), t('Required')), '#description' => t('Must users preview posts before submitting?')
  );

  return system_settings_form('node_configure', $form);
}

/**
 * Retrieve the comment mode for the given node ID (none, read, or read/write).
 */
function node_comment_mode($nid) {
  static $comment_mode;
  if (!isset($comment_mode[$nid])) {
    $comment_mode[$nid] = db_result(db_query('SELECT comment FROM {node} WHERE nid = %d', $nid));
  }
  return $comment_mode[$nid];
}

/**
 * Implementation of hook_link().
 */
function node_link($type, $node = 0, $main = 0) {
  $links = array();

  if ($type == 'node') {
    if ($main == 1 && $node->teaser && $node->readmore) {
      $links[] = l(t('read more'), "node/$node->nid", array('title' => t('Read the rest of this posting.'), 'class' => 'read-more'));
    }
  }

  return $links;
}

/**
 * Implementation of hook_menu().
 */
function node_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array('path' => 'admin/node', 'title' => t('content'),
      'callback' => 'node_admin_nodes',
      'access' => user_access('administer nodes'));
    $items[] = array('path' => 'admin/node/overview', 'title' => t('list'),
      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);

    if (module_exist('search')) {
      $items[] = array('path' => 'admin/node/search', 'title' => t('search'),
        'callback' => 'node_admin_search',
        'access' => user_access('administer nodes'),
        'type' => MENU_LOCAL_TASK);
    }

    $items[] = array('path' => 'admin/settings/node', 'title' => t('posts'),
      'callback' => 'node_configure',
      'access' => user_access('administer nodes'));
    $items[] = array('path' => 'admin/settings/content-types', 'title' => t('content types'),
      'callback' => 'node_types_configure',
      'access' => user_access('administer nodes'));

    $items[] = array('path' => 'node', 'title' => t('content'),
      'callback' => 'node_page',
      'access' => user_access('access content'),
      'type' => MENU_MODIFIABLE_BY_ADMIN);
    $items[] = array('path' => 'node/add', 'title' => t('create content'),
      'callback' => 'node_page',
      'access' => user_access('access content'),
      'type' => MENU_ITEM_GROUPING,
      'weight' => 1);
    $items[] = array('path' => 'rss.xml', 'title' => t('rss feed'),
      'callback' => 'node_feed',
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK);
  }
  else {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(arg(1));
      if ($node->nid) {
        $items[] = array('path' => 'node/'. arg(1), 'title' => t('view'),
          'callback' => 'node_page',
          'access' => node_access('view', $node),
          'type' => MENU_CALLBACK);
        $items[] = array('path' => 'node/'. arg(1) .'/view', 'title' => t('view'),
            'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
        $items[] = array('path' => 'node/'. arg(1) .'/edit', 'title' => t('edit'),
          'callback' => 'node_page',
          'access' => node_access('update', $node),
          'weight' => 1,
          'type' => MENU_LOCAL_TASK);
        $items[] = array('path' => 'node/'. arg(1) .'/delete', 'title' => t('delete'),
          'callback' => 'node_delete_confirm',
          'access' => node_access('delete', $node),
          'weight' => 1,
          'type' => MENU_CALLBACK);
        $revisions_access = ((user_access('view revisions') || user_access('administer nodes')) && node_access('view', $node) && db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', arg(1))) > 1);
        $items[] = array('path' => 'node/'. arg(1) .'/revisions', 'title' => t('revisions'),
          'callback' => 'node_revisions',
          'access' => $revisions_access,
          'weight' => 2,
          'type' => MENU_LOCAL_TASK);
        $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/delete', 
          'title' => t('revisions'),
          'callback' => 'node_revisions',
          'access' => $revisions_access,
          'weight' => 2,
          'type' => MENU_CALLBACK);
        $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/revert', 
          'title' => t('revisions'),
          'callback' => 'node_revisions',
          'access' => $revisions_access,
          'weight' => 2,
          'type' => MENU_CALLBACK);
      }
    }
    else if (arg(0) == 'admin' && arg(1) == 'settings' && arg(2) == 'content-types' && is_string(arg(3))) {
      $items[] = array('path' => 'admin/settings/content-types/'. arg(3),
        'title' => t("'%name' content type", array('%name' => node_get_name(arg(3)))),
        'type' => MENU_CALLBACK);
    }
  }

  return $items;
}

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

/**
 * List node administration operations that can be performed.
 */
function node_operations() {
  $operations = array(
    'approve' =>   array(t('Approve the selected posts'), 'UPDATE {node} SET status = 1, moderate = 0 WHERE nid = %d'),
    'promote' =>   array(t('Promote the selected posts'), 'UPDATE {node} SET status = 1, promote = 1, moderate = 0 WHERE nid = %d'),
    'sticky' =>    array(t('Make the selected posts sticky'), 'UPDATE {node} SET status = 1, sticky = 1 WHERE nid = %d'),
    'demote' =>    array(t('Demote the selected posts'), 'UPDATE {node} SET promote = 0 WHERE nid = %d'),
    'unpublish' => array(t('Unpublish the selected posts'), 'UPDATE {node} SET status = 0 WHERE nid = %d'),
    'delete' =>    array(t('Delete the selected posts'), '')
  );
  return $operations;
}

/**
 * List node administration filters that can be applied.
 */
function node_filters() {
  // Regular filters
  $filters['status'] = array('title' => t('status'),
    'options' => array('status-1'   => t('published'),     'status-0' => t('not published'),
                       'moderate-1' => t('in moderation'), 'moderate-0' => t('not in moderation'),
                       'promote-1'  => t('promoted'),      'promote-0' => t('not promoted'),
                       'sticky-1'   => t('sticky'),        'sticky-0' => t('not sticky')));
  $filters['type'] = array('title' => t('type'), 'options' => node_get_types());
  // The taxonomy filter
  if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) {
    $filters['category'] = array('title' => t('category'), 'options' => $taxonomy);
  }

  return $filters;
}

/**
 * Build query for node administration filters based on session.
 */
function node_build_filter_query() {
  $filters = node_filters();

  // Build query
  $where = $args = array();
  $join = '';
  foreach ($_SESSION['node_overview_filter'] as $index => $filter) {
    list($key, $value) = $filter;
    switch($key) {
      case 'status':
        // Note: no exploitable hole as $key/$value have already been checked when submitted
        list($key, $value) = explode('-', $value, 2);
        $where[] = 'n.'. $key .' = %d';
        break;
      case 'category':
        $table = "tn$index";
        $where[] = "$table.tid = %d";
        $join .= "INNER JOIN {term_node} $table ON n.nid = $table.nid ";
        break;
      case 'type':
        $where[] = "n.type = '%s'";
    }
    $args[] = $value;
  }
  $where = count($where) ? 'WHERE '. implode(' AND ', $where) : '';

  return array('where' => $where, 'join' => $join, 'args' => $args);
}

/**
 * Return form for node administration filters.
 */
function node_filter_form() {
  $session = &$_SESSION['node_overview_filter'];
  $session = is_array($session) ? $session : array();
  $filters = node_filters();

  $i = 0;
  $form['filters'] = array('#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'node_filters',
  );
  foreach ($session as $filter) {
    list($type, $value) = $filter;
    if ($type == 'category') {
      // Load term name from DB rather than search and parse options array.
      $value = module_invoke('taxonomy', 'get_term', $value);
      $value = $value->name;
    }
    else {
      $value = $filters[$type]['options'][$value];
    }
    $string = ($i++ ? '<em>and</em> where <strong>%a</strong> is <strong>%b</strong>' : '<strong>%a</strong> is <strong>%b</strong>');
    $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'] , '%b' => $value)));
  }

  foreach ($filters as $key => $filter) {
    $names[$key] = $filter['title'];
    $form['filters']['status'][$key] = array('#type' => 'select', '#options' => $filter['options']);
  }

  $form['filters']['filter'] = array('#type' => 'radios', '#options' => $names, '#default_value' => 'status');
  $form['filters']['buttons']['submit'] = array('#type' => 'submit', '#value' => (count($session) ? t('Refine') : t('Filter')));
  if (count($session)) {
    $form['filters']['buttons']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));
    $form['filters']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
  }

  return drupal_get_form('node_filter_form', $form);
}

/**
 * Theme node administration filter form.
 */
function theme_node_filter_form(&$form) {
  $output .= '<div id="node-admin-filter">';
  $output .= form_render($form['filters']);
  $output .= '</div>';
  $output .= form_render($form);
  return $output;
}

/**
 * Theme node administraton filter selector.
 */
function theme_node_filters(&$form) {
  $output .= '<ul>';
  if (sizeof($form['current'])) {
    foreach (element_children($form['current']) as $key) {
      $output .= '<li>' . form_render($form['current'][$key]) . '</li>';
    }
  }

  $output .= '<li><dl class="multiselect">' . (sizeof($form['current']) ? '<dt><em>'. t('and') .'</em> '. t('where') .'</dt>' : '') . '<dd class="a">';
  foreach (element_children($form['filter']) as $key) {
    $output .= form_render($form['filter'][$key]);
  }
  $output .= '</dd>';

  $output .= '<dt>'. t('is') .'</dt>' . '<dd class="b">';

  foreach (element_children($form['status']) as $key) {
    $output .= form_render($form['status'][$key]);
  }
  $output .= '</dd>';

  $output .= '</dl>';
  $output .= '<div class="container-inline" id="node-admin-buttons">'. form_render($form['buttons']) .'</div>';
  $output .= '</li></ul><br class="clear" />';

  return $output;
}

/**
 * Process result from node administration filter form.
 */
function node_filter_form_submit() {
  global $form_values;
  $op = $_POST['op'];
  $filters = node_filters();
  switch ($op) {
    case t('Filter'):
    case t('Refine'):
      if (isset($form_values['filter'])) {
        $filter = $form_values['filter'];

        // Flatten the options array to accommodate hierarchical/nested options.
        $flat_options = form_options_flatten($filters[$filter]['options']);

        if (isset($flat_options[$form_values[$filter]])) {
          $_SESSION['node_overview_filter'][] = array($filter, $form_values[$filter]);
        }
      }
      break;
    case t('Undo'):
      array_pop($_SESSION['node_overview_filter']);
      break;
    case t('Reset'):
      $_SESSION['node_overview_filter'] = array();
      break;
  }
}

/**
 * Generate the content administration overview.
 */
function node_admin_nodes_submit($form_id, $edit) {
  $operations = node_operations();
  if ($operations[$edit['operation']][1]) {
    // Flag changes
    $operation = $operations[$edit['operation']][1];
    foreach ($edit['nodes'] as $nid => $value) {
      if ($value) {
        db_query($operation, $nid);
      }
    }
    cache_clear_all();
    drupal_set_message(t('The update has been performed.'));
  }
}

function node_admin_nodes_validate($form_id, $edit) {
  $edit['nodes'] = array_diff($edit['nodes'], array(0));
  if (count($edit['nodes']) == 0) {
    if ($edit['operation'] == 'delete') {
      form_set_error('', t('Please select some items to perform the delete operation.'));
    }
    else {
      form_set_error('', t('Please select some items to perform the update on.'));
    }
  }
}

/**
 * Menu callback: content administration.
 */
function node_admin_nodes() {
  global $form_values;
  $output = node_filter_form();

  if ($_POST['edit']['operation'] == 'delete' && $_POST['edit']['nodes']) {
    return node_multiple_delete_confirm();
  }

  $filter = node_build_filter_query();

  $result = pager_query('SELECT n.*, u.name, u.uid FROM {node} n '. $filter['join'] .' INNER JOIN {users} u ON n.uid = u.uid '. $filter['where'] .' ORDER BY n.changed DESC', 50, 0, NULL, $filter['args']);

  $form['options'] = array('#type' => 'fieldset',
    '#title' => t('Update options'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $options = array();
  foreach (node_operations() as $key => $value) {
    $options[$key] = $value[0];
  }
  $form['options']['operation'] = array('#type' => 'select', '#options' => $options,  '#default_value' => 'approve');
  $form['options']['submit'] = array('#type' => 'submit', '#value' => t('Update'));

  $destination = drupal_get_destination();
  while ($node = db_fetch_object($result)) {
    $nodes[$node->nid] = '';
    $form['title'][$node->nid] = array('#value' => l($node->title, 'node/'. $node->nid) .' '. theme('mark', node_mark($node->nid, $node->changed)));
    $form['name'][$node->nid] =  array('#value' => node_get_name($node));
    $form['username'][$node->nid] = array('#value' => theme('username', $node));
    $form['status'][$node->nid] =  array('#value' =>  ($node->status ? t('published') : t('not published')));
    $form['operations'][$node->nid] = array('#value' => l(t('edit'), 'node/'. $node->nid .'/edit', array(), $destination));
  }
  $form['nodes'] = array('#type' => 'checkboxes', '#options' => $nodes);
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));

  // Call the form first, to allow for the form_values array to be populated.
  $output .= drupal_get_form('node_admin_nodes', $form);

  return $output;
}

/**
 * Theme node administration overview.
 */
function theme_node_admin_nodes($form) {
  // Overview table:
  $header = array(NULL, t('Title'), t('Type'), t('Author'), t('Status'), t('Operations'));

  $output .= form_render($form['options']);
  if (isset($form['title']) && is_array($form['title'])) {
    foreach (element_children($form['title']) as $key) {
      $row = array();
      $row[] = form_render($form['nodes'][$key]);
      $row[] = form_render($form['title'][$key]);
      $row[] = form_render($form['name'][$key]);
      $row[] = form_render($form['username'][$key]);
      $row[] = form_render($form['status'][$key]);
      $row[] = form_render($form['operations'][$key]);
      $rows[] = $row;
    }

  }
  else  {
    $rows[] = array(array('data' => t('No posts available.'), 'colspan' => '6'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= form_render($form['pager']);
  }

  $output .= form_render($form);

  return $output;
}

function node_multiple_delete_confirm() {
  $edit = $_POST['edit'];

  $form['nodes'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  // array_filter returns only elements with true values
  foreach (array_filter($edit['nodes']) as $nid => $value) {
    $title = db_result(db_query('SELECT title FROM {node} WHERE nid = %d', $nid));
    $form['nodes'][$nid] = array('#type' => 'hidden', '#value' => $nid, '#prefix' => '<li>', '#suffix' => check_plain($title) ."</li>\n");
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');

  return confirm_form('node_multiple_delete_confirm', $form,
                      t('Are you sure you want to delete these items?'),
                      'admin/node', t('This action cannot be undone.'),
                      t('Delete all'), t('Cancel'));
}

function node_multiple_delete_confirm_submit($form_id, $edit) {
  if ($edit['confirm']) {
    foreach ($edit['nodes'] as $nid => $value) {
      node_delete($nid);
    }
    drupal_set_message(t('The items have been deleted.'));
  }
  return 'admin/node';
}

/**
 * Menu callback; presents each node type configuration page.
 */
function node_types_configure($type = NULL) {
  if (isset($type)) {
    $node = new stdClass();
    $node->type = $type;
    $form['submission'] = array('#type' => 'fieldset', '#title' =>t('Submission form') );
    $form['submission'][$type . '_help']  = array(
      '#type' => 'textarea', '#title' => t('Explanation or submission guidelines'), '#default_value' =>  variable_get($type .'_help', ''),
      '#description' => t('This text will be displayed at the top of the %type submission form. It is useful for helping or instructing your users.', array('%type' => node_get_name($type)))
    );
    $form['submission']['minimum_'. $type .'_size'] = array(
      '#type' => 'select', '#title' => t('Minimum number of words'), '#default_value' => variable_get('minimum_'. $type .'_size', 0), '#options' => drupal_map_assoc(array(0, 10, 25, 50, 75, 100, 125, 150, 175, 200)),
      '#description' => t('The minimum number of words a %type must be to be considered valid. This can be useful to rule out submissions that do not meet the site\'s standards, such as short test posts.', array('%type' => node_get_name($type)))
    );
    $form['workflow'] = array('#type' => 'fieldset', '#title' =>t('Workflow'));
    $form['type'] = array('#type' => 'value', '#value' => $type);

    $form['array_filter'] = array('#type' => 'value', '#value' => TRUE);
    return system_settings_form($type .'_node_settings', $form);
  }
  else {
    $header = array(t('Type'), t('Operations'));

    $rows = array();
    foreach (node_get_types() as $type => $name) {
      $rows[] = array($name, l(t('configure'), 'admin/settings/content-types/'. $type));
    }

    return theme('table', $header, $rows);
  }
}

/**
 * Generate an overview table of older revisions of a node.
 */
function node_revision_overview($node) {
  drupal_set_title(t('Revisions for %title', array('%title' => check_plain($node->title))));

  $header = array(t('Revision'), array('data' => t('Operations'), 'colspan' => 2));

  $revisions = node_revision_list($node);

  $rows = array();
  $revert_permission = FALSE;
  if ((user_access('revert revisions') || user_access('administer nodes')) && node_access('update', $node)) {
    $revert_permission = TRUE;
  }
  $delete_permission = FALSE;
  if (user_access('administer nodes')) {
    $delete_permission = TRUE;
  }
  foreach ($revisions as $revision) {
    $row = array();
    $operations = array();

    if ($revision->current_vid > 0) {
      $row[] = array('data' => t('%date by %username', array('%date' => l(format_date($revision->timestamp, 'small'), "node/$node->nid"), '%username' => theme('username', $revision)))
                               . (($revision->log != '') ? '<p class="revision-log">'. filter_xss($revision->log) .'</p>' : ''),
                     'class' => 'revision-current');
      $operations[] = array('data' => theme('placeholder', t('current revision')), 'class' => 'revision-current', 'colspan' => 2);
    }
    else {
      $row[] = t('%date by %username', array('%date' => l(format_date($revision->timestamp, 'small'), "node/$node->nid/revisions/$revision->vid/view"), '%username' => theme('username', $revision)))
               . (($revision->log != '') ? '<p class="revision-log">'. filter_xss($revision->log) .'</p>' : '');
      if ($revert_permission) {
        $operations[] = l(t('revert'), "node/$node->nid/revisions/$revision->vid/revert");
      }
      if ($delete_permission) {
        $operations[] = l(t('delete'), "node/$node->nid/revisions/$revision->vid/delete");
      }
    }
    $rows[] = array_merge($row, $operations);
  }
  $output .= theme('table', $header, $rows);

  return $output;
}

/**
 * Revert to the revision with the specified revision number. A node and nodeapi "update" event is triggered
 * (via the node_save() call) when a revision is reverted.
 */
function node_revision_revert($nid, $revision) {
  global $user;

  $node = node_load($nid, $revision);
  if ((user_access('revert revisions') || user_access('administer nodes')) && node_access('update', $node)) {
    if ($node->vid) {
      $form = array();
      $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
      $form['vid'] = array('#type' => 'value', '#value' => $node->vid);
      return confirm_form('node_revision_revert_confirm', $form, 
                     t('Are you sure you want to revert %title to the revision from %revision-date?', array('%title' => theme('placeholder', $node->title), '%revision-date' => theme('placeholder', format_date($node->revision_timestamp)))),
                     "node/$nid/revisions", ' ', t('Revert'), t('Cancel'));
    }
    else {
      drupal_set_message(t('You tried to revert to an invalid revision.'), 'error');
    }
    drupal_goto('node/'. $nid .'/revisions');
  }
  drupal_access_denied();
}

function node_revision_revert_confirm_submit($form_id, $form_values) {
  $nid = $form_values['nid'];
  $revision = $form_values['vid'];
  $node = node_load($nid, $revision);
  $node->revision = 1;
  $node->log = t('Copy of the revision from %date.', array('%date' => theme('placeholder', format_date($node->revision_timestamp))));
  if (module_exist('taxonomy')) {
    $node->taxonomy = array_keys($node->taxonomy);
  }

  node_save($node);
  drupal_set_message(t('%title has been reverted back to the revision from %revision-date', array('%revision-date' => theme('placeholder', format_date($node->revision_timestamp)), '%title' => theme('placeholder', check_plain($node->title)))));
  watchdog('content', t('%type: reverted %title revision %revision.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $revision))));
  return 'node/'. $nid .'/revisions';  
}

/**
 * Delete the revision with specified revision number. A "delete revision" nodeapi event is invoked when a
 * revision is deleted.
 */
function node_revision_delete($nid, $revision) {
  if (user_access('administer nodes')) {
    $node = node_load($nid);
    if (node_access('delete', $node)) {
      // Don't delete the current revision
      if ($revision != $node->vid) {
        $node = node_load($nid, $revision);
        $form = array();
        $form['nid'] = array('#type' => 'value', '#value' => $nid);
        $form['vid'] = array('#type' => 'value', '#value' => $revision);
        return confirm_form('node_revision_delete_confirm', $form, 
                     t('Are you sure you want to delete %title revision %revision?', array('%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $revision))),
                     "node/$nid/revisions", '', t('Delete'), t('Cancel'));
      }
      else {
        drupal_set_message(t('Deletion failed. You tried to delete the current revision.'));
      }
      if (db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', $nid)) > 1) {
        drupal_goto("node/$nid/revisions");
      }
      else {
        drupal_goto("node/$nid");
      }
    }
  }
  drupal_access_denied();
}

function node_revision_delete_confirm_submit($form_id, $form_values) {
  $node = node_load($form_values['nid'], $form_values['vid']);
  db_query("DELETE FROM {node_revisions} WHERE nid = %d AND vid = %d", $node->nid, $node->vid);
  node_invoke_nodeapi($node, 'delete revision');
  drupal_set_message(t('Deleted %title revision %revision.', array('%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $node->vid))));
  watchdog('content', t('%type: deleted %title revision %revision.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $node->revision))));
 
  if (db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', $node->nid)) > 1) {
    return "node/$node->nid/revisions";
  }
  return "node/$node->nid";
}

/**
 * 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_revisions} 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;
  }

  return $revisions;
}

function node_admin_search() {
  $output = search_form(url('admin/node/search'), $_POST['edit']['keys'], 'node') . search_data($_POST['edit']['keys'], 'node');
  return $output;
}

/**
 * Implementation of hook_block().
 */
function node_block($op = 'list', $delta = 0) {
  if ($op == 'list') {
    $blocks[0]['info'] = t('Syndicate');
    return $blocks;
  }
  else if ($op == 'view') {
    $block['subject'] = t('Syndicate');
    $block['content'] = theme('feed_icon', url('rss.xml'));

    return $block;
  }
}

/**
 * A generic function for generating RSS feeds from a set of nodes.
 *
 * @param $nodes
 *   An object as returned by db_query() which contains the nid field.
 * @param $channel
 *   An associative array containing title, link, description and other keys.
 *   The link should be an absolute URL.
 */
function node_feed($nodes = 0, $channel = array()) {
  global $base_url, $locale;

  if (!$nodes) {
    $nodes = 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));
  }

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

  while ($node = db_fetch_object($nodes)) {
    // Load the specified node:
    $item = node_load($node->nid);
    $link = url("node/$node->nid", NULL, NULL, 1);

    if ($item_length != 'title') {
      $teaser = ($item_length == 'teaser') ? TRUE : FALSE;

      // Filter and prepare node teaser
      if (node_hook($item, 'view')) {
        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
    $extra = node_invoke_nodeapi($item, 'rss item');
    $extra = array_merge($extra, array(array('key' => 'pubDate', 'value' =>  date('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 ($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 ($item->readmore) {
          $item_text .= '<p>'. l(t('read more'), 'node/'. $item->nid, NULL, NULL, NULL, TRUE) .'</p>';
        }
        break;
      case 'title':
        $item_text = '';
        break;
    }

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

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

  $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $output .= "<rss version=\"". $channel["version"] . "\" xml:base=\"". $base_url ."\" ". implode(' ', $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;
}

/**
 * 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;

  // Auto-generate the teaser, but only if it hasn't been set (e.g. by a
  // module-provided 'teaser' form item).
  if (!isset($node->teaser)) {
    $node->teaser = isset($node->body) ? node_teaser($node->body, isset($node->format) ? $node->format : NULL) : '';
  }

  $access = user_access('administer nodes');
  if ($access) {
    // Populate the "authored by" field.
    if ($account = user_load(array('name' => $node->name))) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }

    $node->created = $node->date ? strtotime($node->date) : NULL;
  }
  // Force defaults in case people modify the form:
  $node_options = variable_get('node_options_'. $node->type, array('status', 'promote'));
  foreach (array('status', 'moderate', 'promote', 'sticky', 'revision') as $key) {
    if (!$access || !isset($node->$key)) {
      $node->$key = in_array($key, $node_options);
    }
  }

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

  $node->validated = TRUE;

  return $node;
}

/**
 * Perform validation checks on the given node.
 */
function node_validate($node, $form = array()) {
  // Convert the node to an object, if necessary.
  $node = (object)$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 (isset($node->body) && count(explode(' ', $node->body)) < variable_get('minimum_'. $node->type .'_size', 0)) {
    form_set_error('body', t('The body of your %type is too short. You need at least %words words.', array('%words' => variable_get('minimum_'. $node->type .'_size', 0), '%type' => node_get_name($node))));
  }

  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' => theme('placeholder', $node->name))));
    }

    // Validate the "authored on" field. As of PHP 5.1.0, strtotime returns FALSE instead of -1 upon failure.
    if (!empty($node->date) && strtotime($node->date) <= 0) {
      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);
}

function node_form_validate($form_id, $form_values, $form) {
  node_validate($form_values, $form);
}

function node_object_prepare(&$node) {
  if (user_access('administer nodes')) {
    // Set up default values, if required.
    if (!isset($node->created)) {
      $node->created = time();
    }

    if (!isset($node->date)) {
      $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
    }
  }
  node_invoke($node, 'prepare');
  node_invoke_nodeapi($node, 'prepare');
}

/**
 * Generate the node editing form.
 */
function node_form($node) {
  $node = (object)$node;
  $form = node_form_array($node);
  return drupal_get_form($node->type .'_node_form', $form, 'node_form');
}

/**
* Generate the node editing form array.
*/
function node_form_array($node) {
  node_object_prepare($node);

  // Set the id of the top-level form tag
  $form['#id'] = 'node-form';

  /**
   * Basic node information.
   * These elements are just values so they are not even sent to the client.
   */
  foreach (array('nid', 'vid', 'uid', 'created', 'type') as $key) {
    $form[$key] = array('#type' => 'value', '#value' => $node->$key);
  }

  // Changed must be sent to the client, for later overwrite error checking.
  $form['changed'] = array('#type' => 'hidden', '#default_value' => $node->changed);

  // Get the node-specific bits.
  $form = array_merge_recursive($form, node_invoke($node, 'form'));
  if (!isset($form['title']['#weight'])) {
    $form['title']['#weight'] = -5;
  }

  $node_options = variable_get('node_options_'. $node->type, array('status', 'promote'));
  // If this is a new node, fill in the default values.
  if (!isset($node->nid)) {
    foreach (array('status', 'moderate', 'promote', 'sticky', 'revision') as $key) {
      $node->$key = in_array($key, $node_options);
    }
    global $user;
    $node->uid = $user->uid;
  }
  else {
    // Nodes being edited should always be preset with the default revision setting.
    $node->revision = in_array('revision', $node_options);
  }
  $form['#node'] = $node;

  if (user_access('administer nodes')) {
    // Node author information
    $form['author'] = array('#type' => 'fieldset', '#title' => t('Authoring information'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => 20);
    $form['author']['name'] = array('#type' => 'textfield', '#title' => t('Authored by'), '#maxlength' => 60, '#autocomplete_path' => 'user/autocomplete', '#default_value' => $node->name ? $node->name : '', '#weight' => -1, '#description' => t('Leave blank for %anonymous.', array('%anonymous' => theme('placeholder', variable_get('anonymous', 'Anonymous')))));
    $form['author']['date'] = array('#type' => 'textfield', '#title' => t('Authored on'), '#maxlength' => 25, '#description' => t('Format: %time. Leave blank to use the time of form submission.', array('%time' => $node->date)));

    if (isset($node->nid)) {
      $form['author']['date']['#default_value'] = $node->date;
    }

    // Node options for administrators
    $form['options'] = array('#type' => 'fieldset', '#title' => t('Publishing options'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => 25);
    $form['options']['status']   = array('#type' => 'checkbox', '#title' => t('Published'), '#default_value' => $node->status);
    $form['options']['moderate'] = array('#type' => 'checkbox', '#title' => t('In moderation queue'), '#default_value' => $node->moderate);
    $form['options']['promote']  = array('#type' => 'checkbox', '#title' => t('Promoted to front page'), '#default_value' => $node->promote);
    $form['options']['sticky']   = array('#type' => 'checkbox', '#title' => t('Sticky at top of lists'), '#default_value' => $node->sticky);
    $form['options']['revision'] = array('#type' => 'checkbox', '#title' => t('Create new revision'), '#default_value' => $node->revision);
  }
  else {
    // Put all of these through as values if the user doesn't have access to them.
    foreach (array('uid', 'created') as $key) {
      $form[$key] = array('#type' => 'value', '#value' => $node->$key);
    }
  }

  // Add the buttons.
  $form['preview'] = array('#type' => 'button', '#value' => t('Preview'), '#weight' => 40);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'), '#weight' => 45);
  if ($node->nid && node_access('delete', $node)) {
    $form['delete'] = array('#type' => 'button', '#value' => t('Delete'), '#weight' => 50);
  }

  $form['#after_build'] = array('node_form_add_preview');

  return $form;
}

function node_form_add_preview($form) {
  global $form_values;

  $op = isset($_POST['op']) ? $_POST['op'] : '';
  if ($op == t('Preview')) {
    // Invoke full validation for the form, to protect against cross site
    // request forgeries (CSRF) and setting arbitrary values for fields such as
    // the input format. Preview the node only when form validation does not
    // set any errors.
    drupal_validate_form($form['form_id']['#value'], $form);
    if (!form_get_errors()) {
      // Because the node preview may display a form, we must render it
      // outside the node submission form tags using the #prefix property
      // (i.e. to prevent illegally nested forms).
      // If the node form already has a #prefix, we must preserve it.
      // In this case, we put the preview before the #prefix so we keep
      // the #prefix as "close" to the rest of the form as possible,
      // for example, to keep a <div> only around the form, not the
      // preview. We pass the global $form_values here to preserve
      // changes made during form validation.
      $preview = node_preview((object)$form_values);
      $form['#prefix'] = isset($form['#prefix']) ? $preview . $form['#prefix'] : $preview;
    }
  }
  if (variable_get('node_preview', 0) && (form_get_errors() || $op != t('Preview'))) {
    unset($form['submit']);
  }
  return $form;
}

function theme_node_form($form) {
  $output = "\n<div class=\"node-form\">\n";

  // Admin form fields and submit buttons must be rendered first, because
  // they need to go to the bottom of the form, and so should not be part of
  // the catch-all call to form_render().
  $admin = '';
  if (isset($form['author'])) {
    $admin .= "    <div class=\"authored\">\n";
    $admin .= form_render($form['author']);
    $admin .= "    </div>\n";
  }
  if (isset($form['options'])) {
    $admin .= "    <div class=\"options\">\n";
    $admin .= form_render($form['options']);
    $admin .= "    </div>\n";
  }
  $buttons = form_render($form['preview']);
  $buttons .= form_render($form['submit']);
  $buttons .= isset($form['delete']) ? form_render($form['delete']) : '';

  // Everything else gets rendered here, and is displayed before the admin form
  // field and the submit buttons.
  $output .= "  <div class=\"standard\">\n";
  $output .= form_render($form);
  $output .= "  </div>\n";

  if (!empty($admin)) {
    $output .= "  <div class=\"admin\">\n";
    $output .= $admin;
    $output .= "  </div>\n";
  }
  $output .= $buttons;
  $output .= "</div>\n";

  return $output;
}

/**
 * Present a node submission form or a set of links to such forms.
 */
function node_add($type) {
  global $user;

  // If a node type has been specified, validate its existence.
  if (array_key_exists($type, node_get_types()) && node_access('create', $type)) {
    // Initialize settings:
    $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $type);

    $output = node_form($node);
    drupal_set_title(t('Submit %name', array('%name' => node_get_name($node))));
  }
  else {
    // If no (valid) node type has been provided, display a node type overview.
    foreach (node_get_types() as $type => $name) {
      if (node_access('create', $type)) {
        $out = '<dt>'. l($name, "node/add/$type", array('title' => t('Add a new %s.', array('%s' => $name)))) .'</dt>';
        $out .= '<dd>'. implode("\n", module_invoke_all('help', 'node/add#'. $type)) .'</dd>';
        $item[$name] = $out;
      }
    }

    if (isset($item)) {
      uksort($item, 'strnatcasecmp');
      $output = t('Choose the appropriate item from the list:') .'<dl>'. implode('', $item) .'</dl>';
    }
    else {
      $output = t('You are not allowed to create content.');
    }
  }

  return $output;
}

/**
 * Generate a node preview.
 */
function node_preview($node) {
  if (node_access('create', $node) || node_access('update', $node)) {
    // Load the user's name when needed:
    if (isset($node->name)) {
      // The use of isset() is mandatory in the context of user IDs, because
      // user ID 0 denotes the anonymous user.
      if ($user = user_load(array('name' => $node->name))) {
        $node->uid = $user->uid;
        $node->picture = $user->picture;
      }
      else {
        $node->uid = 0; // anonymous user
      }
    }
    else if ($node->uid) {
      $user = user_load(array('uid' => $node->uid));
      $node->name = $user->name;
      $node->picture = $user->picture;
    }

    // Set the timestamps when needed:
    if ($node->date) {
      $node->created = strtotime($node->date);
    }
    $node->changed = time();

    // Extract a teaser, if it hasn't been set (e.g. by a module-provided
    // 'teaser' form item).
    if (!isset($node->teaser)) {
      $node->teaser = node_teaser($node->body, $node->format);
    }

    // Display a preview of the node:
    // Previewing alters $node so it needs to be cloned.
    if (!form_get_errors()) {
      $cloned_node = drupal_clone($node);
      $cloned_node->in_preview = TRUE;
      $output = theme('node_preview', $cloned_node);
    }
    drupal_set_title(t('Preview'));
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('create content'), 'node/add'), l(t('Submit %name', array('%name' => node_get_name($node))), 'node/add/'. $node->type)));

    return $output;
  }
}

/**
 * Display a node preview for display during node creation and editing.
 *
 * @param $node
 *   The node object which is being previewed.
 */
function theme_node_preview($node) {
  $output = '<div class="preview">';
  if ($node->teaser && $node->teaser != $node->body) {
    drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "&lt;!--break--&gt;" (without the quotes) to fine-tune where your post gets split.'));
    $output .= '<h3>'. t('Preview trimmed version') .'</h3>';
    $output .= node_view(drupal_clone($node), 1, FALSE, 0);
    $output .= '<h3>'. t('Preview full version') .'</h3>';
    $output .= node_view($node, 0, FALSE, 0);
  }
  else {
    $output .= node_view($node, 0, FALSE, 0);
  }
  $output .= "</div>\n";

  return $output;
}

function node_form_submit($form_id, $edit) {
  global $user;

  // Fix up the node when required:
  $node = node_submit($edit);

  // Prepare the node's body:
  if ($node->nid) {
    // Check whether the current user has the proper access rights to
    // perform this operation:
    $original_node = node_load($node->nid); //check access rights using the unmodified node
    if (node_access('update', $original_node)) {
      node_save($node);
      watchdog('content', t('%type: updated %title.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), 'node/'. $node->nid));
      drupal_set_message(t('The %post was updated.', array ('%post' => node_get_name($node))));
    }
  }
  else {
    // Check whether the current user has the proper access rights to
    // perform this operation:
    if (node_access('create', $node)) {
      node_save($node);
      watchdog('content', t('%type: added %title.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), "node/$node->nid"));
      drupal_set_message(t('Your %post was created.', array ('%post' => node_get_name($node))));
    }
  }
  if ($node->nid) {
    if (node_access('view', $node)) {
      return 'node/'. $node->nid;
    }
    else {
      return '';
    }
  }
  // it is very unlikely we get here
  return FALSE;
}

/**
 * Menu callback -- ask for confirmation of node deletion
 */
function node_delete_confirm() {
  $edit = $_POST['edit'];
  $edit['nid'] = $edit['nid'] ? $edit['nid'] : arg(1);
  $node = node_load($edit['nid']);

  if (node_access('delete', $node)) {
    $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
    $output = confirm_form('node_delete_confirm', $form,
                   t('Are you sure you want to delete %title?', array('%title' => theme('placeholder', $node->title))),
                   $_GET['destination'] ? $_GET['destination'] : 'node/'. $node->nid, t('This action cannot be undone.'),
                   t('Delete'), t('Cancel')  );
  }

  return $output;
}

/**
 * Execute node deletion
 */
function node_delete_confirm_submit($form_id, $form_values) {
  if ($form_values['confirm']) {
    node_delete($form_values['nid']);
  }

  return '';
}

/**
 * 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_revisions} WHERE nid = %d', $node->nid);

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

    // Clear the cache so an anonymous poster can see the node being deleted.
    cache_clear_all();

    // Remove this node from the search index if needed.
    if (function_exists('search_wipe')) {
      search_wipe($node->nid, 'node');
    }
    drupal_set_message(t('%title has been deleted.', array('%title' => theme('placeholder', $node->title))));
    watchdog('content', t('%type: deleted %title.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title))));
  }
}

/**
 * Menu callback for revisions related activities.
 */
function node_revisions() {
  if (is_numeric(arg(1)) && arg(2) == 'revisions') {
    $op = arg(4) ? arg(4) : 'overview';
    switch ($op) {
      case 'overview':
        $node = node_load(arg(1));
        if ((user_access('view revisions') || user_access('administer nodes')) && node_access('view', $node)) {
          return node_revision_overview($node);
        }
        drupal_access_denied();
        return;
      case 'view':
        if (is_numeric(arg(3))) {
          $node = node_load(arg(1), arg(3));
          if ($node->nid) {
            if ((user_access('view revisions') || user_access('administer nodes')) && node_access('view', $node)) {
              drupal_set_title(t('Revision of %title from %date', array('%title' => theme('placeholder', $node->title), '%date' => format_date($node->revision_timestamp))));
              return node_show($node, arg(2));
            }
            drupal_access_denied();
            return;
          }
        }
        break;
      case 'revert':
        return node_revision_revert(arg(1), arg(3));
        break;
      case 'delete':
        return node_revision_delete(arg(1), arg(3));
        break;
    }
  }
  drupal_not_found();
}

/**
 * Generate a listing of promoted nodes.
 */
function node_page_default() {
  $result = pager_query(db_rewrite_sql('SELECT n.nid, n.sticky, n.created 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));

  if (db_num_rows($result)) {
    drupal_add_link(array('rel' => 'alternate',
                          'type' => 'application/rss+xml',
                          'title' => t('RSS'),
                          'href' => url('rss.xml', NULL, NULL, TRUE)));

    $output = '';
    while ($node = db_fetch_object($result)) {
      $output .= node_view(node_load($node->nid), 1);
    }
    $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
  }
  else {
    $output = t('
      <h1 class="title">Welcome to your new Drupal website!</h1>
      <p>Please follow these steps to set up and start using your website:</p>
      <ol>
        <li>
          <strong>Create your administrator account</strong>
          To begin, <a href="%register">create the first account</a>. This account will have full administration rights and will allow you to configure your website.
        </li>
        <li>
          <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.
        </li>
        <li>
          <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>.
        </li>
        <li>
          <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>.
        </li>
        <li>
          <strong>Start posting content</strong>
          Finally, you can <a href="%content">create content</a> for your website. This message will disappear once you have published your first post.
        </li>
      </ol>
      <p>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.</p>',
      array('%drupal' => 'http://drupal.org/', '%register' => url('user/register'), '%admin' => url('admin'), '%config' => url('admin/settings'), '%modules' => url('admin/modules'), '%download_modules' => 'http://drupal.org/project/modules', '%themes' => url('admin/themes'), '%download_themes' => 'http://drupal.org/project/themes', '%content' => url('node/add'), '%help' => url('admin/help'), '%handbook' => 'http://drupal.org/handbooks', '%forum' => 'http://drupal.org/forum', '%support' => 'http://drupal.org/support')
    );
    $output = '<div id="first-time">'. $output .'</div>';
  }

  return $output;
}

/**
 * Menu callback; dispatches control to the appropriate operation handler.
 */
function node_page() {
  $op = arg(1);

  if (is_numeric($op)) {
    $op = (arg(2) && !is_numeric(arg(2))) ? arg(2) : 'view';
  }

  switch ($op) {
    case 'view':
      if (is_numeric(arg(1))) {
        $node = node_load(arg(1));
        if ($node->nid) {
          drupal_set_title(check_plain($node->title));
          return node_show($node, arg(2));
        }
        else if (db_result(db_query('SELECT nid FROM {node} WHERE nid = %d', arg(1)))) {
          drupal_access_denied();
        }
        else {
          drupal_not_found();
        }
      }
      break;
    case 'add':
      return node_add(arg(2));
      break;
    case 'edit':
      if ($_POST['op'] == t('Delete')) {
        // Note: we redirect from node/uid/edit to node/uid/delete to make the tabs disappear.
        if ($_REQUEST['destination']) {
          $destination = drupal_get_destination();
          unset($_REQUEST['destination']);
        }
        drupal_goto('node/'. arg(1) .'/delete', $destination);
      }

      if (is_numeric(arg(1))) {
        $node = node_load(arg(1));
        if ($node->nid) {
          drupal_set_title(check_plain($node->title));
          return node_form($node);
        }
        else if (db_result(db_query('SELECT nid FROM {node} WHERE nid = %d', arg(1)))) {
          drupal_access_denied();
        }
        else {
          drupal_not_found();
        }
      }
      break;
    default:
      drupal_set_title('');
      return node_page_default();
  }
}

/**
 * shutdown function to make sure we always mark the last node processed.
 */
function node_update_shutdown() {
  global $last_change, $last_nid;

  if ($last_change && $last_nid) {
    variable_set('node_cron_last', $last_change);
    variable_set('node_cron_last_nid', $last_nid);
  }
}

/**
 * Implementation of hook_update_index().
 */
function node_update_index() {
  global $last_change, $last_nid;

  register_shutdown_function('node_update_shutdown');

  $last = variable_get('node_cron_last', 0);
  $last_nid = variable_get('node_cron_last_nid', 0);
  $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 GREATEST(IF(c.last_comment_timestamp IS NULL, 0, c.last_comment_timestamp), n.changed) as last_change, n.nid FROM {node} n LEFT JOIN {node_comment_statistics} c ON n.nid = c.nid WHERE n.status = 1 AND ((GREATEST(n.changed, c.last_comment_timestamp) = %d AND n.nid > %d) OR (n.changed > %d OR c.last_comment_timestamp > %d)) ORDER BY GREATEST(n.changed, c.last_comment_timestamp) ASC, n.nid ASC', $last, $last_nid, $last, $last, $last, 0, $limit);

  while ($node = db_fetch_object($result)) {
    $last_change = $node->last_change;
    $last_nid = $node->nid;
    $node = node_load($node->nid);

    // Get node output (filtered and with module-specific fields).
    if (node_hook($node, 'view')) {
      node_invoke($node, 'view', false, false);
    }
    else {
      $node = node_prepare($node, false);
    }
    // Allow modules to change $node->body before viewing.
    node_invoke_nodeapi($node, 'view', false, false);

    $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_id, &$form) {
  // Node publishing options
  if (isset($form['type']) && $form['type']['#value'] .'_node_settings' == $form_id) {
    $form['workflow']['node_options_'. $form['type']['#value']] = array('#type' => 'checkboxes',
      '#title' => t('Default options'),
      '#default_value' => variable_get('node_options_'. $form['type']['#value'], array('status', 'promote')),
      '#options' => array(
        'status' => t('Published'),
        'moderate' => t('In moderation queue'),
        'promote' => t('Promoted to front page'),
        'sticky' => t('Sticky at top of lists'),
        'revision' => t('Create new revision'),
      ),
      '#description' => t('Users with the <em>administer nodes</em> permission will be able to override these options.'),
    );
  }

  // Advanced node search form
  elseif ($form_id == 'search_form' && arg(1) == 'node') {
    // 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']['category'] = array(
        '#type' => 'select',
        '#title' => t('Only in the category(s)'),
        '#prefix' => '<div class="criterion">',
        '#size' => 10,
        '#suffix' => '</div>',
        '#options' => $taxonomy,
        '#multiple' => TRUE,
      );
    }

    // Node types:
    $types = node_get_types();
    $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><br class="clear" />',
    );

    $form['#validate']['node_search_validate'] = array();
  }
}

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

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

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

/**
 * @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 $uid
 *   The user ID on which the operation is to be performed.
 * @return
 *   TRUE if the operation may be performed.
 */
function node_access($op, $node = NULL, $uid = NULL) {
  // Convert the node to an object if necessary:
  if ($op != 'create') {
    $node = (object)$node;
  }
  // If the node is in a restricted format, disallow editing.
  if ($op == 'update' && !filter_access($node->format)) {
    return FALSE;
  }

  if (user_access('administer nodes')) {
    return TRUE;
  }

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

  // Can't use node_invoke(), because the access hook takes the $op parameter
  // before the $node parameter.
  $access = module_invoke(node_get_base($node), 'access', $op, $node);
  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, $uid) 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));
  }
  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('administer nodes')) {
    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.
 * @return
 *   An SQL where clause.
 */
function _node_access_where_sql($op = 'view', $node_access_alias = 'na', $uid = NULL) {
  if (user_access('administer nodes')) {
    return;
  }

  $grants = array();
  foreach (node_access_grants($op, $uid) 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 $uid
 *   The user ID 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, $uid = NULL) {
  global $user;

  if (isset($uid)) {
    $user_object = user_load(array('uid' => $uid));
  }
  else {
    $user_object = $user;
  }

  return array_merge(array('all' => array(0)), module_invoke_all('node_grants', $user_object, $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;
  }
}

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