summaryrefslogtreecommitdiffstats
path: root/views.module
blob: 4ad2c9a8dc5fceaa26305fee9a61b08c829f56c8 (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
<?php
// $Id$

function views_init() {
  // hook init is called even on cached pages, but we don't want to
  // actually do anything in that case.
  if (!function_exists('drupal_get_path')) {
    return;
  }
  // Load all our module 'on behalfs'.
  $path = drupal_get_path('module', 'views') . '/modules';
  $files = system_listing('views_.*\.inc$', $path, 'name', 0);

  foreach($files as $file) {
    // The filename format is very specific. It must be views_MODULENAME.inc
    $module = substr_replace($file->name, '', 0, 6);
    if (module_exist($module)) {
      require_once($file->filename);
    }
  }
}

// ---------------------------------------------------------------------------
// Acquire Views Data

/**
 * Return the arguments array; construct one if we haven't already. The
 * array is cached in a global, safely named variable so that arguments
 * are only constructed once per run.
 */
function _views_get_arguments($titles = false) {
  static $views_arguments;
  global $locale;

  if (!$views_arguments) {
    $data = cache_get("views_arguments:$locale");
    $cache = unserialize($data->data);
    if (is_array($cache)) {
      $views_arguments = $cache;
    }
    else {
      $arguments = module_invoke_all('views_arguments');
      foreach ($arguments as $name => $arg) {
        if ($arg['option'] && !is_array($arg['option'])) {
          if ($arg['option'] == 'string' || $arg['option'] == 'integer') {
            $arg['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
          }
          else {
            $arg['option'] = array('#type' => 'select', '#options' => $arg['option']);
          }
        }
        $views_arguments['base'][$name] = $arg['name'];
        $views_arguments['title'][$name] = $arg;
      }
      $cache = $views_arguments;
      cache_set("views_arguments:$locale", serialize($cache));
    }
  }
  return ($titles ? $views_arguments['base'] : $views_arguments['title']);
}

/**
 * Constructs the full table information array. Caches it into a global array
 * so that it will only be called once per run.
 */
function _views_get_tables($full = false) {
  static $views_tables;
  global $locale;

  if (!$views_tables) {
    $data = cache_get("views_tables:$locale");
    $cache = unserialize($data->data);

    if (is_array($cache)) {
      $views_tables = $cache;
    }
    else {
      $table_data = module_invoke_all('views_tables');
      $views_tables['tables'] = $table_data;

      foreach ($table_data as $name => $table) {
        if (is_array($table['filters'])) {
          foreach ($table['filters'] as $filter => $data) {
            $data['table'] = $name;
            // translate for deprecated APIs...
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
            if ($data['list']) {
              $data['value'] = array('#type' => 'select', '#options' => $data['list']);
              if ($data['list-type'] != 'select') {
                $data['value']['#multiple'] = TRUE;
              }
            }
            else if (!$data['value']) {
              $data['value'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
            }
            $views_tables['filters']['titles']["$name.$filter"] = $data['name'];
            $views_tables['filters']['base']["$name.$filter"] = $data;
          }
        }
        if (is_array($table['fields'])) {
          foreach ($table['fields'] as $field => $data) {
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
            $data['table'] = $name;
            $views_tables['fields']['titles']["$name.$field"] = $data['name'];
            $views_tables['fields']['base']["$name.$field"] = $data;
          }
        }
        if (is_array($table['sorts'])) {
          foreach ($table['sorts'] as $field => $data) {
            $data['table'] = $name;
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
            $views_tables['sorts']['titles']["$name.$field"] = $data['name'];
            $views_tables['sorts']['base']["$name.$field"] = $data;
          }
        }
      }
      cache_set("views_tables:$locale", serialize($views_tables));
    }
  }
  return ($full ? $views_tables : $views_tables['tables']);
}

/**
 * Gets the filter information; if it doesn't exist, call the function
 * that constructs all that.
 */
function _views_get_filters($titles = false) {
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['filters']['titles'] : $table_data['filters']['base']);
}

/**
 * Gets the field information; if it doesn't exist, call the function
 * that constructs all that.
 */
function _views_get_fields($titles = false) {
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['fields']['titles'] : $table_data['fields']['base']);
}

/**
 * Gets the sort information; if it doesn't exist, call the function
 * that constructs all that.
 */
function _views_get_sorts($titles = false) {
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['sorts']['titles'] : $table_data['sorts']['base']);
}

/**
 * Invalidate the views cache, forcing a rebuild on the next grab of table data.
 */
function views_invalidate_cache() {
  cache_clear_all('views_', true);
}

/**
 * Ensures that views have legitimate information; a bit more is stored on
 * the $view object than is in the database, and this isn't necessarily
 * set when a view is constructed externally.
 */
function _views_sanitize_view(&$view) {
  _views_check_arrays($view); // so reference works.
  foreach ($view->field as $i => $field) {
    $view->field[$i]['id'] = $view->field[$i]['fullname'] = "$field[tablename].$field[field]";
    $view->field[$i]['queryname'] = "$field[tablename]_$field[field]";
  }

  foreach ($view->filter as $i => $filter) {
    $view->filter[$i]['id'] = $view->filter[$i]['field'] = "$filter[tablename].$filter[field]";
  }

  foreach ($view->exposed_filter as $i => $exposed_filter) {
    $view->exposed_filter[$i]['id'] = $view->exposed_filter[$i]['field'] = "$exposed_filter[tablename].$exposed_filter[field]";
  }

  foreach ($view->sort as $i => $sort) {
    $view->sort[$i]['id'] = $view->sort[$i]['field'] = "$sort[tablename].$sort[field]";
  }

  foreach ($view->argument as $i => $argument) {
    $view->argument[$i]['id'] = $view->argument[$i]['type'];
  }
}

/**
 * Build default view information from all modules and cache it.
 */
function _views_get_default_views() {
  static $views_default_views;
  global $locale;

  if (!$views_default_views) {
    $data = cache_get("views_default_views:$locale");
    $cache = unserialize($data->data);

    if (is_array($cache)) {
      $views_default_views = $cache;
    }
    else {
      // We have to make sure table data is built in order to be sure about providers.
      $tables = array_keys(_views_get_tables());

      $views = module_invoke_all('views_default_views');
      $views_default_views = array();
      foreach ($views as $i => $view) {
        if (!is_array($view->requires) || !array_diff($view->requires, $tables)) {
          _views_sanitize_view($view);
          $views_default_views[$i] = $view;
        }
      }
      cache_set("views_default_views:$locale", serialize($views_default_views));
    }
  }
  return $views_default_views;
}

