summaryrefslogtreecommitdiffstats
path: root/workbench_moderation.module
blob: 3370981e2d86d6bbf91be879dbd75942b9b68e49 (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
<?php

/**
 * @file
 * Content moderation for Workbench.
 *
 * Based on content_moderation.module by eugenmayer.
 * Base version 1.12.2.17 2010/04/18 11:31:29.
 */

/**
 * Implements hook_menu().
 */
function workbench_moderation_menu() {
  $items = array();

  // Display a node's moderation history
  $items["node/%node/moderation"] = array(
    'title' => 'Moderate',
    'description' => 'Show the content moderation history.',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'workbench_moderation_node_history_view',
    'page arguments' => array(1),
    'access callback' => '_workbench_moderation_access',
    'access arguments' => array('view history', 1),
    'file' => 'workbench_moderation.node.inc'
  );

  // Unpublishing a live revision.
  $items["node/%node/moderation/%/unpublish"] = array(
    'title' => 'Unpublish revision',
    'description' => 'Unpublish the current live revision.',
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('workbench_moderation_node_unpublish_form', 1),
    'load arguments' => array(3),
    'access callback' => '_workbench_moderation_access',
    'access arguments' => array('unpublish', 1),
    'file' => 'workbench_moderation.node.inc'
  );

  // Change the moderation state of a node.
  // Used in workbench_moderation_get_moderation_links()
  $items["node/%node/moderation/%/change-state/%"] = array(
    'title' => 'Change moderation state',
    'page callback' => 'workbench_moderation_moderate_callback',
    'page arguments' => array(1, 5),
    'load arguments' => array(3),
    'access callback' => '_workbench_moderation_moderate_access',
    'access arguments' => array(1, 5),
    'type' => MENU_CALLBACK,
  );

  $items['node/%node/moderation/view'] = array(
    'title' => 'Revisions',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -1,
  );

  // View the current revision of a node. Redirects to node/%node if the current revision is
  // published, and to node/%node/draft if the current revision is a draft.
  $items["node/%node/current-revision"] = array(
    'page callback' => 'workbench_moderation_node_current_view',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'file' => 'workbench_moderation.node.inc',
  );

  // View the current draft of a node.
  $items["node/%node/draft"] = array(
    'title' => 'View draft',
    'page callback' => 'workbench_moderation_node_view_draft',
    'page arguments' => array(1),
    'access callback' => '_workbench_moderation_access_current_draft',
    'access arguments' => array(1),
    'file' => 'workbench_moderation.node.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
  );

  // Module settings.
  $items["admin/config/workbench/moderation"] = array(
    'title' => 'Workbench Moderation',
    'description' => 'Configure content moderation.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('workbench_moderation_admin_states_form'),
    'access arguments' => array('administer workbench moderation'),
    'file' => 'workbench_moderation.admin.inc',
  );
  $items['admin/config/workbench/moderation/general'] = array(
    'title' => 'States',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -1,
  );
  $items['admin/config/workbench/moderation/transitions'] = array(
    'title' => 'Transitions',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('workbench_moderation_admin_transitions_form'),
    'access arguments' => array('administer workbench moderation'),
    'file' => 'workbench_moderation.admin.inc',
  );
  $items['admin/config/workbench/moderation/check-permissions'] = array(
    'title' => 'Check permissions',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('workbench_moderation_admin_check_role_form'),
    'access arguments' => array('administer workbench moderation'),
    'file' => 'workbench_moderation.admin.inc',
    'weight' => 10,
  );

  // If the diff module is present, replicate its pages under the moderation tab.
  if (module_exists('diff')) {
    $diff_menu_items  = diff_menu();

    $items['node/%node/moderation/diff'] = array(
      'type' => MENU_LOCAL_TASK,
      'file path' => drupal_get_path('module', 'diff'),
      'title' => 'Compare revisions',
      'page arguments' => array(1),
    );

    $items['node/%node/moderation/diff'] += $diff_menu_items['node/%node/revisions/list'];


    $items['node/%node/moderation/diff/list'] = array(
      'title' => 'Compare revisions',
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'weight' => -1,
    );

    $items['node/%node/moderation/diff/view'] = array(
      'page arguments' => array(1, 5, 6),
      'tab_parent' => 'node/%/moderation/diff/list',
      'file path' => drupal_get_path('module', 'diff'),
    );

    $items['node/%node/moderation/diff/view'] += $diff_menu_items['node/%node/revisions/view'];
  }

  return $items;
}


/**
 * Implements hook_form_FORM_ID_alter.
 */
function workbench_moderation_form_diff_node_revisions_alter(&$form, &$form_state, $form_id) {

  // If this form is appearing under moderation then add a submit function
  // that will keep the user in the moderation tab.
  if (arg(2) == 'moderation') {
    $form['#submit'][] = 'workbench_moderation_diff_node_revisions_submit';
  }
}

/**
 * Redirects the the diff_node_revisions form when the user is under the moderation tab.
 */
function workbench_moderation_diff_node_revisions_submit($form, &$form_state) {

  // the ids are ordered so the old revision is always on the left
  $old_vid = min($form_state['values']['old'], $form_state['values']['new']);
  $new_vid = max($form_state['values']['old'], $form_state['values']['new']);
  $form_state['redirect'] =  'node/'. $form_state['values']['nid'] .'/moderation/diff/view/'. $old_vid .'/'. $new_vid;
}

/**
 * Implements hook_menu_alter().
 */
function workbench_moderation_menu_alter(&$items) {
  // Hijack the node/X/edit page to ensure that the right revision (most current) is displayed.
  $items['node/%node/edit']['page callback'] = 'workbench_moderation_node_edit_page_override';

  // Override the node edit menu item title.
  $items['node/%node/edit']['title callback'] = 'workbench_moderation_edit_tab_title';
  $items['node/%node/edit']['title arguments'] = array(1);

  // Override the node view menu item title.
  $items['node/%node/view']['title callback'] = 'workbench_moderation_view_tab_title';
  $items['node/%node/view']['title arguments'] = array(1);

  // Redirect node/%node/revisions
  $items['node/%node/revisions']['page callback'] = 'workbench_moderation_node_revisions_redirect';
  $items['node/%node/revisions']['page arguments'] = array(1);

  // Override the node revision view callback.
 $items['node/%node/revisions/%/view']['page callback'] = 'workbench_moderation_node_view_revision';
 $items['node/%node/revisions/%/view']['file path'] = drupal_get_path('module', 'workbench_moderation');
 $items['node/%node/revisions/%/view']['file'] = 'workbench_moderation.node.inc';


  // For revert and delete operations, use our own access check.
  $items['node/%node/revisions/%/revert']['access callback'] = '_workbench_moderation_revision_access';
  $items['node/%node/revisions/%/delete']['access callback'] = '_workbench_moderation_revision_access';

  // Provide a container administration menu item, if one doesn't already exist.
  if (!isset($items['admin/config/workbench'])) {
    $items['admin/config/workbench'] = array(
      'title' => 'Workbench',
      'description' => 'Workbench',
      'page callback' => 'system_admin_menu_block_page',
      'access arguments' => array('administer site configuration'),
      'position' => 'right',
      'file' => 'system.admin.inc',
      'file path' => drupal_get_path('module', 'system'),
    );
  }
}

/**
 * Redirects 'node/%node/revisions' to node/%node/moderation
 *
 * workbench_moderation_menu_alter() changes the page callback
 * for 'node/%node/revisions' to this function
 *
 * @param $node
 *   The node being acted upon.
 */
function workbench_moderation_node_revisions_redirect($node) {
  // Redirect node types subject to moderation.
  if (workbench_moderation_node_type_moderated($node->type) === TRUE) {
    drupal_goto('node/' . $node->nid . '/moderation');
  }
  // Return the normal node revisions page for unmoderated types.
  else {

    if (module_exists('diff')) {
      return diff_diffs_overview($node);
    }
    else {
      return node_revision_overview($node);
    }
  }
}

/**
 * Implements hook_menu_local_tasks_alter().
 *
 * Hide the node revisions tab conditionally.
 *
 * Check if the node type is subject to moderation. If so, unset the revision
 * tab. This step is necessary because hook_menu_alter cannot change the menu
 * item type on a node type by node type basis for node/%node/revision.
 *
 * Additionally, workbench_menu_alter() is used to change the page callback
 * for node/%node/revisions so that this URL redirects to node/%node/moderation
 * for node types subject to moderation.
 */
function workbench_moderation_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Do we need to bother doing anything?
  if (empty($data['tabs'][0]['output'])) {
    return;
  }

  // Check the path.
  $arg = arg(0, $root_path);
  $arg1 = arg(1, $root_path);
  if ($arg != 'node' || $arg1 != '%') {
    return;
  }

  // Get the node for the current menu router.
  if ($node = menu_get_object()) {
    // Here is the reason this hook implementation exists:
    // If this is a node type that gets moderated, don't show 'node/%/revisions'
    if (workbench_moderation_node_type_moderated($node->type) === TRUE) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        if (!empty($value['#link']['path']) && $value['#link']['path'] == 'node/%/revisions') {
          unset($data['tabs'][0]['output'][$key]);
          break;
        }
      }
    }
  }
}

/**
 * Change the name of the node edit tab, conditionally.
 *
 * - Don't change the title if the content is not under moderation.
 *
 * - If a piece of content has a published revision and the published revision
 *   is also the current moderation revision, the "Edit" tab should be titled
 *   "Create draft".
 *
 * - If a piece of content has a published revision and the current moderation
 *   revision is a newer, or if the content has no published revision, the
 *   "Edit" tab should be titled "Edit draft".
 *
 * @param $node
 *   The node being acted upon.
 *
 * @return
 *   The title for the tab.
 */
function workbench_moderation_edit_tab_title($node) {
  // Use the normal tab title if the node type is not under moderation.
  if (!workbench_moderation_node_type_moderated($node->type)) {
    return t('Edit');
  }

  // Is the latest draft published?
  $state = $node->workbench_moderation;
  if (!empty($state['published']) && $state['published']->vid == $state['current']->vid) {
    return t('New draft');
  }

  // The latest draft is not published.
  return t('Edit draft');
}

/**
 * Change the name of the node view tab, conditionally.
 *
 * - Don't change the title if the content is not under moderation.
 *
 * - If a piece of content has a published revision, the "View" tab should be
 *   titled "View published".
 *
 * - Otherwise, it should be titled "View draft".
 *
 * @param $node
 *   The node being acted upon.
 *
 * @return
 *   The title for the tab.
 */
function workbench_moderation_view_tab_title($node) {
  // Use the normal tab title if the node type is not under moderation.
  if (!workbench_moderation_node_type_moderated($node->type)) {
    return t('View');
  }

  // Is there a published revision?
  $state = $node->workbench_moderation;
  if (!empty($state['published'])) {
    return t('View published');
  }
  return t('View draft');
}


/**
 * Implements hook_admin_paths().
 */
function workbench_moderation_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/moderation' => TRUE,
    );
    return $paths;
  }
}

/**
 * Implements hook_theme().
 */
function workbench_moderation_theme() {
  return array(
    'workbench_moderation_admin_states_form' => array(
      'file' => 'workbench_moderation.admin.inc',
      'render element' => 'form',
    ),
    'workbench_moderation_admin_transitions_form' => array(
      'file' => 'workbench_moderation.admin.inc',
      'render element' => 'form',
    ),
  );
}

/**
 * Implements hook_permission().
 *
 * Provides permissions for each state to state change.
 */
function workbench_moderation_permission() {
  $permissions = array();
  $permissions['view all unpublished content'] = array(
    'title' => t('View all unpublished content'),
  );
  $permissions['administer workbench moderation'] = array(
    'title' => t('Administer Workbench Moderation'),
  );
  $permissions['bypass workbench moderation'] = array(
    'title' => t('Bypass moderation restrictions'),
    'restrict access' => TRUE,
  );
  $permissions['view moderation history'] = array(
    'title' => t('View moderation history'),
  );
  $permissions['view moderation messages'] = array(
    'title' => t('View the moderation messages on a node')
  );
  $permissions['use workbench_moderation my drafts tab'] = array(
    'title' => t('Use "My drafts" workbench tab')
  );
  $permissions['use workbench_moderation needs review tab'] = array(
    'title' => t('Use "Needs review" workbench tab')
  );

  // Per-node-type, per-transition permissions. Used by workbench_moderation_state_allowed().
  $node_types = workbench_moderation_moderate_node_types();
  $transitions = workbench_moderation_transitions();

  foreach ($transitions as $transition) {
    $from_state = $transition->from_name;
    $to_state = $transition->to_name;

    // Always set a permission to perform all moderation states.
    $permissions["moderate content from $from_state to $to_state"] = array(
      'title' => t('Moderate all content from %from_state to %to_state', array('%from_state' => workbench_moderation_state_label($from_state), '%to_state' => workbench_moderation_state_label($to_state))),
    );
    // Per-node type permissions are very complex, and should only be used if
    // absolutely needed. For right now, this is hardcoded to OFF. To enable it,
    // Add this line to settings.php and then reset permissions.
    //   $conf['workbench_moderation_per_node_type'] = TRUE;
    if (variable_get('workbench_moderation_per_node_type', FALSE)) {
      foreach ($node_types as $node_type) {
        $permissions["moderate $node_type state from $from_state to $to_state"] = array(
          'title' => t('Moderate %node_type state from %from_state to %to_state', array('%node_type' => node_type_get_name($node_type), '%from_state' => workbench_moderation_state_label($from_state), '%to_state' => workbench_moderation_state_label($to_state))),
        );
      }
    }
  }
  return $permissions;
}

/**
 * Implements hook_node_access().
 *
 * Allows users with the 'view all unpublished content' permission to do so.
 */
function workbench_moderation_node_access($node, $op, $account) {
  if ($op == 'view' && !$node->status && user_access('view all unpublished content', $account)) {
    return NODE_ACCESS_ALLOW;
  }
  return NODE_ACCESS_IGNORE;
}

/**
 * Custom access handler for node operations.
 *
 * @param $op
 *   The operation being requested.
 * @param $node
 *   The node being acted upon.
 *
 * @return
 *   Boolean TRUE or FALSE.
 */
function _workbench_moderation_access($op, $node) {
  global $user;

  // If we do not control this node type, deny access.
  if (workbench_moderation_node_type_moderated($node->type) === FALSE) {
    return FALSE;
  }

  $access = TRUE;

  // The user must be able to view the moderation history.
  $access &= user_access('view moderation history');

  // The user must be able to edit this node.
  $access &= node_access('update', $node);

  if ($op == 'unpublish') {
    // workbench_moderation_states_next() checks transition permissions.
    $next_states = workbench_moderation_states_next(workbench_moderation_state_published(), $user, $node);
    $access &= !empty($next_states);
  }

  // Allow other modules to change our rule set.
  drupal_alter('workbench_moderation_access', $access, $op, $node);

  return $access;
}

/**
 * Wrapper for the 'revert' and 'delete' operations of _node_revision_access().
 *
 * Drupal core's "current revision" of a node is the version in {node}; for
 * Workbench Moderation, latest revision in {node_revision} is the current
 * revision. For nodes with a published revision, Workbench Moderation keeps
 * that revision in {node}, whether or not it is the current revision.
 */
function _workbench_moderation_revision_access($node, $op) {
  // Normal behavior for unmoderated nodes.
  if (!workbench_moderation_node_type_moderated($node->type)) {
    return _node_revision_access($node, $op);
  }

  // Prevent reverting to or deleting the current revision.
  if ($node->workbench_moderation['current']->vid == $node->workbench_moderation['my_revision']->vid) {
    return FALSE;
  }

  // Temporarily give the node an impossible revision.
  // _node_revision_access() keeps access check results in a static variable
  // indexed by revision only, not by op. Thus, subsequent checks on the same
  // vid for different ops yield the same result, regardless of permissions.
  // Setting a fake vid here allows us to store different static results per op.
  $tmp = $node->vid;
  switch ($op) {
    case 'update':
      $node->vid = -1;
      break;
    case 'delete':
      $node->vid = -2;
      break;
  }

  // Check access.
  $access = _node_revision_access($node, $op);

  // Restore the original revision id.
  $node->vid = $tmp;
  return $access;
}

/**
 * Checks if a user may make a particular transition on a node.
 *
 * @param $node
 *   The node being acted upon.
 * @param $state
 *   The new moderation state.
 *
 * @return
 *   Booelan TRUE or FALSE.
 */