/**
 * Return the style plugins; construct one if we haven't already. The
 * array is cached in a static variable so that arguments
 * are only constructed once per run.
 */
function _views_get_style_plugins($titles = false) {
  static $views_style_plugins;
  global $locale;

  if (!$views_style_plugins) {
    $data = cache_get("views_style_plugins:$locale");
    $cache = unserialize($data->data);
    if (is_array($cache)) {
      $views_style_plugins = $cache;
    }
    else {
      $arguments = module_invoke_all('views_style_plugins');
      foreach ($arguments as $name => $arg) {
        $views_style_plugins['title'][$name] = $arg['name'];
        $views_style_plugins['base'][$name] = $arg;
      }
      $cache = $views_style_plugins;
      cache_set("views_style_plugins:$locale", serialize($cache));
    }
  }
  return ($titles ? $views_style_plugins['title'] : $views_style_plugins['base']);
}

// ---------------------------------------------------------------------------
// Drupal Hooks

/**
 * Implementation of hook_help()
 */
function views_help($section) {
  switch ($section) {
    case 'admin/help#views':
    case 'admin/modules#description':
      return t('The views module creates customized views of node lists.');
  }
}

/**
 * Implementation of hook_menu()
 */
function views_menu($may_cache) {
  $items = array();
  global $locale;

  if ($may_cache) {
    // Invalidate the views cache to ensure that views data gets rebuilt.
    // This is the best way to tell that module configuration has changed.
    if (arg(0) == 'admin' && arg(1) == 'modules') {
      views_invalidate_cache();
    }

    $result = db_query("SELECT * FROM {view_view} WHERE page = 1");
    $views_with_inline_args = array();

    while ($view = db_fetch_object($result)) {
      // unpack the array
      $view->access = ($view->access ? explode(', ', $view->access) : array());

      // This happens before the next check; even if it's put off for later
      // it is still used.
      $used[$view->name] = true;

      if (strrpos($view->url, '$arg')) {
        $arg_result = db_query("SELECT * FROM {view_argument} WHERE vid = %d", $view->vid);
        while ($view->argument[] = db_fetch_array($arg_result));
        array_pop($view->argument); // get rid of the NULL at the end.
        $views_with_inline_args[$view->name] = $view;
        continue;
      }
      _views_create_menu_item($items, $view, $view->url, array($view->name));
    }
    $default_views = _views_get_default_views();
    $views_status = variable_get('views_defaults', array());

    foreach ($default_views as $name => $view) {
      if ($view->page && !$used[$name] &&
       ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {

        if (strrpos($view->url, '$arg')) {
          $views_with_inline_args[$view->name] = $view;
          continue;
        }

        _views_create_menu_item($items, $view, $view->url, array($view->name));
      }
    }
    cache_set("views_with_inline_args:$locale", serialize($views_with_inline_args), CACHE_TEMPORARY);
  }
  else {
    $data = cache_get("views_with_inline_args:$locale");
    $views = unserialize($data->data);

    if (is_array($views)) {
      foreach ($views as $view) {
        // Do substitution on args.
        $view_args = array($view->name);
        $menu_path = array();
        foreach (explode('/', $view->url) as $num => $element) {
          if ($element == '$arg') {
            $menu_path[] = arg($num);
            $view_args[] = arg($num);
            $view->args[] = arg($num);
          }
          else {
            $menu_path[] = $element;
          }
        }
        $path = implode('/', $menu_path);
        _views_create_menu_item($items, $view, $path, $view_args, MENU_CALLBACK);
      }
    }
  }
  return $items;
}

/**
 * Helper function to add a menu item for a view.
 */
function _views_create_menu_item(&$items, $view, $path, $args, $local_task_type = MENU_NORMAL_ITEM) {
  static $roles = NULL;
  if ($roles == NULL) {
    global $user;
    $roles = array_keys($user->roles);
  }
  $title = views_get_title($view, 'menu');
  $type = _views_menu_type($view);
  if ($type == MENU_LOCAL_TASK || $type == MENU_DEFAULT_LOCAL_TASK) {
    $weight = $view->menu_tab_weight;
  }
  $access = !$view->access || array_intersect($view->access, $roles);
  $items[] = _views_menu_item($path, $title, $args, $access, $type, $weight);

  if ($type == MENU_DEFAULT_LOCAL_TASK) {
    $items[] = _views_menu_item(dirname($path), $title, $args, $access, $local_task_type, $weight);
  }
}

/**
 * Helper function to create a menu item for a view.
 */
function _views_menu_item($path, $title, $args, $access, $type, $weight = NULL) {
  $retval = array('path' => $path,
    'title' => $title,
    'callback' => 'views_view_page',
    'callback arguments' => $args,
    'access' => $access,
    'type' => $type,
  );
  if ($weight !== NULL) {
    $retval['weight'] = $weight;
  }
  return $retval;
}

/**
 * Determine what menu type a view needs to use.
 */
function _views_menu_type($view) {
  if ($view->menu) {
    if ($view->menu_tab_default) {
      $type = MENU_DEFAULT_LOCAL_TASK;
    }
    else if ($view->menu_tab) {
      $type = MENU_LOCAL_TASK;
    }
    else {
      $type = MENU_NORMAL_ITEM;
    }
  }
  else {
    $type = MENU_CALLBACK;
  }
  return $type;
}

/**
 * Implementation of hook_block()
 */
function views_block($op = 'list', $delta = 0) {
  $block = array();
  if ($op == 'list') {
    // Grab views from the database and provide them as blocks.
    $result = db_query("SELECT vid, block_title, page_title, name FROM {view_view} WHERE block = 1");
    while ($view = db_fetch_object($result)) {
      $block[$view->name]['info'] = views_get_title($view, 'block-info');
    }

    $default_views = _views_get_default_views();
    $views_status = variable_get('views_defaults', array());

    foreach ($default_views as $name => $view) {
      if (!isset($block[$name]) && $view->block &&
        ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {
        $block[$name]['info'] = views_get_title($view, 'block');
      }
    }
    return $block;
  }
  else if ($op == 'view') {
    return views_view_block($delta);
  }
}

// ---------------------------------------------------------------------------
// View Construction

/**
 * Ensure that all the arrays in a view exist so we don't run into array
 * operations on a non-array error.
 */
function _views_check_arrays(&$view) {
  $fields = array('field', 'sort', 'argument', 'filter', 'exposed_filter', 'access');

  foreach($fields as $field) {
    if (!is_array($view->$field)) {
      $view->$field = array();
    }
  }
  return $view;
}

/**
 * This function loads a view by name or vid; if not found in db, it looks
 * for a default view by that name.
 */
function views_get_view($view_name) {
  $view = _views_load_view($view_name);
  if ($view) {
    return $view;
  }

  if (is_int($view_name)) {
    return; // don't bother looking if view_name is an int!
  }

  $default_views = _views_get_default_views();

  if (isset($default_views[$view_name])) {
    return $default_views[$view_name];
  }
}

/**
 * This views a view by page, and should only be used as a callback.
 */
function views_view_page() {
  $args = func_get_args();
  // FIXME: Most of this code is unnecessary now that we add our
  // $view info as a callback argument via the menu hook.
  while ($next = array_shift($args)) {
    if (!$view_name) {
      $view_name = $next;
    }
    else {
      $view_name .= "/$next";
    }

    if ($view = views_get_view($view_name)) {
      break;
    }
  }
  if (!$view) {
    drupal_not_found();
    exit;
  }

  $output = views_build_view('page', $view, $args, $view->use_pager, $view->nodes_per_page);
  if ($output === FALSE) {
    drupal_not_found();
    exit;
  }

  return $output;
}

/**
 * This views a view by block. Can be used as a callback or programmatically.
 */
function views_view_block($vid) {
  $view = views_get_view($vid);

  if (!$view || !$view->block) {
    return NULL;
  }

  global $user;
  $roles = array_keys($user->roles);
  if ($view->access && !array_intersect($roles, $view->access)) {
    return NULL;
  }

  $content = views_build_view('block', $view, array(), false, $view->nodes_per_block);
  if ($content) {
    $block['content'] = $content;
    $block['subject'] = views_get_title($view, 'block');
    return $block;
  }
  else {
    return NULL;
  }
}

/**
 * This builds the basic view.
 * @param $type
 *    'page' -- Produce output as a page, sent through theme.
 *      The only real difference between this and block is that
 *      a page uses drupal_set_title to change the page title.
 *    'block' -- Produce output as a block, sent through theme.
 *    'embed' -- Use this if you want to embed a view onto another page,
 *      and don't want any block or page specific things to happen to it.
 *    'result' -- return an $info array. The array contains:
 *      query: The actual query ran.
 *      countquery: The count query that would be run if limiting was required.
 *      summary: True if an argument was missing and a summary was generated.
 *      level: What level the missing argument was at.
 *      result: Database object you can use db_fetch_object on.
 *    'items' -- return info array as above, except instead of result,
 *      items: An array of objects containing the results of the query.
 * @param $view
 *   The actual view object. Use views_get_view() if you only have the name or
 *   vid.
 * @param $args
 *   args taken from the URL. Not relevant for many views. Can be null.
 * @param $use_pager
 *   If set, use a pager. Set this to the pager id you want it
 *   to use if you plan on using multiple pagers on a page. To go with the
 *   default setting, set to $view->use_pager.
 * @param $limit
 *   Required if $use_pager is set; if $limit is set and $use_pager is
 *   not, this will be the maximum number of records returned. This is ignored
 *   if using a view set to return a random result. To go with the default
 *   setting set to $view->nodes_per_page or $view->nodes_per_block. If
 *   $use_pager is set and this field is not, you'll get a SQL error. Don't
 *   do that!
 * @param $page
 *   $use_pager is false, and $limit is !0, $page tells it what page to start
 *   on, in case for some reason a particular section of view is needed,
 *   without paging on.
*/
function views_build_view($type, $view, $args = array(), $use_pager = false, $limit = 0, $page = 0) {
  $GLOBALS['current_view'] = &$view;

  $viewtype = ($type == 'block' ? $view->block_type : $view->page_type);

  if ($view->view_args_php) {
    ob_start();
    $args = eval($view->view_args_php);
    ob_end_clean();
  }

  if ($view->query) {
    $info['query'] = $view->query;
    $info['countquery'] = $view->countquery;

    if ($viewtype == 'table') {
      $view->table_header = _views_construct_header($view, $fields);
    }
  }
  else {
    $path = drupal_get_path('module', 'views');
    require_once("$path/views_query.inc");

    $info = _views_build_query($view, $args);
    if ($info['fail']) {
      return FALSE;
    }
  }

  // Run-time replacement so we can do cacheing
  $replacements = module_invoke_all('views_query_substitutions', $view);
  foreach ($replacements as $src => $dest) {
    $info['query'] = str_replace($src, $dest, $info['query']);
    $info['countquery'] = str_replace($src, $dest, $info['countquery']);
    
    foreach ($info['args'] as $id => $arg) {
      $info['args'][$id] = str_replace($src, $dest, $arg);
    }
  }

  $query = db_rewrite_sql($info['query'], 'node');

  if ($use_pager) {
    $cquery = db_rewrite_sql($info['countquery'], 'node', 'nid', $info['rewrite_args']);
    $result = pager_query($query, $limit, $use_pager, $cquery, $info['args']);
  }
  else {
    $result = ($limit ? db_query_range($query, $info['args'], $page * $limit, $limit) : db_query($query, $info['args']));
  }

  if ($type == 'result') {
    $info['result'] = $result;
    return $info;
  }

  $items = array();
  while ($item = db_fetch_object($result)) {
    $items[] = $item;
  }

  if ($type == 'items') {
    $info['items'] = $items;
    return $info;
  }

  // Call a hook that'll let modules modify the view just before it is displayed.
  foreach (module_implements('views_pre_view') as $module) {
    $function = $module .'_views_pre_view';
    $output .= $function($view, $items);
  }

/*
  // In block mode, change $view->url to include the proper arguments.
  if ($type == 'block' && $args) {
    $url = views_get_summary_link_base($view->argument[count($args)-1]['type'], $view->url, count($args), $args);
    if ($url) {
      $view->url = $url;
    }
  }
*/
  $view->real_url = views_get_url($view, $args);

  $view->use_pager = $use_pager;
  $output .= views_theme('views_view', $view, $type, $items, $info['level'], $args);

  // Call a hook that'll let modules modify the view just after it is displayed.
  foreach (module_implements('views_post_view') as $module) {
    $function = $module .'_views_post_view';
    $output .= $function($view, $items, $output);
  }

  return $output;
}

// ---------------------------------------------------------------------------
// Utility

/**
 * Easily theme any item to a view.
 * @param $function
 *   The name of the function to call.
 * @param $view
 *   The view being themed.
 */
function views_theme() {
  $args = func_get_args();
  $function = array_shift($args);
  $view = $args[0];

  if (!($func = theme_get_function($function . "_" . $view->name))) {
    $func = theme_get_function($function);
  }

  if ($func) {
    return call_user_func_array($func, $args);
  }
}

/**
 * Easily theme any item to a field name.
 * field name will be in the format of TABLENAME_FIELDNAME
 * You have to understand a bit about the views data to utilize this.
 *
 * @param $function
 *   The name of the function to call.
 * @param $field_name
 *   The field being themed.
 */
function views_theme_field() {
  $args = func_get_args();
  $function = array_shift($args);
  $field_name = array_shift($args);

  if (!($func = theme_get_function($function . "_" . $field_name))) {
    $func = theme_get_function($function);
  }

  if ($func) {
    return call_user_func_array($func, $args);
  }
}

/**
 * Figure out what timezone we're in; needed for some date manipulations.
 */
function _views_get_timezone() {
  global $user;
  if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
    $timezone = $user->timezone;
  }
  else {
    $timezone = variable_get('date_default_timezone', 0);
  }

  return $timezone;
}

/**
 * Figure out what the URL of the view we're currently looking at is.
 */
function views_get_url($view, $args) {
  $url = $view->url;

  $where = 1;
  foreach ($args as $arg) {
    // This odd construct prevents us from strposing once there is no
    // longer an $arg to replace.
    if ($where && $where = strpos('$arg', $url)) {
      $url = str_replace($url, $arg, $where, 4);
    }
    else {
      $url .= "/$arg";
    }
  }

  return $url;
}

/**
 * Figure out what the title of a view should be.
 */
function views_get_title($view, $context = 'menu', $args = NULL) {
  if ($context == 'menu' && $view->menu_title)
    return $view->menu_title;

  if ($context == 'block' && $view->block_title) {
    return $view->block_title;
  }

  if ($context == 'block-info') {
    return $view->description ? $view->description : $view->name;
  }

  if ($args === NULL)
    $args = $view->args;

  $count = count($args);
  if ($count >= count($view->argument)) {
    $title = $view->page_title;
  }
  else {
    $title = $view->argument[$count]['title'];
  }
  if (!$title && $context == 'menu') {
    $title = $view->block_title;
  }

  if (!$view->argument) {
    return $title;
  }

  $arginfo = _views_get_arguments();
  foreach ($view->argument as $i => $arg) {
    if (!isset($args[$i])) {
      break;
    }
    $argtype = $arg['type'];
    if (function_exists($arginfo[$argtype]['handler'])) {
      // call the handler
      $rep = $arginfo[$argtype]['handler']('title', $args[$i], $argtype);
      $title = str_replace("%" . ($i + 1), $rep, $title);

    }
  }
  return $title;
}

/**
 * Determine whether or not a view is cacheable. A view is not cacheable if
 * there is some kind of user input or data required. For example, views
 * that need to restrict to the 'current' user, or any views that require
 * arguments or allow click-sorting are not cacheable.
 */
function _views_is_cacheable(&$view) {
  // views with arguments are immediately not cacheable.
  if (!empty($view->argument) || !empty($view->exposed_filter)) {
    return false;
  }

  $filters = _views_get_filters();

  foreach ($view->filter as $i => $filter) {
    if ($filters[$filter['field']]['cacheable'] == 'no')  {
      return false;
    }
  }

  foreach ($view->field as $i => $field) {
    if ($field['sortable']) {
      return false;
    }
  }
  return true;
}

// ---------------------------------------------------------------------------
// Database functions

/**
 * Provide all the fields in a view.
 */
function _views_view_fields() {
  return array('vid', 'name', 'description', 'access', 'page', 'page_title', 'page_header', 'page_header_format', 'page_footer', 'page_footer_format', 'page_empty', 'page_empty_format', 'page_type', 'use_pager', 'nodes_per_page', 'url', 'menu', 'menu_tab', 'menu_tab_default', 'menu_tab_weight', 'menu_title', 'block', 'block_title', 'block_use_page_header', 'block_header', 'block_header_format', 'block_use_page_footer', 'block_footer', 'block_footer_format', 'block_use_page_empty', 'block_empty', 'block_empty_format', 'block_type', 'nodes_per_block', 'block_more', 'url', 'breadcrumb_no_home', 'changed', 'query', 'countquery', 'view_args_php');
}

/**
 * Delete a view from the database.
 */
function _views_delete_view($view) {
  $view->vid = intval($view->vid);
  if (!$view->vid) {
    return;
  }

  db_query("DELETE FROM {view_view} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_sort} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_argument} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_tablefield} where vid=%d", $view->vid);
}

/**
 * Load a view from the database.
 */
function _views_load_view($arg) {
  static $cache = array();
  $which = is_numeric($arg) ? 'vid' : 'name';
  if (isset($cache[$which][$arg])) {
    return $cache[$which][$arg];
  }

  $where = (is_numeric($arg) ? "v.vid =  %d" : "v.name = '%s'");
  $view = db_fetch_object(db_query("SELECT v.* FROM {view_view} v WHERE $where", $arg));

  if (!$view->name) {
    return NULL;
  }

  $view->access = ($view->access ? explode(', ', $view->access) : array());

  // load the sorting criteria too.
  $result = db_query("SELECT * FROM {view_sort} vs WHERE vid = $view->vid ORDER BY position ASC");

  $view->sort = array();
  while ($sort = db_fetch_array($result)) {
    if (substr($sort['field'], 0, 2) == 'n.') {
      $sort['field'] = 'node' . substr($sort['field'], 1);
    }
    $sort['id'] = $sort['field'];
    $view->sort[] = $sort;
  }

  $result = db_query("SELECT * FROM {view_argument} WHERE vid = $view->vid ORDER BY position ASC");

  $view->argument = array();
  while ($arg = db_fetch_array($result)) {
    $arg['id'] = $arg['type'];
    $view->argument[] = $arg;
  }

  $result = db_query("SELECT * FROM {view_tablefield} WHERE vid = $view->vid ORDER BY position ASC");

  $view->field = array();
  while ($arg = db_fetch_array($result)) {
    if ($arg['tablename'] == 'n') {
      $arg['tablename'] = 'node';
    }
    $arg['id'] = $arg['fullname'] = "$arg[tablename].$arg[field]";
    $arg['queryname'] = "$arg[tablename]_$arg[field]";
    $view->field[] = $arg;
  }

  $result = db_query("SELECT * FROM {view_filter} WHERE vid = $view->vid ORDER BY position ASC");

  $filters = _views_get_filters();
  $view->filter = array();
  while ($filter = db_fetch_array($result)) {
    if (substr($filter['field'], 0, 2) == 'n.') {
      $filter['field'] = 'node' . substr($filter['field'], 1);
    }

    if ($filter['operator'] == 'AND' ||
        $filter['operator'] == 'OR' ||
        $filter['operator'] == 'NOR' ||
        $filters[$filter['field']]['value-type'] == 'array' ) {
      if ($filter['value'] !== NULL && $filter['value'] !== '') {
        $filter['value'] = explode(',', $filter['value']);
      }
      else {
        $filter['value'] = array();
      }
    }
    $filter['id'] = $filter['field'];
    $view->filter[] = $filter;
  }

  $result = db_query("SELECT * FROM {view_exposed_filter} WHERE vid = $view->vid ORDER BY position ASC");

  $view->exposed_filter = array();
  while ($arg = db_fetch_array($result)) {
    $arg['id'] = $arg['field'];
    $view->exposed_filter[] = $arg;
  }

  $cache['vid'][$view->vid] = $view;
  $cache['name'][$view->name] = $view;

  return $view;
}

/**
 * Save a view to the database.
 */
function _views_save_view($view) {
  _views_check_arrays($view);

  // cache the query
  if (_views_is_cacheable($view)) {
    $path = drupal_get_path('module', 'views');
    require_once("$path/views_query.inc");

    $info = _views_build_query($view);
    $view->query = _views_replace_args($info['query'], $info['args']);
    $view->countquery = _views_replace_args($info['countquery'], $info['args']);
  }
  else {
    $view->query = NULL;
    $view->countquery = NULL;
  }

  $view->access = implode(', ', $view->access);

  $view->changed = time();
  $fields = _views_view_fields();
  if ($view->vid) {
    // update
    // Prepare the query:
    foreach ($view as $key => $value) {
      if (in_array($key, $fields)) {
        $q[] = db_escape_string($key) ." = '%s'";
        $v[] = $value;
      }
    }

    // Update the view in the database:
    db_query("UPDATE {view_view} SET ". implode(', ', $q) ." WHERE vid = '$view->vid'", $v);
    db_query("DELETE from {view_sort} WHERE vid='$view->vid'");
    db_query("DELETE from {view_argument} WHERE vid='$view->vid'");
    db_query("DELETE from {view_tablefield} WHERE vid='$view->vid'");
    db_query("DELETE from {view_filter} WHERE vid='$view->vid'");
    db_query("DELETE from {view_exposed_filter} WHERE vid='$view->vid'");
  }
  else {
    // insert

    // This method really saves on typos, and makes it a lot easier to add fields
    // later on.
    $view->vid = db_next_id('{view_view}_vid');

    // Prepare the query:
    foreach ($view as $key => $value) {
      if (in_array((string) $key, $fields)) {
        $k[] = db_escape_string($key);
        $v[] = $value;
        $s[] = is_numeric($value) ? '%d' : "'%s'";
      }
    }

    db_query("INSERT INTO {view_view} (". implode(", ", $k) .") VALUES (". implode(", ", $s) .")", $v);
  }

  foreach ($view->sort as $i => $sort) {
    db_query("INSERT INTO {view_sort} (vid, position, field, sortorder, options) VALUES (%d, %d, '%s', '%s', '%s')", $view->vid, $i, $sort['field'], $sort['sortorder'], $sort['options']);
  }

  foreach ($view->argument as $i => $arg) {
    db_query("INSERT INTO {view_argument} (vid, type, argdefault, title, options, position) VALUES (%d, '%s', %d, '%s', '%s', %d)", $view->vid, $arg['type'], $arg['argdefault'], $arg['title'], $arg['options'], $i);
  }

  foreach ($view->field as $i => $arg) {
    db_query("INSERT INTO {view_tablefield} (vid, tablename, field, label, handler, sortable, defaultsort, options, position) VALUES (%d, '%s', '%s', '%s', '%s', %d, '%s', '%s', %d)", $view->vid, $arg['tablename'], $arg['field'], $arg['label'], $arg['handler'], $arg['sortable'], $arg['defaultsort'], $arg['options'], $i);
  }

  foreach ($view->filter as $i => $arg) {
    if (is_array($arg['value'])) {
      $arg['value'] = implode(',', $arg['value']);
    }
    db_query("INSERT INTO {view_filter} (vid, tablename, field, value, operator, options, position) VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d)", $view->vid, $arg['tablename'], $arg['field'], $arg['value'], $arg['operator'], $arg['options'], $i);
  }

  foreach ($view->exposed_filter as $i => $arg) {
    db_query("INSERT INTO {view_exposed_filter} (vid, field, label, optional, is_default, single, operator, position) VALUES (%d, '%s', '%s', %d, %d, %d, %d, %d)", $view->vid, $arg['field'], $arg['label'], $arg['optional'], $arg['is_default'], $arg['single'], $arg['operator'], $i);
  }
}

// ---------------------------------------------------------------------------
// Helper functions to build views and view data

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to a $table array and returns it.
 */
function views_new_table($table_name, $provider, $left_table, $left_field, $right_field, $extra = NULL) {
  $table['name'] = $table_name;
  $table['provider'] = $provider;
  $table['join']['left']['table'] = $left_table;
  $table['join']['left']['field'] = $left_field;
  $table['join']['right']['field'] = $left_field;
  if ($extra) {
    $table['join']['extra'] = $extra;
  }
  return $table;
}

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to the $table array.
 */
function views_table_add_field(&$table, $name, $label, $help, $others = array()) {
  views_table_add_data($table, 'fields', $name, $label, $help, $others);
}

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to the $table array.
 */
function views_table_add_filter(&$table, $name, $label, $help, $others = array()) {
  views_table_add_data($table, 'filters', $name, $label, $help, $others);
}

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to the $table array.
 */
function views_table_add_sort(&$table, $name, $label, $help, $others = array()) {
  views_table_add_data($table, 'sorts', $name, $label, $help, $others);
}

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to the $table array.
 */
function views_table_add_data(&$table, $type, $name, $label, $help, $others = array()) {
  $table[$type][$name]['name'] = $label;
  $table[$type][$name]['help'] = $help;
  foreach ($others as $key => $value) {
    $table[$type][$name][$key] = $value;
  }
}

/**
 * Create a blank view.
 */
function views_create_view($name, $description, $access = array()) {
  $view = new stdClass();
  _views_check_arrays($view);

  $view->name = $name;
  $view->description = $description;
  $view->access = $access;
  
  // ensure some things are numerically 0.
  $view->nodes_per_page = 0;
  $view->nodes_per_block = 0;
  return $view;
}

/**
 * Add page info to a view.
 */
function views_view_add_page(&$view, $title, $url, $type, $pager, $nodes_per_page, $header, $header_format, $breadcrumb_no_home = FALSE) {
  $view->page = TRUE;
  $view->page_title = $title;
  $view->url = $url;
  $view->page_type = $type;
  $view->use_pager = $pager;
  $view->nodes_per_page = $nodes_per_page;
  $view->page_header = $header;
  $view->page_header_format = $header_format;
  $view->breadcrumb_no_home = $breadcrumb_no_home;
}

/**
 * Add menu info to a view.
 */
function views_view_add_menu(&$view, $title, $tab, $tab_weight, $default_tab) {
  $view->menu = TRUE;
  $view->menu_title = $title;
  $view->menu_tab = $tab;
  $view->menu_tab_weight = $tab_weight;
  $view->menu_tab_default = $default_tab;
}

/**
 * Add block info to a view.
 */
function views_view_add_block(&$view, $title, $type, $nodes_per_block, $more, $use_page_header, $header = '', $header_format = 0) {
  $view->block = TRUE;
  $view->block_title = $title;
  $view->block_type = $type;
  $view->nodes_per_block = $nodes_per_block;
  $view->block_more = $more;
  $view->block_use_page_header = $use_page_header;
  $view->block_header = $header;
  $view->block_header_format = $header_format;
}

/**
 * Add field info to a view.
 */
function views_view_add_field(&$view, $table, $field, $label, $sortable = FALSE, $default_sort = 0, $handler = '') {
  $view->filter[] = array(
    'tablename' => $table,
    'field' => $field,
    'label' => $label,
    'sortable' => $sortable,
    'defaultsort' => $default_sort,
    'handler' => $handler
  );
}

/**
 * Add argument info to a view.
 */
function views_view_add_argument(&$view, $type, $default, $title, $option = '') {
  $view->argument[] = array(
    'type' => $type,
    'argdefault' => $default,
    'title' => $title,
    'options' => $option,
  );
}

/**
 * Add filter info to a view.
 */
function views_view_add_filter(&$view, $table, $field, $operator, $value, $option) {
  $view->filter[] = array(
    'tablename' => $table,
    'field' => $field,
    'operator' => $operator,
    'value' => $value,
    'options' => $option,
  );
}

/**
 * Add exposed_filter info to a view.
 */
function views_view_add_exposed_filter(&$view, $table, $field, $optional, $is_default, $lock_operator, $single) {
  $view->exposed_filter[] = array(
    'tablename' => $table,
    'field' => $field,
    'optional' => $optional,
    'is_default' => $is_default,
    'operator' => $lock_operator,
    'single' => $single
  );
}

/**
 * Add sort info to a view.
 */
function views_view_add_sort(&$view, $table, $field, $order, $option) {
  $view->sort[] = array(
    'tablename' => $table,
    'field' => $field,
    'sortorder' => $order,
    'options' => $option
  );
}

// ---------------------------------------------------------------------------
// Themeable and support for themeables.

/**
 * Figure out how to display the data of a field. Many fields simply display
 * the data as-is, but many fields have to massage that data, which is
 * done through handlers.
 * 
 * DEPRECATED. Left in for backward compatibility.
 */
function _views_handle_field($fields, $field, $data) {
  return views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $data);
}