function _workbench_moderation_moderate_access($node, $state) {
  global $user;

  $my_revision = $node->workbench_moderation['my_revision'];
  $next_states = workbench_moderation_states_next($my_revision->state, $user, $node);
  $access = node_access('update', $node, $user)       // the user can edit the node
          && $my_revision->current                    // this is the current revision (no branching the revision history)
          && (!empty($next_states))                   // there are next states the user may transition to
          && isset($next_states[$state]);             // this state is in the available next states

  // Allow other modules to change our rule set.
  $op = 'moderate';
  drupal_alter('workbench_moderation_access', $access, $op, $node);

  return $access;
}

/**
 * Checks if the user can view the current node revision.
 *
 * This is the access callback for node/%node/draft as defined in
 * workbench_moderation_menu().
 *
 * @param $node
 *   The node being acted upon.
 *
 * @return
 *   Booelan TRUE or FALSE.
 */
function _workbench_moderation_access_current_draft($node) {

  // This tab should only appear for node types under moderation
  if (!workbench_moderation_node_type_moderated($node->type)) {
    return FALSE;
  }

  $state = $node->workbench_moderation;
  return (_workbench_moderation_access('view revisions', $node)
      && !empty($state['published'])
      && $state['published']->vid != $state['current']->vid);
}

/**
 * Implements hook_help().
 */
function workbench_moderation_help($path, $arg) {
  switch ($path) {
    case 'admin/help#workbench_moderation':
      return '<p>' . t("Enables you to control node display with a moderation workflow. You can have a 'Live revision' for all visitors and pending revisions which need to be approved to become the new 'Live revision.'") . '</p>';

    case 'admin/config/workbench/moderation':
      return '<p>' . t("These are the states through which a node passes in order to become published. By default, the Workbench Moderation module provides the states 'Draft,' 'Needs review,' and 'Published'. On this screen you may create, delete and re-order states. Additional states might include 'Legal review,' 'PR review', or any or state your site may need.") . '</p>';

    case 'admin/config/workbench/moderation/transitions':
      return '<p>' . t('The Workbench Moderation module keeps track of when a node moves from one state to another. By default, nodes begin in the %draft state and end in the %published state. The transitions on this page control how nodes move from state to state. <a href="@permissions">Permission to perform these transitions is controlled on a role-by-role basis</a>.', array('%draft' => workbench_moderation_state_label(workbench_moderation_state_none()), '%published' => workbench_moderation_state_label(workbench_moderation_state_published()), '@permissions' => url('admin/people/permissions', array('fragment' => 'module-workbench_moderation')))) . '</p>';

    case 'admin/config/workbench/moderation/check-permissions':
      return '<p>' . t("In order to participate in the moderation process, Drupal users must be granted several node- and moderation- related permissions. This page can help check whether roles have the correct permissions to author, edit, moderate, and publish moderated content.") . '</p>';
  }
}

/**
 * Implements hook_views_api().
 */
function workbench_moderation_views_api() {
  return array('api' => 2.0);
}

/**
 * Implements hook_views_default_views().
 */
function workbench_moderation_views_default_views() {
  $module = 'workbench_moderation';
  $directory = 'views';
  $extension = 'view.inc';
  $name = 'view';

  // From workbench_load_all_exports().
  $return = array();
  // Find all the files in the directory with the correct extension.
  $files = file_scan_directory(drupal_get_path('module', $module) . "/$directory", "/.$extension/");
  foreach ($files as $path => $file) {
    require $path;
    if (isset($$name)) {
      $return[$$name->name] = $$name;
    }
  }

  return $return;
}


/**
 * Implements hook_node_presave().
 *
 * Ensure that a node in moderation has the proper publication status.
 * We set $node->status = 0 (unpublished) if this is a new node which has not
 * been marked as published, or if the node has no published revision.
 */
function workbench_moderation_node_presave($node) {
  global $user;
  if (isset($node->workbench_moderation_state_new)) {
    // If the new moderation state is published, or if this revision is the
    // published revision, set the node status to published.
    if ($node->workbench_moderation_state_new == workbench_moderation_state_published() || (!empty($node->workbench_moderation['published']) && $node->vid == $node->workbench_moderation['published']->vid)) {
      $node->status = 1;
    }
    else {
      $node->status = 0;
    }
  }
}

/**
 * Implements hook_node_insert().
 *
 * Wrapper call to the update hook.
 */
function workbench_moderation_node_insert($node) {
  workbench_moderation_node_update($node);
}

/**
 * Implements hook_node_update().
 *
 * Handles the submit of the node form moderation information
 */
function workbench_moderation_node_update($node) {
  global $user;

  // Don't proceed if moderation is not enabled on this content type, or if
  // we're replacing an already-published revision.
  if (!workbench_moderation_node_type_moderated($node->type) ||
      !empty($node->workbench_moderation['updating_live_revision'])) {
    return;
  }

  // Set default moderation state values.
  if (!isset($node->workbench_moderation_state_current)) {
    $node->workbench_moderation_state_current = ($node->status ? workbench_moderation_state_published() : workbench_moderation_state_none());
  };
  if (!isset($node->workbench_moderation_state_new)) {
    $node->workbench_moderation_state_new = variable_get('workbench_moderation_default_state_' . $node->type, workbench_moderation_state_none());
  };

  // If this is a new node, give it some information about 'my revision'.
  if (!isset($node->workbench_moderation)) {
    $node->workbench_moderation = array();
    $node->workbench_moderation['my_revision'] = $node->workbench_moderation['current'] = (object) array(
      'from_state' => workbench_moderation_state_none(),
      'state' => workbench_moderation_state_none(),
      'nid' => $node->nid,
      'vid' => $node->vid,
      'uid' => $user->uid,
      'current' => TRUE,
      'published' => FALSE,
      'stamp' => $node->changed,
    );
  }

  // Apply moderation changes if this is a new revision or if the moderation
  // state has changed.
  if (!empty($node->revision) || $node->workbench_moderation_state_current != $node->workbench_moderation_state_new) {
    // Update attached fields.
    field_attach_update('node', $node);
    // Moderate the node.
    workbench_moderation_moderate($node, $node->workbench_moderation_state_new);
  }

  return;
}

/**
 * Implements hook_node_load().
 *
 * Load moderation history and status on a node.
 */
function workbench_moderation_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    // Add the node history
    workbench_moderation_node_data($node);
  }
}

/**
 * Implements hook_node_view().
 *
 * Display messages about the node's moderation state.
 */
function workbench_moderation_node_view($node, $view_mode = 'full') {
  // Show moderation state messages if we're on a node page.
  if (node_is_page($node) && $view_mode == 'full' && empty($node->in_preview)) {
    workbench_moderation_messages('view', $node);
  }
}

/**
 * Implements hook_node_delete().
 */