/**
 * Themeable function to handle displaying a specific field.
 */
function theme_views_handle_field($fields, $field, $data) {
  $info = $fields[$field['fullname']];

  if ($field['handler'] && function_exists($field['handler'])) {
    return $field['handler']($info, $field, $data->$field['queryname'], $data);
  }

  if ($info['handler'] && is_string($info['handler']) && function_exists($info['handler'])) {
    return $info['handler']($info, $field, $data->$field['queryname'], $data);
  }

  return check_plain($data->$field['queryname']);
}

/**
 * Construct a header for a table view.
 */
function _views_construct_header($view, $fields) {
  foreach ($view->field as $field) {
    $header = array();
    $info = $fields[$field['fullname']];

    $header['data'] = ($field['label'] ? $field['label'] : $info['name']);

    if ($field['sortable']) {
      $header['field'] = $field['fullname'];
    }
    if ($field['defaultsort']) {
      $header['sort'] = strtolower($field['defaultsort']);
    }

    // Add CSS id to table cell header cell.
    $header['id'] = "view-field-$field[queryname]";
    $header['class'] = "view-cell-header";
    $headers[] = $header;
  }
  return $headers;
}

function theme_views_display_filters($view) {
  $filters = _views_get_filters();
  foreach ($view->exposed_filter as $count => $expose) {
    $id = $expose['id'];
    $filterinfo = $filters[$id];
    foreach ($view->filter as $filter) {
      if ($filter['id'] == $id) {
        break;
      }
    }

    // set up the operator widget.
    if (!$expose['operator']) {
      // 'operator' is either an array or a handler
      $operator = $filterinfo['operator'];
      if (!is_array($operator) && function_exists($filterinfo['operator']))  {
        $operator = $filterinfo['operator']('operator', $filterinfo);
      }

      $form["op$count"] = array(
        '#name' => "op$count", // get rid of edit[] array.
        '#type' => 'select',
        '#default_value' => $filter['operator'],
        '#options' => $operator,
      );
      if (array_key_exists("op$count", $_GET)) {
        $form["op$count"]["#default_value"] = $_GET["op$count"];
      }
    }

    // set up the filter widget.
    $item = $filterinfo['value'];
    $item['#name'] = "filter$count";

    if (!is_array($item['#options']) && function_exists($item['#options'])) {
      $item['#options'] = $item['#options']('value', $filterinfo);
    }
    if (!$expose['optional'] || $expose['is_default']) {
      $item['#default_value'] = $filter['value'];
    }

    if ($expose['single']) {
      unset($item['#multiple']);
    }
    if ($expose['optional'] && is_array($item['#options'])) {
      $item['#options'] = array('**ALL**' => t('<All>')) + $item['#options'];
    }

    if (array_key_exists("filter$count", $_GET)) {
      $item["#default_value"] = $_GET["filter$count"];
    }
    $form["filter$count"] = $item;
  }
  $form['#method'] = 'get';
  $form['view'] = array('#type' => 'value', '#value' => $view);
  $form['submit'] = array('#type' => 'button', '#value' => t('Submit'));

  return drupal_get_form("views_filters_$view->name", $form, 'views_filters');
}

function theme_views_filters($form) {
  $view = $form['view']['#value'];
  foreach ($view->exposed_filter as $count => $expose) {
    $row[] = form_render($form["op$count"]) . form_render($form["filter$count"]);
    $label[] = $expose['label'];
  }
  $row[] = form_render($form['submit']);
  $label[] = ''; // so the column count is the same.
  return theme('table', $label, array($row)) . form_render($form);
}

/**
 * Display the nodes of a view as a list.
 */
function theme_views_view_list($view, $nodes) {
  $fields = _views_get_fields();

  foreach ($nodes as $node) {
    $item = '';
    foreach ($view->field as $field) {
      if ($field['label']) {
        $item .= "<div class='view-label view-label-$field[queryname]'>" . $field['label'] . "</div>";
      }
      $item .= "<div class='view-field view-data-$field[queryname]'>" . views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node) . "</div>";
    }
    $items[] = "<div class='view-item view-item-$view->name'>$item</div>\n"; // l($node->title, "node/$node->nid");
  }
  if ($items) {
    return theme('item_list', $items);
  }
}

/**
 * Display the nodes of a view as a table.
 */
function theme_views_view_table($view, $nodes) {
  $fields = _views_get_fields();

  foreach ($nodes as $node) {
    $row = array();
    foreach ($view->field as $field) {
      $cell['data'] = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node);
      $cell['class'] = "view-field view-field-$field[queryname]";
      $row[] = $cell;
    }
    $rows[] = $row;
  }
  return theme('table', $view->table_header, $rows);
}