function workbench_moderation_node_delete($node) {
  // Delete node history when it is deleted.
  db_delete('workbench_moderation_node_history')
    ->condition('nid', $node->nid)
    ->execute();
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Add moderation rules to node types.
 */
function workbench_moderation_form_node_type_form_alter(&$form, $form_state) {
  // Get a list of moderation states.
  $options = workbench_moderation_state_labels();

  // Disable the 'revision' checkbox when the 'moderation' checkbox is checked, so that moderation
  // can not be enabled unless revisions are enabled.
  $form['workflow']['node_options']['revision']['#states'] = array(
    'disabled' => array(':input[name="node_options[moderation]"]' => array('checked' => TRUE)),
  );

  // Disable the 'moderation' checkbox when the 'revision' checkbox is not checked, so that
  // revisions can not be turned off without also turning off moderation.
  $form['workflow']['node_options']['#options']['moderation'] = t('Enable moderation of revisions');
  $form['workflow']['node_options']['moderation']['#description'] = t('Revisions must be enabled in order to use moderation.');
  $form['workflow']['node_options']['moderation']['#states'] = array(
    'disabled' => array(':input[name="node_options[revision]"]' => array('checked' => FALSE)),
  );

  // This select element is hidden when moderation is not enabled.
  $form['workflow']['workbench_moderation_default_state'] = array(
    '#title' => t('Default moderation state'),
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => variable_get('workbench_moderation_default_state_' . $form['#node_type']->type),
    '#description' => t('Set the default moderation state for this content type. Users with additional moderation permissions will be able to set the moderation state when creating or editing nodes.'),
    '#states' => array(
      'visible' => array(':input[name="node_options[moderation]"]' => array('checked' => TRUE)),
    ),
  );
  $form['#validate'][] = 'workbench_moderation_node_type_form_validate';
}

/**
 * Validate the content type form.
 */
function workbench_moderation_node_type_form_validate($from, &$form_state) {
  // Ensure that revisions are enabled if moderation is.
  if ($form_state['values']['node_options']['moderation']) {
    $form_state['values']['node_options']['status'] = 0;
    $form_state['values']['node_options']['revision'] = 1;
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * Forcing new reversion and publishing.
 */
function workbench_moderation_form_node_form_alter(&$form, $form_state) {
  global $user;

  // This must be a node form and a type that has moderation enabled
  if (!workbench_moderation_node_type_moderated($form['type']['#value'])) {
    return;
  }
  // Set a moderation state even if there is not one defined
  if (isset($form['#node']->workbench_moderation['current']->state)) {
    $moderation_state = $form['#node']->workbench_moderation['current']->state;
  }
  else {
    $moderation_state = variable_get('workbench_moderation_default_state_' . $form['type']['#value'], workbench_moderation_state_none());
  }

  // Store the current moderation state
  $form['workbench_moderation_state_current'] = array(
    '#type' => 'value',
    '#value' => $moderation_state
  );
  // We have a use case where a live node is being edited. This will always
  // revert back to the original node status.
  if ($moderation_state == workbench_moderation_state_published()) {
    $moderation_state = workbench_moderation_state_none();
  }
  // Get all the states *this* user can access. If states is false, this user
  // can not change the moderation state
  if ($states = workbench_moderation_states_next($moderation_state, $user, $form['#node'])) {
    $current = array($moderation_state => t('Current: @state', array('@state' => workbench_moderation_state_label($moderation_state))));
    $states = array_merge($current, $states);
    $form['revision_information']['workbench_moderation_state_new'] = array(
      '#title' => t('Moderation state'),
      '#type' => 'select',
      '#options' => $states,
      '#default_value' => $moderation_state,
      '#description' => t('Set the moderation state for this content.'),
      '#access' => $states ? TRUE: FALSE,
    );
  }
  else {
    // Store the current moderation state
    $form['workbench_moderation_state_new'] = array(
      '#type' => 'value',
      '#value' => $moderation_state
    );
  }

  // Always create new revisions for nodes that are moderated
  $form['revision_information']['revision'] = array(
    '#type' => 'value',
    '#value' => TRUE,
  );

  // Set a default revision log message.
  $logged_name = (user_is_anonymous() ? variable_get('anonymous', t('Anonymous')) : $user->name);
  if (!empty($form['#node']->nid)) {
    $form['revision_information']['log']['#default_value'] = t('Edited by @user.', array('@user' => $logged_name));
  }
  else {
    $form['revision_information']['log']['#default_value'] = t('Created by @user.', array('@user' => $logged_name));
  }

  // Move the revision log into the publishing options to make things pretty.
  if ($form['options']['#access']) {
    $form['options']['log'] = $form['revision_information']['log'];
    $form['options']['log']['#title'] = t('Moderation notes');
    $form['options']['workbench_moderation_state_new'] = $form['revision_information']['workbench_moderation_state_new'];

    // Unset the old placement of the Revision log.
    unset($form['revision_information']['log']);
    unset($form['revision_information']['workbench_moderation_state_new']);

    // The revision information section should now be empty.
    $form['revision_information']['#access'] = FALSE;
  }

  // Setup the JS for the vertical tabs summary. The heavy weight allows this
  // script to replace the default node summary callbacks that get registered by
  // "lighter" scripts.
  // Note: Form API '#attached' does not allow to set a weight.
  drupal_add_js(drupal_get_path('module', 'workbench_moderation') . '/js/workbench_moderation.js', array('weight' => 90));

  // Users can not choose to publish content; content can only be published by
  // setting the content's moderation state to "Published".
  $form['options']['status']['#access'] = FALSE;
  $form['actions']['submit']['#submit'][] = 'workbench_moderation_node_form_submit';
  workbench_moderation_messages('edit', $form['#node']);
}

/**
 * Redirect to the current revision of a node after editing.
 */
function workbench_moderation_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = array('node/' . $form_state['node']->nid . '/current-revision');
}

/**
 * Overrides the node/%/edit page to ensure the proper revision is shown.
 *
 * @param $node
 *   The node being acted upon.
 * @return
 *   A node editing form.
 */
function workbench_moderation_node_edit_page_override($node) {
  // Check to see if this is an existing node
  if (isset($node->nid)) {
    if (workbench_moderation_node_type_moderated($node->type)) {
      // Load the node moderation data
      workbench_moderation_node_data($node);
      // We ONLY edit the current revision
      $node = workbench_moderation_node_current_load($node);
    }
  }
  // Ensure we have the editing code.
  module_load_include('inc', 'node', 'node.pages');
  return node_page_edit($node);
}

/**
 * Returns the key which represents the live revision.
 *
 * @TODO: make this configurable.
 */
function workbench_moderation_state_published() {
  return 'published';
}

/**
 * Returns the key which represents the neutral non moderated revision.
 *
 * @TODO: make this configurable.
 */
function workbench_moderation_state_none() {
  return 'draft';
}

/**
 * Determines if this content type is set to be moderated
 *
 * @param $type
 *   String, content type name
 *
 * @return boolean
 */
function workbench_moderation_node_type_moderated($type) {
  // Is this content even in moderatation?
  $options = variable_get("node_options_$type", array());
  if (in_array('revision', $options) && in_array('moderation', $options)) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Lists content types that are moderated
 */
function workbench_moderation_moderate_node_types() {
  $types = node_type_get_types();
  $result = array();
  foreach ($types as $type) {
    // Is this content even in moderatation?
    if (workbench_moderation_node_type_moderated($type->type)) {
      $result[] = $type->type;
    }
  }
  return $result;
}

/**
 * Checks if a user may change the state of a node.
 *
 * This check is based on transition and node type. Users
 * with the 'bypass workbench moderation' permission may make any state
 * transition.
 *
 * @see workbench_moderation_permission()
 *
 * Note that we do not use content-type specific moderation by default. To
 * enable that, see the instructions in workbench_moderation_permission().
 *
 * @param $account
 *   The user account being checked.
 * @param $from_state
 *   The original moderation state.
 * @param $to_state
 *   The new moderation state.
 *
 * @return
 *   Bollean TRUE or FALSE.
 */
function workbench_moderation_state_allowed($account, $from_state, $to_state, $node_type) {
  // Allow super-users to moderate all content.
  if (user_access("bypass workbench moderation", $account)) {
    return TRUE;
  }

  // Can this user moderate all content for this transition?
  if (user_access("moderate content from $from_state to $to_state", $account)) {
    return TRUE;
  }

  // Are we using complex node type rules for this transition?
  if (variable_get('workbench_moderation_per_node_type', FALSE) && user_access("moderate $node_type state from $from_state to $to_state", $account)) {
    return TRUE;
  }

  // Default return.
  return FALSE;
}

/**
 * Adds current and live revision data to a node.
 *
 * @param $node
 *   The node being acted upon.
 */
function workbench_moderation_node_data($node) {
  // Make sure that this node type is moderated.
  if (!workbench_moderation_node_type_moderated($node->type)) {
    return;
  }

  // Path module is stupid and doesn't load its data in node_load.
  if (module_exists('path') && isset($node->nid)) {
    $path = array();
    $conditions = array('source' => 'node/' . $node->nid);
    if ($node->language != LANGUAGE_NONE) {
      $conditions['language'] = $node->language;
    }
    $path = path_load($conditions);
    if ($path === FALSE) {
      $path = array();
    }
    if (isset($node->path)) {
      $path += $node->path;
    }
    $path += array(
      'pid' => NULL,
      'source' => 'node/' . $node->nid,
      'alias' => '',
      'language' => isset($node->language) ? $node->language : LANGUAGE_NONE,
    );

    $node->path = $path;
  }

  // Build a default 'current' moderation record. Nodes will lack a
  // workbench_moderation record if moderation was not enabled for their node
  // type when they were created. In that case, assume the live node is at the
  // current revision.
  $defaults = array(
    'hid' => NULL,
    'nid' => $node->nid,
    'vid' => $node->vid,
    'from_state' => workbench_moderation_state_none(),
    'state' => ($node->status ? workbench_moderation_state_published() : workbench_moderation_state_none()),
    'uid' => $node->uid,
    'stamp' => $node->changed,
    'published' => $node->status,
    'current' => 1,
  );

  // We'll store moderation state information in an array on the node.
  $node->workbench_moderation = array();

  // Fetch the most recent revision from the {node_revision} table. This is the
  // current revision ("head").
  $query = db_select('node_revision', 'r');
  $query->addJoin('LEFT OUTER', 'workbench_moderation_node_history', 'm', 'r.vid = %alias.vid');
  $query->condition('r.nid', $node->nid)
    ->orderBy('r.vid', 'DESC')
    ->orderBy('m.hid', 'DESC')
    ->fields('m')
    ->fields('r', array('title', 'timestamp'));
  $current = $query->execute()->fetchObject();

  if (!$current) {
    $current = (object) $defaults;
  }
  else {
    // Fill in any defaults that are missing from the database record. We need
    // to maintain false-y values except for NULL, so array_filter() +
    // array_merge() wouldn't work here.
    foreach (array_keys($defaults) as $key) {
      if (is_null($current->$key)) {
        $current->$key = $defaults[$key];
      }
    }
  }

  $current->current = 1;
  $node->workbench_moderation['current'] = $current;

  // Fetch the published revision. There may not be a workbench_moderation
  // record for some nodes, but in those cases if the node is published,
  // $current->published will be TRUE.
  if ($current->published) {
    $published = $current;
  }
  else {
    // Fetch the most recent published revision.
    $query = db_select('node', 'n');
    $query->addJoin('INNER', 'node_revision', 'r', 'n.vid = r.vid');
    $query->addJoin('LEFT OUTER', 'workbench_moderation_node_history', 'm', 'r.vid = m.vid');
    $query->condition('n.nid', $node->nid)
      ->condition('n.status', 1)
      ->orderBy('m.hid', 'DESC')
      ->fields('r', array('nid', 'vid', 'title', 'timestamp'))
      ->fields('m');
    $published = $query->execute()->fetchObject();
  }
  // If we have a published copy, add that to the array.
  if ($published) {
    $published->state = workbench_moderation_state_published();
    $node->workbench_moderation['published'] = $published;
  }

  // Fetch the workbench_moderation record for this node object's revision. If
  // it is either the current or published revision of the node, that data will
  // be used.
  if ($node->vid == $current->vid) {
    $my_revision = $current;
  }
  elseif ($published && $node->vid == $published->vid) {
    $my_revision = $published;
  }
  else {
    $query = db_select('node_revision', 'r');
    $query->addJoin('LEFT OUTER', 'workbench_moderation_node_history', 'm', 'r.vid = m.vid');
    $query->condition('m.vid', $node->vid)
      ->orderBy('m.hid', 'DESC')
      ->fields('m')
      ->fields('r', array('nid', 'vid', 'title', 'timestamp'));
    $my_revision = $query->execute()->fetchObject();

    // This might happen if you're turning workbench_moderation on and off, but
    // it should be really rare. Workbench_moderation must have recorded a
    // current revision, and then the node table must contain a different and
    // unpublished revision.
    if (!$my_revision) {
      $my_revision = (object) array(
        'hid' => NULL,
        'nid' => $node->nid,
        'vid' => $node->vid,
        'from_state' => workbench_moderation_state_none(),
        'state' => workbench_moderation_state_none(),
        'uid' => $node->uid,
        'stamp' => $node->changed,
        'published' => 0,
        'current' => 0,
      );
    }
  }
  // Add my revision to the array.
  $node->workbench_moderation['my_revision'] = $my_revision;
}

/**
 * Utility function to load the current revision of a node.
 *
 * @param $node
 *   The node being acted upon.
 *
 * @return
 *   The current node according to moderation.
 */
function workbench_moderation_node_current_load($node) {
  // Is there a current revision?
  if (isset($node->workbench_moderation['current']->vid)) {
    // Ensure that we will return the current revision
    if ($node->vid != $node->workbench_moderation['current']->vid) {
      $node = node_load($node->nid, $node->workbench_moderation['current']->vid);
    }
  }
  return $node;
}


/**
 * Utility function to load the live revision of a node.
 *
 * This is encapsulated so that changes to how the moderation data is stored
 * will not impact the API.
 *
 * @param $node
 *   The node being acted upon.
 *
 * @return
 *   The node object of the live revision.
 */
function workbench_moderation_node_live_load($node) {
  // Is there a live revision of this node?
  if (isset($node->workbench_moderation['published']->vid)) {
    return node_load($node->nid, $node->workbench_moderation['published']->vid, TRUE);
  }
}


/**
 * Utility function to determine if this node is in the live state.
 *
 * @param $node
 *   The node being acted upon.
 *
 * @return
 *   Boolean TRUE if this is the current revision. FALSE if not.
 */
function workbench_moderation_node_is_current($node) {
  if (isset($node->workbench_moderation['published']->vid) && isset($node->workbench_moderation['current']->vid)) {
    if ($node->workbench_moderation['published']->vid == $node->workbench_moderation['current']->vid) {
      return TRUE;
    }
    return FALSE;
  }
  // If not set, then TRUE.
  return TRUE;
}

/**
 * Get a list of all moderation states.
 *
 * @return
 *   An array of state objects, keyed by state name and ordered by weight. Each
 *   state object has name, description, and weight properties.
 */
function workbench_moderation_states() {
  static $states;
  if (!isset($states)) {
    $states = db_select('workbench_moderation_states', 'states')
      ->fields('states', array('name', 'label', 'description', 'weight'))
      ->orderBy('states.weight', 'ASC')
      ->execute()
      ->fetchAllAssoc('name');
  }

  return $states;
}

/**
 * Generate an array of moderation states suitable for use as Form API #options.
 *
 * @return
 *   An array of states with machine names as keys and labels as values.
 */
function workbench_moderation_state_labels() {
  $labels = &drupal_static(__FUNCTION__);

  if (!isset($labels)) {
    $labels = array();
    foreach (workbench_moderation_states() as $machine_name => $state) {
      $labels[$machine_name] = $state->label;
    }
  }

  return $labels;
}

/**
 * Get the label for a state based on its machine name.
 *
 * @param type $machine_name
 *   The machine name of the state.
 * @return
 *   An unsanitized label or an empty string if the state does not exist.
 */
function workbench_moderation_state_label($machine_name) {
  $labels = workbench_moderation_state_labels();
  return isset($labels[$machine_name]) ? $labels[$machine_name] : '';
}

/**
 * Get information about a single moderation state.
 *
 * @param type $machine_name
 *   The machine name of the state.
 * @return
 *   An object of information about the state or FALSE if the state does not exist.
 */
function workbench_moderation_state_load($machine_name) {
  $states = workbench_moderation_states();
  if (isset($states[$machine_name])) {
    return $states[$machine_name];
  }
  return FALSE;
}

/**
 * Save a new or existing moderation state.
 *
 * Moderation state names must be unique, so saving a state object with a
 * non-unique name updates the existing state.
 *
 * @TODO: add a hook here.
 *
 * @param $state
 *   An object with name, description, and weight properties.
 */
function workbench_moderation_state_save($state) {
  return db_merge('workbench_moderation_states')
    ->key(array('name' => $state->name))
    ->fields((array) $state)
    ->execute();
}

/**
 * Delete a moderation state.
 *
 * This function also deletes any transitions that reference the deleted
 * moderation state.
 *
 * @TODO: add a hook here.
 *
 * @param $state
 *   An object with at least a name property.
 *
 */
function workbench_moderation_state_delete($state) {
  db_delete('workbench_moderation_states')
    ->condition('name', $state->name)
    ->execute();

  db_delete('workbench_moderation_transitions')
    ->condition(db_or()->condition('from_name', $state->name)->condition('to_name', $state->name))
    ->execute();
}

/**
 * Get a list of all moderation state transitions.
 *
 * @return
 *   An array of transition objects, each with from_name and to_name properties
 *   that reference moderation states. The array is ordered by the weight of the
 *   'from' states, then by the weight of the 'to' states.
 */
function workbench_moderation_transitions() {
  static $transitions;
  if (!isset($transitions)) {
    $query = db_select('workbench_moderation_transitions', 't')
      ->fields('t', array('from_name', 'to_name'));

    $alias_from = $query->addJoin('INNER', 'workbench_moderation_states', NULL, 't.from_name = %alias.name');
    $alias_to = $query->addJoin('INNER', 'workbench_moderation_states', NULL, 't.to_name = %alias.name');

    $query
      ->orderBy("$alias_from.weight", 'ASC')
      ->orderBy("$alias_to.weight", 'ASC');

    $transitions = $query->execute()->fetchAll();
  }
  return $transitions;
}

/**
 * Saves a moderation state transition.
 *
 * @TODO: add a hook here.
 *
 * @param $transition
 *   An object with from_name and to_name properties that reference moderation
 *   states.
 */
function workbench_moderation_transition_save($transition) {
  return db_merge('workbench_moderation_transitions')
    ->key(array('from_name' => $transition->from_name, 'to_name' => $transition->to_name))
    ->fields((array) $transition)
    ->execute();
}

/**
 * Deletes a moderation state transition.
 *
 * @TODO: add a hook here.
 *
 * @param $transition
 *   An object with from_name and to_name properties that reference moderation
 *   states.
 */
function workbench_moderation_transition_delete($transition) {
  db_delete('workbench_moderation_transitions')
    ->condition('from_name', $transition->from_name)
    ->condition('to_name', $transition->to_name)
    ->execute();
}

/**
 * Provides a list of possible next states for this node.
 *
 * This function is used in permissions checks, so it should never return
 * disallowed transitions.
 *
 * @param $current_state
 *   The current moderation state.
 * @param $account
 *   The user object being checked.
 * @param $node
 *   The node object being acted upon.
 *
 * @return
 *   If the user may moderate a change, return an array of possible state
 *   changes. Otherwise, return FALSE.
 */
function workbench_moderation_states_next($current_state, $account = NULL, $node) {
  $states = FALSE;

  // Make sure we have a current state.
  if (!$current_state) {
    $current_state = workbench_moderation_state_none();
  }

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

  if (user_access('bypass workbench moderation', $account)) {
    // Some functions expect an array of $state => $state pairs.
    $states = workbench_moderation_state_labels();
    unset($states[$current_state]);
  }
  else {
    // Get a list of possible transitions.
    $select = db_select('workbench_moderation_transitions', 'transitions')
      ->condition('transitions.from_name', $current_state)
      ->fields('transitions', array('to_name'))
      ->fields('states', array('label'));
    $select->join('workbench_moderation_states', 'states', 'transitions.to_name = states.name');

    $states = $select->execute()->fetchAllKeyed();

    // Checks whether the user has permission to make each transition. The
    // 'bypass workbench moderation' permission is accounted for in
    // workbench_moderation_state_allowed().
    if ($states) {
      foreach ($states as $machine_name => $label) {
        if (!workbench_moderation_state_allowed($account, $current_state, $machine_name, $node->type)) {
          unset($states[$machine_name]);
        }
      }
    }
  }

  $context = array('account' => $account, 'node' => $node);
  drupal_alter('workbench_moderation_states_next', $states, $current_state, $context);
  return $states;
}

/**
 * Provide quick moderation of nodes.
 *
 * Access is controlled by the menu router to these pseudo-form callbacks.
 * This function is also abstracted so that it can be called from any node
 * context.
 *
 * @see _workbench_moderation_moderate_access()
 * @see workbench_moderation_menu()
 * @see workbench_moderation_node_update()
 *
 * @param $node
 *   The node being acted upon.
 * @param $state
 *   The new moderation state requested.
 */
function workbench_moderation_moderate($node, $state) {
  global $user;

  $old_revision = $node->workbench_moderation['my_revision'];

  // Get the number of revisions for this node with vids greater than $node->vid
  $vid_count = db_select('node_revision', 'r')
    ->condition('r.nid', $node->nid)
    ->condition('r.vid', $node->vid, '>')
    ->countQuery()->execute()->fetchField();
  // If the number of greater vids is 0, then this is the most current revision
  $current = ($vid_count == 0);

  // Build a history record.
  $new_revision = (object) array(
    'from_state' => $old_revision->state,
    'state' => $state,
    'nid' => $node->nid,
    'vid' => $node->vid,
    'uid' => $user->uid,
    'current' => $current,
    'published' => ($state == workbench_moderation_state_published()),
    'stamp' => $_SERVER['REQUEST_TIME'],
  );

  // If this is the new 'current' moderation record, it should be the only one
  // flagged 'current' in {workbench_moderation_node_history}.
  if ($new_revision->current) {
    $query = db_update('workbench_moderation_node_history')
      ->condition('nid', $node->nid)
      ->fields(array('current' => 0))
      ->execute();
  }

  // If this revision is to be published, the new moderation record should be
  // the only one flagged 'published' in both
  // {workbench_moderation_node_history} AND {node_revision}
  if ($new_revision->published) {
    $query = db_update('workbench_moderation_node_history')
      ->condition('nid', $node->nid)
      ->fields(array('published' => 0))
      ->execute();
    $query = db_update('node_revision')
      ->condition('nid', $node->nid)
      ->fields(array('status' => 0))
      ->execute();
  }

  // Save the node history record.
  drupal_write_record('workbench_moderation_node_history', $new_revision);

  // Update the node's content_moderation information so that we can publish it
  // if necessary.
  $node->workbench_moderation['my_revision'] = $new_revision;
  if ($new_revision->current) {
    $node->workbench_moderation['current'] = $new_revision;
  }
  // Handle the published revision.
  if ($new_revision->published) {
    // If we're moderating a revision to the published state, mark the new
    // revision as the published revision.
    $node->workbench_moderation['published'] = $new_revision;
  }
  elseif (isset($node->workbench_moderation['published']) && $new_revision->vid == $node->workbench_moderation['published']->vid && $new_revision->from_state == workbench_moderation_state_published()) {
    // If we're moderating the published revision to a non-published state,
    // remove the workbench moderation 'published' property.
    unset($node->workbench_moderation['published']);
  }

  // If we're moderating an unpublished revision and there is an existing
  // published revision, make sure that the published revision is live.
  // We do this in a shutdown function to avoid race conditions when
  // running node_save() from within a node submission.
  if (!empty($node->workbench_moderation['published'])) {
    drupal_register_shutdown_function('workbench_moderation_store', $node);
  }


  // Notify other modules that the state was changed.
  module_invoke_all('workbench_moderation_transition', $node, $old_revision->state, $state);
}

/**
 * Shutdown callback for saving a node revision.
 *
 * This function is called by drupal_register_shutdown_function().
 * The purpose is to delay a node_save() call so that a live revision
 * is not called during hook_node_update().
 *
 * Instead, we delay the update until the new revision is saved. This way,
 * we can more safely call the revision and pick up changes to items
 * that are not revisioned (such as menu and path assignments).
 *
 * @see workbench_moderation_moderate()
 *
 * @param $node
 *   The node being saved.
 */
function workbench_moderation_store($node) {
  if (!isset($node->nid)) {
    watchdog('Workbench moderation', 'Failed to save node revision: node not passed to shutdown function.', array(), WATCHDOG_NOTICE);
    return;
  }
  watchdog('Workbench moderation', 'Saved node revision: %node as live version for node %live.', array('%node' => $node->vid, '%live' => $node->nid), WATCHDOG_NOTICE, l($node->title, 'node/' . $node->nid));
  $live_revision = workbench_moderation_node_live_load($node);
  // Make sure we're published.
  $live_revision->status = 1;
  // Don't create a new revision.
  $live_revision->revision = 0;
  // Prevent another moderation record from being written.
  $live_revision->workbench_moderation['updating_live_revision'] = TRUE;

  // Reset flag from taxonomy_field_update() so that {taxonomy_index} values aren't written twice.
  $taxonomy_index_flag = &drupal_static('taxonomy_field_update', array());
  unset($taxonomy_index_flag[$node->nid]);

  // Save the node.
  node_save($live_revision);
}

/**
 * Helper function to redirect after a state change submission.
 *
 * @param $node
 *   The node being acted upon.
 * @param $state
 *   The new moderation state requested.
 */
function workbench_moderation_moderate_callback($node, $state) {
  if (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], "{$node->nid}:{$node->vid}:$state")) {
    return MENU_ACCESS_DENIED;
  }

  workbench_moderation_moderate($node, $state);
  drupal_goto(isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid . '/moderation');
}

/**
 * Generates a list of links to available moderation actions.
 *
 * @param $node
 *   The node being acted upon.
 * @param $url_options
 *   An array of options to pass, following the url() function syntax.
 *
 * @return
 *   A list of links to display with the revision.
 */
function workbench_moderation_get_moderation_links($node, $url_options = array()) {
  // Make sure that this node type is moderated.
  if (!workbench_moderation_node_type_moderated($node->type)) {
    return;
  }

  // Build links to available moderation states.
  $links = array();
  $my_revision = $node->workbench_moderation['my_revision'];
  if ($my_revision->vid == $node->workbench_moderation['current']->vid
      && $next_states = workbench_moderation_states_next($my_revision->state, NULL, $node)) {
    foreach ($next_states as $state => $label) {
      $link = array_merge($url_options, array(
        'title' => t('Change to %label', array('%label' => workbench_moderation_state_label($state))),
        'href' => "node/{$node->nid}/moderation/{$node->vid}/change-state/{$state}",
      ));
      $link['query']['token'] = drupal_get_token("{$node->nid}:{$node->vid}:{$state}");
      $links[] = $link;
    }
  }

  return $links;
}

/**
 * Generates a moderation form for a node.
 *
 * The caller of this form needs to check whether the node is in moderation.
 *
 * @param $node
 *   The node being acted upon.
 *
 * @return $form
 *   A Drupal Forms API array.
 */
function workbench_moderation_moderate_form($form, &$form_state, $node, $destination = NULL) {
  global $user;
  $form = array();

  // Build links to available moderation states.
  $links = array();
  $my_revision = $node->workbench_moderation['my_revision'];
  if ($my_revision->vid == $node->workbench_moderation['current']->vid
      && $next_states = workbench_moderation_states_next($my_revision->state, $user, $node)) {
    $form['#destination'] = $destination;
    $form['node'] = array(
      '#type' => 'value',
      '#value' => $node,
    );
    $form['#attributes']['class'][] = 'workbench-moderation-moderate-form';
    $form['#attached']['css'][] = drupal_get_path('module', 'workbench_moderation') . '/css/workbench_moderation.css';
    $form['state'] = array(
      '#type' => 'select',
      '#title' => t('Moderation state'),
      '#title_display' => 'invisible',
      '#options' => $next_states,
      '#default_value' => _workbench_moderation_default_next_state($my_revision->state, $next_states),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Apply'),
    );

    // Cache the form on first load to preserve the node for validation.
    // Otherwise, the node would be reloaded on submit, and there would be no
    // way to detect if the current revision has been changed.
    $form_state['cache'] = TRUE;
  }
  else {
    $form['#access'] = FALSE;
  }

  return $form;
}

function _workbench_moderation_default_next_state($current_state, $next_states) {
  $states = workbench_moderation_states();
  foreach ($states as $state_name => $state) {
    if ($state->weight > $states[$current_state]->weight && isset($next_states[$state_name])) {
      return $state_name;
    }
  }
}

function workbench_moderation_moderate_form_validate($form, &$form_state) {
  // Make sure that the revision that was shown to the user is still the current
  // revision before changing the current revision's state.
  $moderated_node = $form_state['values']['node'];
  $current_node = workbench_moderation_node_current_load(node_load($moderated_node->nid));
  if ($moderated_node->vid != $current_node->vid) {
    form_set_error('', t('The moderation state could not be changed because the draft has been updated by another user. Please review the current draft.'));
    // Redirect the form so that it rebuilds with the current revision.
    drupal_redirect_form($form_state);
  }
}

function workbench_moderation_moderate_form_submit($form, &$form_state) {
  if (_workbench_moderation_moderate_access($form_state['values']['node'], $form_state['values']['state'])) {
    workbench_moderation_moderate(node_load($form_state['values']['node']->nid, $form_state['values']['node']->vid), $form_state['values']['state']);
  }

  // This is not ideal, but if the form is invoked from a node's draft tab and
  // used to publish the node, the draft tab will not be available after
  // publishing, and Drupal's will throw an access denied error before it is
  // able to redirect to the published revision.
  if (!empty($form['#destination'])) {
    if ($form_state['values']['state'] == workbench_moderation_state_published()) {
      if ($uri = entity_uri('node', $form['node']['#value'])) {
        // Disable lookup of the path alias, since the path alias might get
        // changed by modules such as Pathauto.
        $uri['options']['alias'] = TRUE;
        $form_state['redirect'] = array($uri['path'], $uri['options']);
      }
    }
    else {
      $form_state['redirect'] = $form['#destination'];
    }
    drupal_redirect_form($form_state);
  }
}

/**
 * Sets status messages for a node.
 *
 * Note that these status messages aren't relevant to the session, only the
 * current page view.
 *
 * @see workbench_moderation_set_message()
 *
 * @param $context
 *   A string, either 'view' or 'edit'.
 * @param $node
 *   A node object. The current menu object will be used if it is a node and
 *   this variable was not set.
 */
function workbench_moderation_messages($context, $node = NULL) {
  global $user;
  if (!user_access('view moderation messages')
      || (!$node && !($node = menu_get_object()))
      || !workbench_moderation_node_type_moderated($node->type)) {
    return;
  }

  $node_published = FALSE;
  $revision_published = FALSE;
  $revision_current = FALSE;

  // For new content, this property will not be set.
  if (isset($node->workbench_moderation)) {
    $state = $node->workbench_moderation;
    if (!empty($state['published'])) {
      $node_published = TRUE;
    }
    if ($state['my_revision']->published) {
      $revision_published = TRUE;
    }
    if ($state['my_revision']->vid == $state['current']->vid) {
      $revision_current = TRUE;
    }
  }

  // An array of messages to add to the general workbench block.
  $info_block_messages = array();

  if ($context == 'view') {
    $info_block_messages[] = array(
      'label' => t('Revision state'),
      'message' => check_plain(workbench_moderation_state_label($state['my_revision']->state)),
    );
    $info_block_messages[] = array(
      'label' => t('Current draft'),
      'message' => !empty($revision_current) ? t('Yes') : t('No'),
    );

    // Check node access.
    drupal_static('_node_revision_access', array(), TRUE);

    // Add a moderation form.
    if ($revision_current && !$revision_published && _workbench_moderation_access('update', $node) && $moderate_form = drupal_get_form('workbench_moderation_moderate_form', $node, "node/{$node->nid}/current-revision")) {
      if ($moderate_form = drupal_render($moderate_form)) {
        $info_block_messages[] = array(
          'label' => t('Set moderation state'),
          'message' => $moderate_form,
        );
      }
    }

    // Add an unpublish link.
    $next_states = workbench_moderation_states_next(workbench_moderation_state_published(), $user, $node);
    if ($revision_published && !empty($next_states) && $link = workbench_moderation_access_link(t('Unpublish this revision'), "node/{$node->nid}/moderation/{$node->vid}/unpublish")) {
      $info_block_messages[] = array(
        'label' => t('Actions'),
        'message' => $link,
      );
    }

    // Revision navigation links. This is disabled for the time being, since
    // node tabs are lost when navigating through old revisions.
    // @TODO remove this entirely?
    if (variable_get('workbench_moderation_show_revision_navigation', FALSE) && user_access('view revisions')) {
      $links = array();

      // Get previous and next revision ids.
      $args = array(':nid' => $node->nid, ':vid' => $node->vid);
      if ($prev_vid = db_query_range("SELECT nr.vid FROM {node_revision} nr WHERE nr.nid = :nid AND nr.vid < :vid ORDER BY nr.vid DESC", 0, 1, $args)->fetchField()) {
        $links[$prev_vid] = array('title' => t('Previous revision'), 'href' => "node/{$node->nid}/revisions/{$prev_vid}/view");
      }
      if ($next_vid = db_query_range("SELECT nr.vid FROM {node_revision} nr WHERE nr.nid = :nid AND nr.vid > :vid ORDER BY nr.vid ASC", 0, 1, $args)->fetchField()) {
        $links[$next_vid] = array('title' => t('Next revision'), 'href' => "node/{$node->nid}/revisions/{$next_vid}/view");
      }

      // If the current revision is next or previous, use the "node/%node/current-revision" path.
      if (($current = $state['current']->vid) && isset($links[$current])) {
        $links[$current]['href'] = "node/{$node->nid}/current-revision";
      }

      // If the published revision is next or previous, use the "node/%node" path.
      if (isset($state['published']) && ($published = $state['published']->vid) && isset($links[$published])) {
        $links[$published]['href'] = "node/{$node->nid}";
      }

      // Link it up, with access checks.
      foreach ($links as $key => $args) {
        $links[$key] = call_user_func_array('workbench_moderation_access_link', $args);
      }

      // Post the links in a non-repeating message.
      if (!empty($links)) {
        $info_block_messages[] = array(
          'label' => t('View'),
          'message' => implode(', ', $links),
        );
      }
    }
  }
  // @TODO: Clean these up.
  elseif ($context == 'edit') {
    if ($node_published && $revision_published) {
      $info_block_messages[] = array(
        'label' => t('Status'),
        'message' => t('New draft of live content.'),
      );
    }
    elseif ($node_published && !$revision_published) {
      $info_block_messages[] = array(
        'label' => t('Status'),
        'message' => t('New draft from current revision'),
      );
      $link = workbench_moderation_access_link(t('Create a new draft from the published revision.'), "node/{$node->nid}/revisions/{$state['published']->vid}/revert");
      $info_block_messages[] = array(
        'label' => t('Actions'),
        'message' => $link,
      );
    }
    else {
      // New content.
      $info_block_messages[] = array(
        'label' => t('New content'),
        'message' => t('Your draft will be placed in moderation.'),
      );
    }
  }

  // Send the info block array to a static variable.
  workbench_moderation_set_message($info_block_messages);
}

/**
 * Builds a link for use in messages.
 *
 * @see workbench_moderation_messages()
 *
 * @param $text
 *   The link text to use.
 * @param $internal_path
 *   The Drupal path for the link.
 * @param $options
 *   Link options, following the format of url().
 *
 * @return
 *   A drupal-formatted HTML link.
 */
function workbench_moderation_access_link($text, $internal_path, $options = array()) {
  if (($item = menu_get_item($internal_path)) && !empty($item['access'])) {
    return l($text, $internal_path, $options);
  }
}

/**
 * Stores status messages for delivery.
 *
 * This function stores up moderation messages to be passed on to workbench_moderation_workbench_block().
 *
 * This function uses a static variable so that function can be called more than
 * once and the array built up.
 *
 * @see workbench_moderation_workbench_block()
 * @see workbench_moderation_messages()
 *
 * @param $new_messages
 *   An array of messages to be added to the block.
 *
 * @return
 *   An array of messages to be added to the block.
 */
function workbench_moderation_set_message($new_messages = array()) {
  static $messages = array();
  $messages = array_merge($messages, $new_messages);
  return $messages;
}

/**
 * Implements hook_block_view_workbench_block().
 *
 * Show the editorial status of this node.
 */
function workbench_moderation_workbench_block() {
  $output = array();
  foreach (workbench_moderation_set_message() as $message) {
    $output[] = t('!label: <em>!message</em>', array('!label' => $message['label'], '!message' => $message['message']));
  }

  return $output;
}


/**
 * Implementation of hook_workbench_moderation_transition().
 */
function workbench_moderation_workbench_moderation_transition($node, $previous_state, $new_state) {
  if (module_exists('trigger')) {
    workbench_moderation_trigger_transition($node, $previous_state, $new_state);
  }

  if (module_exists('rules')){
    rules_invoke_event('workbench_moderation_after_moderation_transition', $node, $previous_state, $new_state);
  }
}

/**
 * Implements hook_trigger_info().
 *
 * Creates a trigger for each transition.
 */
function workbench_moderation_trigger_info() {

  $output = array(
    'workbench_moderation' => array(
      'workbench_moderation_transition' => array(
        'label' => t('After any transition between states occurs.'),
      ),
    ),
  );

  // Get all transitions.
  $transitions = workbench_moderation_transitions();

  // Add a trigger for each transition.
  foreach ($transitions as $transition_definition) {
    $transition_string = 'wmt_' . $transition_definition->from_name . '__' . $transition_definition->to_name;
    // Hash this string if it's longer than the db field size
    if (strlen($transition_string) > 32) {
      $transition_string = md5($transition_string);
    }

    $output['workbench_moderation'][$transition_string] = array(
      'label' => t('Transition from the state %from_name to %to_name occurs.', array('%from_name' => $transition_definition->from_name, '%to_name' => $transition_definition->to_name)),
    );
  }

  return $output;
}

/**
 * transition trigger: Run actions associated with an arbitrary event.
 *
 * This function is executed after a transition takes place.
 *
 * @param $node
 *   The node undergoing the transition.
 * @param $from_state
 *   The previous workbench moderation state.
 * @param $state
 *   The new workbench moderation state.
 */
function workbench_moderation_trigger_transition($node, $from_state, $state, $a3 = NULL, $a4 = NULL) {
  // Ask the trigger module for all actions enqueued for the 'transition' trigger.
  $aids = trigger_get_assigned_actions('workbench_moderation_transition');
  // prepare a basic context, indicating group and "hook", and call all the
  // actions with this context as arguments.
  $context = array(
    'group' => 'workbench_moderation',
    'hook' => 'transition',
    'from_state' => $from_state,
    'state' => $state,
  );
  actions_do(array_keys($aids), $node, $context, $a3, $a4);


  // Ask the trigger module for all actions enqueued for this specific transition.
  $transition_string = 'wmt_' . $from_state . '__' . $state;
  // Hash this string if it's longer than the db field size
  if (strlen($transition_string) > 32) {
    $transition_string = md5($transition_string);
  }
  $aids = trigger_get_assigned_actions($transition_string);
  $context['hook'] = $transition_string;

  actions_do(array_keys($aids), $node, $context, $a3, $a4);
}

/**
 * Implements hook_action_info().
 */
function workbench_moderation_action_info() {
  $info = array();
  $info['workbench_moderation_set_state_action'] = array(
    'type' => 'node',
    'label' => t('Set moderation state'),
    'configurable' => TRUE,
    'behavior' => array('changes_property'),
    'triggers' => array('node_presave', 'node_insert', 'node_update', 'workbench_moderation_transition'),
  );

  // Get all workbench transitions.
  $transitions = workbench_moderation_transitions();

  // Add a trigger for each transition.
  foreach ($transitions as $transition_definition) {
    $transition_string = 'wmt_' . $transition_definition->from_name . '__' . $transition_definition->to_name;
    // Hash this string if it's longer than the db field size
    if (strlen($transition_string) > 32) {
      $transition_string = md5($transition_string);
    }

    $info['workbench_moderation_set_state_action']['triggers'][] = $transition_string;
  }

  return $info;
}

/**
 * Form builder; Prepare a form for possible moderation states.
 */
function workbench_moderation_set_state_action_form($context) {
  $form = array();

  $form['state'] = array(
    '#type' => 'select',
    '#options' => workbench_moderation_state_labels(),
    '#default_value' => isset($context['state']) ? $context['state'] : '',
  );

  $form['force_transition'] = array(
    '#type' => 'checkbox',
    '#default_value' => FALSE,
  );

  return $form;
}

/**
 * Process workbench_moderation_set_state_action_form form submissions.
 */
function workbench_moderation_set_state_action_submit($form, $form_state) {
  return array('state' => $form_state['values']['state'], 'force_transition' => $form_state['values']['force_transition']);
}

/**
 * Changes the moderation state for a given node.
 */
function workbench_moderation_set_state_action($node, $context) {
  if (empty($context['state'])) return;

  if ((array_key_exists('force_transition', $context) && $context['force_transition']) || _workbench_moderation_moderate_access($node, $context['state'])){
    workbench_moderation_moderate($node, $context['state']);
    watchdog('action', 'Change node %nid moderation state to %state.', array('%nid' => $node->nid, '%state' => $context['state']));
  }
}

/**
 * Implements hook_ctools_plugin_directory() to let the system know
 * where our task and task_handler plugins are.
 */
function workbench_moderation_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'page_manager') {
    return 'plugins/page_manager/' . $plugin_type;
  }
}

/**
 * Implements hook_ctools_plugin_api().
 */
function workbench_moderation_ctools_plugin_api($module, $api) {

  if ($module == 'page_manager' && $api == 'pages_default') {
    return array('version' => 1);
  }
}

/**
 * Implement hook_migrate_api().
 */
function workbench_moderation_migrate_api() {
  return array('api' => 2);
}