/**
 * Display the nodes of a view as teasers.
 */
function theme_views_view_teasers($view, $nodes) {
  return views_theme('views_view_nodes', $view, $nodes, true); 
}

/**
 * Display the nodes of a view as plain nodes.
 */
function theme_views_view_nodes($view, $nodes, $teasers = false, $links = true) {
  foreach ($nodes as $n) {
    $node = node_load($n->nid);
    $output .= node_view($node, $teasers, false, $links);
  }
  return $output;
}

function views_set_breadcrumb($view) {
  $breadcrumb = drupal_get_breadcrumb();
  if ($view->breadcrumb_no_home) {
    array_shift($breadcrumb);
  }

  if ($view->args) {
    // Add a breadcrumb trail for each level of argument we're at.
    $url = $view->url;
    $args = array();
    $where = 1;
    foreach ($view->args as $level => $arg) {
      if ($view->argument[$level]['argdefault'] != 1) {
        $breadcrumb[] = l(views_get_title($view, 'page', $args), $url);
        // For next round.
      }
      $args[] = $arg;
      if ($where && $where = strpos('$arg', $url)) {
        $url = str_replace($url, $arg, $where, 4);
      }
      else {
        $url .= "/$arg";
      }
    }
  }

  drupal_set_breadcrumb($breadcrumb);
}

function views_get_textarea($view, $type, $textarea) {
  $use_page = "block_use_page_$textarea";
  $var = ($type != 'block' || $view->$use_page ? 'page_' : 'block_') . $textarea;
  $format = $var . '_format';

  if ($view->$var) {
    return "<div class='view-$textarea view-$textarea-$view->name'>"
      . check_markup($view->$var, $view->$format, false) . "</div>\n";
  }
}

/**
 * Display a view.
 */
function theme_views_view($view, $type, $nodes, $level = NULL, $args = NULL) {
  $num_nodes = count($nodes);

  if ($type == 'page') {
    drupal_set_title(views_get_title($view, 'page'));
    views_set_breadcrumb($view);
  }

  if ($num_nodes) {
    $output .= views_get_textarea($view, $type, 'header');
  }

  if ($type != 'block' && $view->exposed_filter) {
    $output .= views_theme('views_display_filters', $view);
  }

  if ($num_nodes) {

    if ($level !== NULL) {
      $output .= views_theme('views_summary', $view, $type, $level, $nodes, $args);
    }
    else {
      $plugins = _views_get_style_plugins();
      $view_type = ($type == 'block') ? $view->block_type : $view->page_type;
      $output .= views_theme($plugins[$view_type]['theme'], $view, $nodes);
    }
    $output .= views_get_textarea($view, $type, 'footer');

    if ($type == 'block' && $view->block_more && $num_nodes >= $view->nodes_per_block) {
      $output .= theme('views_more', $view->real_url);
    }
  }
  else {
    $output .= views_get_textarea($view, $type, 'empty');
  }

  if ($view->use_pager) {
    $output .= theme('pager', '', $limit, $view->use_pager);
  }

  if ($output) {
    $output = "<div class='view view-$view->name'>$output</div>\n";
  }
  return $output;
}

/**
 * Format the 'more' link for a view. Personally I prefer [More] but I've
 * been convinced to go with simply 'more'.
 */
function theme_views_more($url) {
  return "<div class='more-link'>" . l(t('more'), $url) . "</div>";
}

/**
 * Get the summary link for a view.
 */
function views_get_summary_link($argtype, $item, $base) {
  $arginfo = _views_get_arguments();
  return $arginfo[$argtype]['handler']('link', $item, $argtype, $base);
}

/**
 * In a summary view, each entry links to a more specific entry
 * in that view. Construct the base of that link.
 */
/*
function views_get_summary_link_base($argtype, $url, $level, $args) {
  $arginfo = _views_get_arguments();
  if (!function_exists($arginfo[$argtype]['handler'])) {
    return NULL;
  }

  $arg = $url;
  for ($i = 0; $i < $level; $i++) {
    $arg .= "/$args[$i]";
  }

  return $arg;
}
*/
/**
 * Display a summary version of a view.
 */
function theme_views_summary($view, $type, $level, $nodes, $args) {
//  $base = views_get_summary_link_base($view->argument[$level]['type'], $view->url, $level, $args);
  foreach ($nodes as $node) {
    $items[] = views_get_summary_link($view->argument[$level]['type'], $node, $view->real_url)  . " (" . $node->num_nodes . ")";
  }
  if ($items) {
    $output .= theme('item_list', $items);
  }

  return $output;
}

// ---------------------------------------------------------------------------
// Generic handlers. These make sense to be used in a lot of different places.

/**
 * Field handlers accept the following arguments:
 * @param $fieldinfo
 *   The array of info for that field from the global tables array.
 * @param $fielddata
 *   All of the info about that field in the database.
 * @param $value
 *   The value of the field fetched from the database.
 * @param $data
 *   The rest of the data about the node fetched from the database, in case
 *   the handler needs more than just the field.
 */

/**
 * Format a date.
 */
function views_handler_field_date($fieldinfo, $fielddata, $value, $data) {
  return format_date($value);
}

/**
 * Format a date using small representation.
 */
function views_handler_field_date_small($fieldinfo, $fielddata, $value, $data) {
  return format_date($value, 'small');
}

/**
 * Format a date using large representation.
 */
function views_handler_field_date_large($fieldinfo, $fielddata, $value, $data) {
  return format_date($value, 'large');
}

/**
 * Format a date using custom representation.
 */
function views_handler_field_date_custom($fieldinfo, $fielddata, $value, $data) {
  return format_date($value, 'custom', $fielddata['options']);
}
/**
 * Format a date as "X time ago".
 */
function views_handler_field_since($fieldinfo, $fielddata, $value, $data) {
  return format_interval(time() - $value);
}

/**
 * Provide a list of all standard supproted date output handlers.
 */
function views_handler_field_dates() {
return array(
    'views_handler_field_date_small'  => t('As Short Date'),
    'views_handler_field_date'        => t('As Medium Date'),
    'views_handler_field_date_large'  => t('As Long Date'),
    'views_handler_field_date_custom' => t('As Custom Date'),
    'views_handler_field_since'       => t('As Time Ago')
  );
}

/**
 * Format a field as an integer.
 */
function views_handler_field_int($fieldinfo, $fielddata, $value, $data) {
  return intval($value);
}

/**
 * Argument handlers take up to 4 fields, which vary based upon the operation.
 * @param $op
 *   The operation to perform:
 *   'summary': A summary view is being constructed. In this case the handler
 *              is to add the necessary components to the query to display
 *              the summary. It must return a $fieldinfo array with 'field'
 *              set to the field the summary is ordered by; if this is aliased
 *              for some reason (such as being an aggregate field) set 'fieldname'
 *              to the alias.
 *    'sort':   Set up the view to sort based upon the setting in $a2.
 *    'filter': Filter the view based upon the argument sent; essentially just
 *              add the where clause here.
 *    'link':   Provide a link from a summary view based upon the argument sent.
 *    'title':  Provide the title of a view for substitution.
 * @param &$query
 *   For summary, filter and link, this is the actual query object; for title this is
 *   simply the value of the argument.
 * @param $a2
 *   For summary, this is the type of the argument. For the others, this is the info
 *   for the argument from the global table. (Why is this not consistent? I dunno).
 * @param $a3
 *   For summary, this is the 'options' field from the db. For 'filter' this is
 *   the argument received. For 'link' this is the base URL of the link. Not used
 *   for 'title'.
 *
 */

// ---------------------------------------------------------------------------
// Filter handlers

/**
 * There are two kinds of filter handlers here; the easy kind simply creates an
 * array of options. For example, for taxonomy we provide a list of all taxonomy
 * terms which is placed in the select box.
 *
 * The other type is the 'custom' handler which is used to create a customized
 * WHERE clause for specialized filters.
 *
 * It takes 4 parameters.
 * @param $op
 *   At this time it will always be 'handler'.
 * @param $filter
 *   Information on the filter from the database, including 'options', 'value' and 'operator'.
 * @param $filterinfo
 *   Information on the filter from the global table array.
 * @param &$query
 *   The query object being worked on.
 */

/**
 * A list of and/or/nor.
 */
function views_handler_operator_andor() {
  return array('AND' => t('Is All Of'), 'OR' => t('Is One Of'), 'NOR' => t('Is None Of'));
}

/**
 * A list of or/nor.
 */
function views_handler_operator_or() {
  return array('OR' => t('Is One Of'), 'NOR' => t('Is None Of'));
}

/**
 * A list of equal or not equal to.
 */
function views_handler_operator_eqneq() {
  return array('=' => t('Is Equal To'), '!=' => t('Is Not Equal To'));
}

 /**
 * A list of greater / equal / less than
 */
function views_handler_operator_gtlt() {
  return array('>' => t("Is Greater Than"), '>=' => t("Is Greater Than Or Equals"), '=' => t("Is Equal To"), '!=' => t("Is Not Equal To"), '<=' => t("Is Less Than Or Equals"), '<' => t("Is Less Than"));
}

/**
 * A list of yes/no.
 */
function views_handler_operator_yesno() {
  return array('1' => t('Yes'), '0' => t('No'));
}

/**
 * Default Views style plugins. Implementation of hook_views_style_plugins()
 */
function views_views_style_plugins() {
  return array(
    'list' => array(
      'name' => t('List View'),
      'theme' => 'views_view_list',
      'validate' => 'views_ui_plugin_validate_list',
    ),
    'table' => array(
      'name' => t('Table View'),
      'theme' => 'views_view_table',
      'validate' => 'views_ui_plugin_validate_table',
    ),
    'teaser' => array(
      'name' => t('Teaser List'),
      'theme' => 'views_view_teasers',
    ),
    'node' => array(
      'name' => t('Full Nodes'),
      'theme' => 'views_view_nodes',
    ),
  );
}

/**
 * A list of options to be used in LIKE queries
 */
function views_handler_operator_like() {
  return array('=' => t('Is Equal To'), 'contains' => t('Contains'), 'starts' => t('Starts With'), 'ends' => t('Ends With'), 'not' => t('Does Not Contain'));
}

/**
 * Custom filter for LIKE operations
 */
function views_handler_filter_like($op, $filter, $filterinfo, &$query) {
  switch (trim($filter['value'])) {
    case (''):
      return;
      break;
  }
  switch ($op) {
    case 'handler':
      $fieldbits = explode('.', $filter['field']);
      $query->ensure_table($fieldbits[0]);
      switch ($filter['operator']) {
        case 'contains':
          $query->add_where("UPPER(%s) LIKE UPPER('%%%s%%')", 
            $filter['field'], $filter['value']);
          break;
        case 'starts':
          $query->add_where("UPPER(%s) LIKE UPPER('%s%%')", 
            $filter['field'], $filter['value']);
          break;
        case 'ends':
          $query->add_where("UPPER(%s) LIKE UPPER('%%%s')", 
            $filter['field'], $filter['value']);
          break;
        case 'not':
          $query->add_where("UPPER(%s) NOT LIKE UPPER('%%%s%%')", 
            $filter['field'], $filter['value']);
          break;
        case '=':
          $query->add_where("UPPER(%s) = '%%%s%%'", 
            $filter['field'], $filter['value']);
          break;
      }
    break;
  }
}

/**
 * Format a field as file size.
 */
function views_handler_field_filesize($fieldinfo, $fielddata, $value, $data) {
  return format_size($value);
}

/**
 * Handle a timestamp filter.
 */
function views_handler_filter_timestamp($op, $filter, $filterinfo, &$query) {
  $value = $filter['value'] == 'now' ? "***CURRENT_TIME***" : strtotime($filter['value']);

  $field = $filter['field'];
  if ($filterinfo['from_unixtime']) {
    $field = "from_UNIXTIME($field)";
  }

  $query->add_where("%s %s %s + %d", $field, $filter['operator'], $value, $filter['options']);
}

/**
 * Provide a form gadget for dates.
 */
function views_handler_filter_date_value_form() {
  return array(
    '#type' => 'textfield',
    '#attributes' => array('class' => 'jscalendar'),
  );
}
/**
 * Substitute current time; this works with cached queries.
 */
function views_views_query_substitutions($view) {
  global $user;
  return array('***CURRENT_TIME***' => time());
}