summaryrefslogtreecommitdiffstats
path: root/views.module
blob: 338354bfdf4f758a4fe0a1b7fb71952037259105 (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
<?php
/**
 * @file
 * Primarily Drupal hooks and global API functions to manipulate views.
 *
 * This is the main module file for Views. The main entry points into
 * this module are views_page() and views_block(), where it handles
 * incoming page and block requests.
 */

/**
 * Advertise the current views api version
 */
function views_api_version() {
  return '3.0';
}

/**
 * Implements hook_forms().
 *
 * To provide distinct form IDs for Views forms, the View name and
 * specific display name are appended to the base ID,
 * views_form_views_form. When such a form is built or submitted, this
 * function will return the proper callback function to use for the given form.
 */
function views_forms($form_id, $args) {
  if (strpos($form_id, 'views_form_') === 0) {
    return array(
      $form_id => array(
        'callback' => 'views_form',
      ),
    );
  }
}

/**
 * Returns a form ID for a Views form using the name and display of the View.
 */
function views_form_id($view) {
  $parts = array(
    'views_form',
    $view->name,
    $view->current_display,
  );

  return implode('_', $parts);
}

/**
 * Views will not load plugins advertising a version older than this.
 */
function views_api_minimum_version() {
  return '2';
}

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

/**
 * Implementation of hook_theme(). Register views theming functions.
 */
function views_theme($existing, $type, $theme, $path) {
  $path = drupal_get_path('module', 'views');
  require_once "./$path/theme/theme.inc";

  // Some quasi clever array merging here.
  $base = array(
    'file' => 'theme.inc',
    'path' => "$path/theme",
  );

  // Our extra version of pager from pager.inc
  $hooks['views_mini_pager'] = $base + array(
    'arguments' => array('tags' => array(), 'limit' => 10, 'element' => 0, 'parameters' => array()),
    'pattern' => 'views_mini_pager__',
  );

  $arguments = array(
    'display' => array('view' => NULL),
    'style' => array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL),
    'row' => array('view' => NULL, 'options' => NULL, 'row' => NULL, 'field_alias' => NULL),
    'exposed_form' => array('view' => NULL, 'options' => NULL),
    'pager' => array(
      'view' => NULL, 'options' => NULL,
      'tags' => array(), 'quantity' => 10, 'element' => 0, 'parameters' => array()
    ),
  );

  // Default view themes
  $hooks['views_view_field'] = $base + array(
    'pattern' => 'views_view_field__',
    'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
  );

  $plugins = views_fetch_plugin_data();

  // Register theme functions for all style plugins
  foreach ($plugins as $type => $info) {
    foreach ($info as $plugin => $def) {
      if (isset($def['theme'])) {
        $hooks[$def['theme']] = array(
          'pattern' => $def['theme'] . '__',
          'file' => $def['theme file'],
          'path' => $def['theme path'],
          'arguments' => $arguments[$type],
        );

        $include = './' . $def['theme path'] . '/' . $def['theme file'];
        if (file_exists($include)) {
          require_once $include;
        }

        if (!function_exists('theme_' . $def['theme'])) {
          $hooks[$def['theme']]['template'] = views_css_safe($def['theme']);
        }
      }
      if (isset($def['additional themes'])) {
        foreach ($def['additional themes'] as $theme => $theme_type) {
          if (empty($theme_type)) {
            $theme = $theme_type;
            $theme_type = $type;
          }

          $hooks[$theme] = array(
            'pattern' => $theme . '__',
            'file' => $def['theme file'],
            'path' => $def['theme path'],
            'arguments' => $arguments[$theme_type],
          );

          if (!function_exists('theme_' . $theme)) {
            $hooks[$theme]['template'] = views_css_safe($theme);
          }
        }
      }
    }
  }

  $hooks['views_form_views_form'] = $base;

  $hooks['views_exposed_form'] = $base + array(
    'template' => 'views-exposed-form',
    'pattern' => 'views_exposed_form__',
    'arguments' => array('form' => NULL),
  );

  $hooks['views_more'] = $base + array(
    'template' => 'views-more',
    'pattern' => 'views_more__',
    'arguments' => array('more_url' => NULL, 'link_text' => 'more'),
  );

  // Add theme suggestions which are part of modules.
  foreach (views_get_module_apis() as $info) {
    if (isset($info['template path'])) {
      $hooks += _views_find_module_templates($hooks, $info['template path']);
    }
  }
  return $hooks;
}

/**
 * Scans a directory of a module for template files.
 *
 * @param $cache
 *   The existing cache of theme hooks to test against.
 * @param $path
 *   The path to search.
 *
 * @see drupal_find_theme_templates
 */
function _views_find_module_templates($cache, $path) {
  $templates = array();
  $regex = '\.tpl\.php' . '$';

  // Because drupal_system_listing works the way it does, we check for real
  // templates separately from checking for patterns.
  $files = drupal_system_listing($regex, $path, 'name', 0);
  foreach ($files as $template => $file) {
    // Chop off the remaining extensions if there are any. $template already
    // has the rightmost extension removed, but there might still be more,
    // such as with .tpl.php, which still has .tpl in $template at this point.
    if (($pos = strpos($template, '.')) !== FALSE) {
      $template = substr($template, 0, $pos);
    }
    // Transform - in filenames to _ to match function naming scheme
    // for the purposes of searching.
    $hook = strtr($template, '-', '_');
    if (isset($cache[$hook])) {
      $templates[$hook] = array(
        'template' => $template,
        'path' => dirname($file->filename),
        'include files' => $cache[$hook]['include files'],
      );
    }
    // Ensure that the pattern is maintained from base themes to its sub-themes.
    // Each sub-theme will have their templates scanned so the pattern must be
    // held for subsequent runs.
    if (isset($cache[$hook]['pattern'])) {
      $templates[$hook]['pattern'] = $cache[$hook]['pattern'];
    }
  }

  $patterns = array_keys($files);

  foreach ($cache as $hook => $info) {
    if (!empty($info['pattern'])) {
      // Transform _ in pattern to - to match file naming scheme
      // for the purposes of searching.
      $pattern = strtr($info['pattern'], '_', '-');

      $matches = preg_grep('/^'. $pattern .'/', $patterns);
      if ($matches) {
        foreach ($matches as $match) {
          $file = substr($match, 0, strpos($match, '.'));
          // Put the underscores back in for the hook name and register this pattern.
          $templates[strtr($file, '-', '_')] = array(
            'template' => $file,
            'path' => dirname($files[$match]->filename),
            'arguments' => $info['arguments'],
            'original hook' => $hook,
            'include files' => $info['include files'],
          );
        }
      }
    }
  }

  return $templates;
}

/**
 * A theme preprocess function to automatically allow view-based node
 * templates if called from a view.
 *
 * The 'modules/node.views.inc' file is a better place for this, but
 * we haven't got a chance to load that file before Drupal builds the
 * node portion of the theme registry.
 */
function views_preprocess_node(&$vars) {
  // The 'view' attribute of the node is added in template_preprocess_views_view_row_node()
  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
    $vars['view'] = &$vars['node']->view;
    $vars['template_files'][] = 'node-view-' . $vars['node']->view->name;
    if(!empty($vars['node']->view->current_display)) {
      $vars['template_files'][] = 'node-view-' . $vars['node']->view->name . '-' . $vars['node']->view->current_display;
    }
  }
}

/**
 * A theme preprocess function to automatically allow view-based node
 * templates if called from a view.
 */
function views_preprocess_comment(&$vars) {
  // The 'view' attribute of the node is added in template_preprocess_views_view_row_comment()
  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
    $vars['view'] = &$vars['node']->view;
    $vars['template_files'][] = 'comment-view-' . $vars['node']->view->name;
    if(!empty($vars['node']->view->current_display)) {
      $vars['template_files'][] = 'comment-view-' . $vars['node']->view->name . '-' . $vars['node']->view->current_display;
    }
  }
}

/**
 * A theme preprocess function to automatically allow blocks with view-based
 * block templates if called from a view.
 */
function views_preprocess_block($vars) {
  if (!empty($vars['block']->view)) {
    $vars['view'] = &$vars['block']->view;
    $vars['template_files'][] = 'block-view-' . $vars['view']->name;
    if(!empty($vars['view']->current_display)) {
      $vars['template_files'][] = 'block-view-' . $vars['view']->name . '-' . $vars['view']->current_display;
    }
  }
}

/*
 * Implementation of hook_perm()
 */
function views_perm() {
  return array('access all views', 'administer views');
}

/**
 * Implementation of hook_menu().
 */
function views_menu() {
  // Any event which causes a menu_rebuild could potentially mean that the
  // Views data is updated -- module changes, profile changes, etc.
  views_invalidate_cache();
  $items = array();
  $items['views/ajax'] = array(
    'title' => 'Views',
    'page callback' => 'views_ajax',
    'access callback' => TRUE,
    'description' => 'Ajax callback for view loading.',
    'file' => 'includes/ajax.inc',
    'type' => MENU_CALLBACK,
  );
  // Path is not admin/build/views due to menu complications with the wildcards from
  // the generic ajax callback.
  $items['admin/views/ajax/autocomplete/user'] = array(
    'page callback' => 'views_ajax_autocomplete_user',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'file' => 'includes/ajax.inc',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_menu_alter().
 */
function views_menu_alter(&$callbacks) {
  $our_paths = array();
  $views = views_get_applicable_views('uses hook menu');
  foreach ($views as $data) {
    list($view, $display_id) = $data;
    $result = $view->execute_hook_menu($display_id, $callbacks);
    if (is_array($result)) {
      // The menu system doesn't support having two otherwise
      // identical paths with different placeholders.  So we
      // want to remove the existing items from the menu whose
      // paths would conflict with ours.

      // First, we must find any existing menu items that may
      // conflict.  We use a regular expression because we don't
      // know what placeholders they might use.  Note that we
      // first construct the regex itself by replacing %views_arg
      // in the display path, then we use this constructed regex
      // (which will be something like '#^(foo/%[^/]*/bar)$#') to
      // search through the existing paths.
      $regex = '#^(' . preg_replace('#%views_arg#', '%[^/]*', implode('|', array_keys($result))) . ')$#';
      $matches = preg_grep($regex, array_keys($callbacks));

      // Remove any conflicting items that were found.
      foreach ($matches as $path) {
        // Don't remove the paths we just added!
        if (!isset($our_paths[$path])) {
          unset($callbacks[$path]);
        }
      }
      foreach ($result as $path => $item) {
        if (!isset($callbacks[$path])) {
          // Add a new item, possibly replacing (and thus effectively
          // overriding) one that we removed above.
          $callbacks[$path] = $item;
        }
        else {
          // This item already exists, so it must be one that we added.
          // We change the various callback arguments to pass an array
          // of possible display IDs instead of a single ID.
          $callbacks[$path]['page arguments'][1] = (array)$callbacks[$path]['page arguments'][1];
          $callbacks[$path]['page arguments'][1][] = $display_id;
          $callbacks[$path]['access arguments'][] = $item['access arguments'][0];
          $callbacks[$path]['load arguments'][1] = (array)$callbacks[$path]['load arguments'][1];
          $callbacks[$path]['load arguments'][1][] = $display_id;
        }
        $our_paths[$path] = TRUE;
      }
    }
  }

  // Save memory: Destroy those views.
  foreach ($views as $data) {
    list($view, $display_id) = $data;
    $view->destroy();
  }
}

/**
 * Helper function for menu loading. This will automatically be
 * called in order to 'load' a views argument; primarily it
 * will be used to perform validation.
 *
 * @param $value
 *   The actual value passed.
 * @param $name
 *   The name of the view. This needs to be specified in the 'load function'
 *   of the menu entry.
 * @param $display_id
 *   The display id that will be loaded for this menu item.
 * @param $index
 *   The menu argument index. This counts from 1.
 */
function views_arg_load($value, $name, $display_id, $index) {
  static $views = array();

  // Make sure we haven't already loaded this views argument for a similar menu
  // item elsewhere.
  $key = $name . ':' . $display_id . ':' . $value . ':' . $index;
  if (isset($views[$key])) {
    return $views[$key];
  }

  if ($view = views_get_view($name)) {
    $view->set_display($display_id);
    $view->init_handlers();

    $ids = array_keys($view->argument);

    $indexes = array();
    $path = explode('/', $view->get_path());

    foreach ($path as $id => $piece) {
      if ($piece == '%' && !empty($ids)) {
        $indexes[$id] = array_shift($ids);
      }
    }

    if (isset($indexes[$index])) {
      if (isset($view->argument[$indexes[$index]])) {
        $arg = $view->argument[$indexes[$index]]->validate_argument($value) ? $value : FALSE;
        $view->destroy();

        // Store the output in case we load this same menu item again.
        $views[$key] = $arg;
        return $arg;
      }
    }
    $view->destroy();
  }
}

/**
 * Page callback entry point; requires a view and a display id, then
 * passes control to the display handler.
 */
function views_page() {
  $args = func_get_args();
  $name = array_shift($args);
  $display_id = array_shift($args);

  // Load the view
  if ($view = views_get_view($name)) {
    return $view->execute_display($display_id, $args);
  }

  // Fallback; if we get here no view was found or handler was not valid.
  return drupal_not_found();
}

/**
 * Implementation of hook_block
 */
function views_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      // Try to avoid instantiating all the views just to get the blocks info.
      views_include('cache');
      $cache = views_cache_get('views_block_items', TRUE);
      if ($cache && is_array($cache->data)) {
        return $cache->data;
      }

      $items = array();
      $views = views_get_all_views();
      foreach ($views as $view) {
        // disabled views get nothing.
        if (!empty($view->disabled)) {
          continue;
        }

        $view->init_display();
        foreach ($view->display as $display_id => $display) {

          if (isset($display->handler) && !empty($display->handler->definition['uses hook block'])) {
            $result = $display->handler->execute_hook_block();
            if (is_array($result)) {
              $items = array_merge($items, $result);
            }
          }

          if (isset($display->handler) && $display->handler->get_option('exposed_block')) {
            $result = $display->handler->get_special_blocks();
            if (is_array($result)) {
              $items = array_merge($items, $result);
            }
          }
        }
      }

      // block.module has a delta length limit of 32, but our deltas can
      // unfortunately be longer because view names can be 32 and display IDs
      // can also be 32. So for very long deltas, change to md5 hashes.
      $hashes = array();

      // get the keys because we're modifying the array and we don't want to
      // confuse PHP too much.
      $keys = array_keys($items);
      foreach ($keys as $delta) {
        if (strlen($delta) >= 32) {
          $hash = md5($delta);
          $hashes[$hash] = $delta;
          $items[$hash] = $items[$delta];
          unset($items[$delta]);
        }
      }

      // Only save hashes if they have changed.
      $old_hashes = variable_get('views_block_hashes', array());
      if ($hashes != $old_hashes) {
        variable_set('views_block_hashes', $hashes);
      }
      // Save memory: Destroy those views.
      foreach ($views as $view) {
        $view->destroy();
      }

      views_cache_set('views_block_items', $items, TRUE);

      return $items;
    case 'view':
      // if this is 32, this should be an md5 hash.
      if (strlen($delta) == 32) {
        $hashes = variable_get('views_block_hashes', array());
        if (!empty($hashes[$delta])) {
          $delta = $hashes[$delta];
        }
      }

      // This indicates it's a special one.
      if (substr($delta, 0, 1) == '-') {
        list($nothing, $type, $name, $display_id) = explode('-', $delta);
        // Put the - back on.
        $type = '-' . $type;
        if ($view = views_get_view($name)) {
          if ($view->access($display_id)) {
            $view->set_display($display_id);
            if (isset($view->display_handler)) {
              $output = $view->display_handler->view_special_blocks($type);
              $view->destroy();
              return $output;
            }
          }
          $view->destroy();
        }
      }

      list($name, $display_id) = explode('-', $delta);
      // Load the view
      if ($view = views_get_view($name)) {
        if ($view->access($display_id)) {
          $output = $view->execute_display($display_id);
          $view->destroy();
          return $output;
        }
        $view->destroy();
      }
      break;
  }
}

/**
 * Implementation of hook_flush_caches().
 */
function views_flush_caches() {
  return array('cache_views', 'cache_views_data');
}

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

/**
 * Access callback to determine if the user can import Views.
 *
 * View imports require an additional access check because they are PHP
 * code and PHP is more locked down than administer views.
 */
function views_import_access() {
  return user_access('administer views') && user_access('use PHP for block visibility');
}

/**
 * Determine if the logged in user has access to a view.
 *
 * This function should only be called from a menu hook or some other
 * embedded source. Each argument is the result of a call to
 * views_plugin_access::get_access_callback() which is then used
 * to determine if that display is accessible. If *any* argument
 * is accessible, then the view is accessible.
 */
function views_access() {
  $args = func_get_args();
  foreach ($args as $arg) {
    if ($arg === TRUE) {
      return TRUE;
    }

    if (!is_array($arg)) {
      continue;
    }

    list($callback, $arguments) = $arg;
    $arguments = $arguments ? $arguments : array();
    // Bring dynamic arguments to the access callback.
    foreach ($arguments as $key => $value) {
      if (is_int($value) && isset($args[$value])) {
        $arguments[$key] = $args[$value];
      }
    }
    if (function_exists($callback) && call_user_func_array($callback, $arguments)) {
      return TRUE;
    }
  }

  return FALSE;
}

/**
 * Access callback for the views_plugin_access_perm access plugin.
 *
 * Determine if the specified user has access to a view on the basis of
 * permissions. If the $account argument is omitted, the current user
 * is used.
 */
function views_check_perm($perm, $account = NULL) {
  return user_access($perm, $account) || user_access('access all views', $account);
}

/**
 * Access callback for the views_plugin_access_role access plugin.

 * Determine if the specified user has access to a view on the basis of any of
 * the requested roles. If the $account argument is omitted, the current user
 * is used.
 */
function views_check_roles($rids, $account = NULL) {
  global $user;
  $account = isset($account) ? $account : $user;
  $roles = array_keys($account->roles);
  $roles[] = $account->uid ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
  return user_access('access all views', $account) || array_intersect(array_filter($rids), $roles);
}
// ------------------------------------------------------------------
// Functions to help identify views that are running or ran

/**
 * Set the current 'page view' that is being displayed so that it is easy
 * for other modules or the theme to identify.
 */
function &views_set_page_view($view = NULL) {
  static $cache = NULL;
  if (isset($view)) {
    $cache = $view;
  }

  return $cache;
}

/**
 * Find out what, if any, page view is currently in use. Please note that
 * this returns a reference, so be careful! You can unintentionally modify the
 * $view object.
 */
function &views_get_page_view() {
  return views_set_page_view();
}

/**
 * Set the current 'current view' that is being built/rendered so that it is
 * easy for other modules or items in drupal_eval to identify
 */
function &views_set_current_view($view = NULL) {
  static $cache = NULL;
  if (isset($view)) {
    $cache = $view;
  }

  return $cache;
}

/**
 * Find out what, if any, current view is currently in use. Please note that
 * this returns a reference, so be careful! You can unintentionally modify the
 * $view object.
 */
function &views_get_current_view() {
  return views_set_current_view();
}

// ------------------------------------------------------------------
// Include file helpers

/**
 * Include views .inc files as necessary.
 */
function views_include($file) {
  static $used = array();
  if (!isset($used[$file])) {
    require_once './' . drupal_get_path('module', 'views') . "/includes/$file.inc";
  }

  $used[$file] = TRUE;
}

/**
 * Load views files on behalf of modules.
 */
function views_module_include($file, $reset = FALSE) {
  foreach (views_get_module_apis($reset) as $module => $info) {
    if (file_exists("./$info[path]/$module.$file")) {
      require_once "./$info[path]/$module.$file";
    }
  }
}

/**
 * Get a list of modules that support the current views API.
 */
function views_get_module_apis($reset = FALSE) {
  static $cache = NULL;
  if (!isset($cache) || $reset) {
    $cache = array();
    foreach (module_implements('views_api') as $module) {
      $function = $module . '_views_api';
      $info = $function();
      if (version_compare($info['api'], views_api_minimum_version(), '>=') &&
          version_compare($info['api'], views_api_version(), '<=')) {
        if (!isset($info['path'])) {
          $info['path'] = drupal_get_path('module', $module);
        }
        $cache[$module] = $info;
      }
    }
  }

  return $cache;
}

/**
 * Include views .css files.
 */
function views_add_css($file) {
  // We set preprocess to FALSE because we are adding the files conditionally,
  // and we don't want to generate duplicate cache files.
  // TODO: at some point investigate adding some files unconditionally and
  // allowing preprocess.
  drupal_add_css(drupal_get_path('module', 'views') . "/css/$file.css", 'module', 'all', FALSE);
}

/**
 * Include views .js files.
 */
function views_add_js($file) {
  // If javascript has been disabled by the user, never add js files.
  if (variable_get('views_no_javascript', FALSE)) {
    return;
  }

  static $base = TRUE;
  if ($base) {
    drupal_add_js(drupal_get_path('module', 'views') . "/js/base.js");
    $base = FALSE;
  }
  drupal_add_js(drupal_get_path('module', 'views') . "/js/$file.js");
}

/**
 * Load views files on behalf of modules.
 */
function views_include_handlers($reset = FALSE) {
  static $finished = FALSE;
  // Ensure this only gets run once.
  if ($finished && !$reset) {
    return;
  }

  views_include('base');
  views_include('handlers');
  views_include('cache');
  views_include('plugins');
  _views_include_handlers($reset);
  $finished = TRUE;
}

/**
 * Load default views files on behalf of modules.
 */
function views_include_default_views($reset = FALSE) {
  static $finished = FALSE;
  // Ensure this only gets run once.
  if ($finished && !$reset) {
    return;
  }

  // Default views hooks may be in the normal handler file,
  // or in a separate views_default file at the discretion of
  // the module author.
  views_include_handlers($reset);

  _views_include_default_views($reset);
  $finished = TRUE;
}

// -----------------------------------------------------------------------
// Views handler functions

/**
 * Fetch a handler from the data cache.
 *
 * @param $table
 *   The name of the table this handler is from.
 * @param $field
 *   The name of the field this handler is from.
 * @param $key
 *   The type of handler. i.e, sort, field, argument, filter, relationship
 * @param $override
 *   Override the actual handler object with this class. Used for
 *   aggregation when the handler is redirected to the aggregation
 *   handler.
 *
 * @return views_handler
 *   An instance of a handler object. May be views_handler_broken.
 */
function views_get_handler($table, $field, $key, $override = NULL) {
  $data = views_fetch_data($table);
  $handler = NULL;

  if (isset($data[$field][$key])) {
    // Set up a default handler:
    if (empty($data[$field][$key]['handler'])) {
      $data[$field][$key]['handler'] = 'views_handler_' . $key;
    }

    if ($override) {
      $data[$field][$key]['override handler'] = $override;
    }

    $handler = _views_prepare_handler($data[$field][$key], $data, $field, $key);
  }

  if ($handler) {
    return $handler;
  }

  vpr("Missing handler: $table $field $key");
  $broken = array(
    'title' => t('Broken handler @table.@field', array('@table' => $table, '@field' => $field)),
    'handler' => 'views_handler_' . $key . '_broken',
    'table' => $table,
    'field' => $field,
  );
  return _views_create_handler($broken, 'handler', $key);
}

/**
 * Fetch Views' data from the cache
 */
function views_fetch_data($table = NULL, $reset = FALSE) {
  views_include('cache');
  return _views_fetch_data($table, $reset);
}

// -----------------------------------------------------------------------
// Views plugin functions

/**
 * Fetch the plugin data from cache.
 */
function views_fetch_plugin_data($type = NULL, $plugin = NULL, $reset = FALSE) {
  views_include('cache');
  return _views_fetch_plugin_data($type, $plugin, $reset);
}

/**
 * Get a handler for a plugin
 *
 * @return views_plugin
 *
 * The created plugin object.
 */
function views_get_plugin($type, $plugin, $reset = FALSE) {
  $definition = views_fetch_plugin_data($type, $plugin, $reset);
  if (!empty($definition)) {
    return _views_create_handler($definition, $type);
  }
}

/**
 * Load the current enabled localization plugin.
 *
 * @return The name of the localization plugin.
 */
function views_get_localization_plugin() {
  $plugin = variable_get('views_localization_plugin', '');
  // Provide sane default values for the localization plugin.
  if (empty($plugin)) {
    if (module_exists('locale')) {
      $plugin = 'core';
    }
    else {
      $plugin = 'none';
    }
  }

  return $plugin;
}

// -----------------------------------------------------------------------
// Views database functions

/**
 * Get a view from the default views defined by modules.
 *
 * Default views are cached per-language.  This function will rescan the
 * default_views hook if necessary.
 *
 * @param $view_name
 *   The name of the view to load.
 * @return
 *   A view object or NULL if it is not available.
 */
function &views_get_default_view($view_name, $reset = FALSE) {
  $null = NULL;

  // Attempt to load individually cached view from cache.
  views_include('cache');
  if (!$reset) {
    $data = views_cache_get("views_default:{$view_name}", TRUE);
    if (isset($data->data) && is_object($data->data)) {
      return $data->data;
    }
  }

  // Otherwise, allow entire cache to be rebuilt.
  $cache = views_discover_default_views($reset);
  if (isset($cache[$view_name])) {
    return $cache[$view_name];
  }
  return $null;
}

/**
 * Create an empty view to work with.
 *
 * @return view
 *   A fully formed, empty $view object. This object must be populated before
 *   it can be successfully saved.
 */
function views_new_view() {
  views_include('view');
  $view = new view();
  $view->vid = 'new';
  $view->add_display('default');

  return $view;
}

/**
 * Scan all modules for default views and rebuild the default views cache.
 *
 * @return An associative array of all known default views.
 */
function views_discover_default_views($reset = FALSE) {
  static $cache = array();

  if (empty($cache) || $reset) {
    views_include('cache');
    $cache = _views_discover_default_views($reset);
  }
  return $cache;
}

/**
 * Return a list of all views and display IDs that have a particular
 * setting in their display's plugin settings.
 *
 * @return
 * @code
 * array(
 *   array($view, $display_id),
 *   array($view, $display_id),
 * );
 * @endcode
 */
function views_get_applicable_views($type) {
  // @todo: Use a smarter flagging system so that we don't have to
  // load every view for this.
  $result = array();
  $views = views_get_all_views();

  foreach ($views as $view) {
    // Skip disabled views.
    if (!empty($view->disabled)) {
      continue;
    }

    if (empty($view->display)) {
      // Skip this view as it is broken.
      vsm(t("Skipping broken view @view", array('@view' => $view->name)));
      continue;
    }

    // Loop on array keys because something seems to muck with $view->display
    // a bit in PHP4.
    foreach (array_keys($view->display) as $id) {
      $plugin = views_fetch_plugin_data('display', $view->display[$id]->display_plugin);
      if (!empty($plugin[$type])) {
        // This view uses hook menu. Clone it so that different handlers
        // don't trip over each other, and add it to the list.
        $v = $view->clone_view();
        if ($v->set_display($id) && $v->display_handler->get_option('enabled')) {
          $result[] = array($v, $id);
        }
        // In PHP 4.4.7 and presumably earlier, if we do not unset $v
        // here, we will find that it actually overwrites references
        // possibly due to shallow copying issues.
        unset($v);
      }
    }
  }
  return $result;
}

/**
 * Return an array of all views as fully loaded $view objects.
 *
 * @param $reset
 *   If TRUE, reset the static cache forcing views to be reloaded.
 */
function views_get_all_views($reset = FALSE) {
  static $views = array();

  if (empty($views) || $reset) {
    $views = array();

    // First, get all applicable views.
    views_include('view');
    $views = view::load_views();

    // Get all default views.
    $status = variable_get('views_defaults', array());

    foreach (views_discover_default_views($reset) as $view) {
      // Determine if default view is enabled or disabled.
      if (isset($status[$view->name])) {
        $view->disabled = $status[$view->name];
      }

      // If overridden, also say so.
      if (!empty($views[$view->name])) {
        $views[$view->name]->type = t('Overridden');
      }
      else {
        $view->type = t('Default');
        $views[$view->name] = $view;
      }
    }

  }
  return $views;
}

/**
 * Get a view from the database or from default views.
 *
 * This function is just a static wrapper around views::load(). This function
 * isn't called 'views_load()' primarily because it might get a view
 * from the default views which aren't technically loaded from the database.
 *
 * @param $name
 *   The name of the view.
 * @param $reset
 *   If TRUE, reset this entry in the load cache.
 * @return view
 *   A reference to the $view object. Use $reset if you're sure you want
 *   a fresh one.
 */
function views_get_view($name, $reset = FALSE) {
  views_include('view');
  $view = view::load($name, $reset);
  $default_view = views_get_default_view($name, $reset);

   // The view does not exist.
  if (empty($view) && empty($default_view)) {
    return;
  }
  // The view is defined in code.
  elseif (empty($view) && !empty($default_view)) {
    $status = variable_get('views_defaults', array());
    if (isset($status[$default_view->name])) {
      $default_view->disabled = $status[$default_view->name];
    }
    $default_view->type = t('Default');
    return $default_view->clone_view();
  }
  // The view is overriden/defined in the database.
  elseif (!empty($view) && !empty($default_view)) {
    $view->type = t('Overridden');
  }

  return $view->clone_view();
}

// ------------------------------------------------------------------
// Views debug helper functions

/**
 * Provide debug output for Views. This relies on devel.module
 */
function views_debug($message) {
  if (module_exists('devel') && variable_get('views_devel_output', FALSE) && user_access('access devel information')) {
    if (is_string($message)) {
      $output = $message;
    }
    else {
      $output = var_export($message, TRUE);
    }
    if (variable_get('views_devel_region', 'footer') != 'watchdog') {
      drupal_set_content(variable_get('views_devel_region', 'footer'), '<pre>' . $output . '</pre>');
    }
    else {
      watchdog('views_logging', '<pre>' . $output . '</pre>');
    }
  }
}

/**
 * Shortcut to views_debug()
 */
function vpr($message) {
  views_debug($message);
}

/**
 * Debug messages
 */
function vsm($message) {
  if (module_exists('devel')) {
    dsm($message);
  }
}

function views_trace() {
  $message = '';
  foreach (debug_backtrace() as $item) {
    if (!empty($item['file']) && !in_array($item['function'], array('vsm_trace', 'vpr_trace', 'views_trace'))) {
      $message .= basename($item['file']) . ": " . (empty($item['class']) ? '' : ($item['class'] . '->')) . "$item[function] line $item[line]" . "\n";
    }
  }
  return $message;
}

function vsm_trace() {
  vsm(views_trace());
}

function vpr_trace() {
  dpr(views_trace());
}

// ------------------------------------------------------------------
// Views form (View with form elements)

/**
 * Returns TRUE if the passed-in view contains handlers with views form
 * implementations, FALSE otherwise.
 */
function views_view_has_form_elements($view) {
  foreach ($view->field as $field) {
    if (property_exists($field, 'views_form_callback') || method_exists($field, 'views_form')) {
      return TRUE;
    }
  }
  $area_handlers = array_merge(array_values($view->header), array_values($view->footer));
  $empty = empty($view->result);
  foreach ($area_handlers as $area) {
    if (method_exists($area, 'views_form') && !$area->views_form_empty($empty)) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * This is the entry function. Just gets the form for the current step.
 * The form is always assumed to be multistep, even if it has only one
 * step (the default 'views_form_views_form' step). That way it is actually
 * possible for modules to have a multistep form if they need to.
 */
function views_form(&$form_state, $view, $output) {
  $form_state['storage']['step'] = isset($form_state['storage']['step']) ? $form_state['storage']['step'] : 'views_form_views_form';

  $form = array();
  $form['#validate'] = array('views_form_validate');
  $form['#submit'] = array('views_form_submit');
  // Tell the preprocessor whether it should hide the header, footer, pager...
  $view->show_view_elements = ($form_state['storage']['step'] == 'views_form_views_form') ? TRUE : FALSE;

  $form = $form_state['storage']['step']($form, $form_state, $view, $output);
  return $form;
}

/**
 * The basic form validate handler.
 * Fires the hook_views_form_validate() function.
 */
function views_form_validate($form, &$form_state) {
  // Fire the hook. Doesn't use module_invoke_all() because $form_state needs
  // to be passed by reference.
  foreach (module_implements('views_form_validate') as $module) {
    $function = $module . '_views_form_validate';
    $function($form, $form_state);
  }
}

/**
 * The basic form submit handler.
 * Fires the hook_views_form_submit() function.
 */
function views_form_submit($form, &$form_state) {
  // Fire the hook. Doesn't use module_invoke_all() because $form_state needs
  // to be passed by reference.
  foreach (module_implements('views_form_submit') as $module) {
    $function = $module . '_views_form_submit';
    $function($form, $form_state);
  }
}

/**
 * Callback for the main step of a Views form.
 * Invoked by views_form().
 */
function views_form_views_form($form, &$form_state, $view, $output) {
  $form['#prefix'] = '<div class="views-form">';
  $form['#suffix'] = '</div>';
  $form['#theme'] = 'views_form_views_form';
  $form['#validate'][] = 'views_form_views_form_validate';
  $form['#submit'][] = 'views_form_views_form_submit';

  // Add the output markup to the form array so that it's included when the form
  // array is passed to the theme function.
  $form['output'] = array(
    '#value' => $output,
    // This way any additional form elements will go before the view
    // (below the exposed widgets).
    '#weight' => 50,
  );

  $substitutions = array();
  foreach ($view->field as $field_name => $field) {
    $has_form = FALSE;
    // If the field provides a views form, allow it to modify the $form array.
    if (property_exists($field, 'views_form_callback')) {
      $callback = $field->views_form_callback;
      $callback($view, $field, $form, $form_state);
      $has_form = TRUE;
    }
    elseif (method_exists($field, 'views_form')) {
      $field->views_form($form, $form_state);
      $has_form = TRUE;
    }

    // Build the substitutions array for use in the theme function.
    if ($has_form) {
      foreach ($view->result as $row_id => $row) {
        $substitutions[] = array(
         'placeholder' => '<!--form-item-' . $field_name . '--' . $row_id . '-->',
          'field_name' => $field_name,
          'row_id' => $row_id,
        );
      }
    }
  }

  // Give the area handlers a chance to extend the form.
  $area_handlers = array_merge(array_values($view->header), array_values($view->footer));
  $empty = empty($view->result);
  foreach ($area_handlers as $area) {
    if (method_exists($area, 'views_form') && !$area->views_form_empty($empty)) {
      $area->views_form($form, $form_state);
    }
  }

  $form['#substitutions'] = array(
    '#type' => 'value',
    '#value' => $substitutions,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#weight' => 100,
  );

  return $form;
}

/**
 * Validate handler for the first step of the views form.
 * Calls any existing views_form_validate functions located
 * on the views fields.
 */
function views_form_views_form_validate($form, &$form_state) {
  $view = $form['#parameters'][2];

  // Call the validation method on every field handler that has it.
  foreach ($view->field as $field_name => $field) {
    if (method_exists($field, 'views_form_validate')) {
      $field->views_form_validate($form, $form_state);
    }
  }

  // Call the validate method on every area handler that has it.
  foreach (array('header', 'footer') as $area) {
    foreach ($view->{$area} as $area_name => $area_handler) {
      if (method_exists($area_handler, 'views_form_validate')) {
        $area_handler->views_form_validate($form, $form_state);
      }
    }
  }
}

/**
 * Submit handler for the first step of the views form.
 * Calls any existing views_form_submit functions located
 * on the views fields.
 */
function views_form_views_form_submit($form, &$form_state) {
  $view = $form['#parameters'][2];

  // Call the submit method on every field handler that has it.
  foreach ($view->field as $field_name => $field) {
    if (method_exists($field, 'views_form_submit')) {
      $field->views_form_submit($form, $form_state);
    }
  }

  // Call the submit method on every area handler that has it.
  foreach (array('header', 'footer') as $area) {
    foreach ($view->{$area} as $area_name => $area_handler) {
      if (method_exists($area_handler, 'views_form_submit')) {
        $area_handler->views_form_submit($form, $form_state);
      }
    }
  }
}

// ------------------------------------------------------------------
// Exposed widgets form

/**
 * Form builder for the exposed widgets form.
 *
 * Be sure that $view and $display are references.
 */
function views_exposed_form(&$form_state) {
  // Don't show the form when batch operations are in progress.
  if ($batch = batch_get() && isset($batch['current_set'])) {
    return array(
      // Set the theme callback to be nothing to avoid errors in template_preprocess_views_exposed_form().
      '#theme' => '',
    );
  }

  // Make sure that we validate because this form might be submitted
  // multiple times per page.
  $form_state['must_validate'] = TRUE;
  $view = &$form_state['view'];
  $display = &$form_state['display'];

  $form_state['input'] = $view->get_exposed_input();

  // Let form plugins know this is for exposed widgets.
  $form_state['exposed'] = TRUE;
  // Check if the form was already created
  if ($cache = views_exposed_form_cache($view->name, $view->current_display)) {
    return $cache;
  }

  $form['#info'] = array();

  if (!variable_get('clean_url', FALSE)) {
    $form['q'] = array(
      '#type' => 'hidden',
      '#value' => $view->get_url(),
    );
  }

  // Go through each handler and let it generate its exposed widget.
  foreach ($view->display_handler->handlers as $type => $value) {
    foreach ($view->$type as $id => $handler) {
      if ($handler->can_expose() && $handler->is_exposed()) {
        $handler->exposed_form($form, $form_state);
        if ($info = $handler->exposed_info()) {
          $form['#info']["$type-$id"] = $info;
        }
      }
    }
  }

  $form['submit'] = array(
    '#name' => '', // prevent from showing up in $_GET.
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#id' => form_clean_id('edit-submit-' . $view->name),
  );

  $form['#action'] = url($view->get_url());
  $form['#theme'] = views_theme_functions('views_exposed_form', $view, $display);
  $form['#id'] = views_css_safe('views_exposed_form-' . check_plain($view->name) . '-' . check_plain($display->id));
//  $form['#attributes']['class'] = array('views-exposed-form');

  // If using AJAX, we need the form plugin.
  if ($view->use_ajax) {
    drupal_add_js('misc/jquery.form.js');
  }
  views_add_js('dependent');

  $exposed_form_plugin = $form_state['exposed_form_plugin'];
  $exposed_form_plugin->exposed_form_alter($form, $form_state);

  // Save the form
  views_exposed_form_cache($view->name, $view->current_display, $form);

  return $form;
}

/**
 * Validate handler for exposed filters
 */
function views_exposed_form_validate(&$form, &$form_state) {
  foreach (array('field', 'filter') as $type) {
    $handlers = &$form_state['view']->$type;
    foreach ($handlers as $key => $handler) {
      $handlers[$key]->exposed_validate($form, $form_state);
    }
  }
  $exposed_form_plugin = $form_state['exposed_form_plugin'];
  $exposed_form_plugin->exposed_form_validate($form, $form_state);
}

/**
 * Submit handler for exposed filters
 */
function views_exposed_form_submit(&$form, &$form_state) {
  foreach (array('field', 'filter') as $type) {
    $handlers = &$form_state['view']->$type;
    foreach ($handlers as $key => $info) {
      $handlers[$key]->exposed_submit($form, $form_state);
    }
  }
  $form_state['view']->exposed_data = $form_state['values'];
  $form_state['view']->exposed_raw_input = array();

  $exclude = array('q', 'submit', 'form_build_id', 'form_id', 'form_token', 'exposed_form_plugin', '');
  $exposed_form_plugin = $form_state['exposed_form_plugin'];
  $exposed_form_plugin->exposed_form_submit($form, $form_state, $exclude);

  foreach ($form_state['values'] as $key => $value) {
    if (!in_array($key, $exclude)) {
      $form_state['view']->exposed_raw_input[$key] = $value;
    }
  }
}

/**
 * Save the Views exposed form for later use.
 *
 * @param $views_name
 *   String. The views name.
 * @param $display_name
 *   String. The current view display name.
 * @param $form_output
 *   Array (optional). The form structure. Only needed when inserting the value.
 * @return
 *   Array. The form structure, if any. Otherwise, return FALSE.
 */
function views_exposed_form_cache($views_name, $display_name, $form_output = NULL) {
  static $views_exposed;

  // Save the form output
  if (!empty($form_output)) {
    $views_exposed[$views_name][$display_name] = $form_output;
    return;
  }

  // Return the form output, if any
  return empty($views_exposed[$views_name][$display_name]) ? FALSE : $views_exposed[$views_name][$display_name];
}

// ------------------------------------------------------------------
// Misc helpers

/**
 * Build a list of theme function names for use most everywhere.
 */
function views_theme_functions($hook, $view, $display = NULL) {
  require_once './' . drupal_get_path('module', 'views') . "/theme/theme.inc";
  return _views_theme_functions($hook, $view, $display);
}

/**
 * Views' replacement for drupal_get_form so that we can do more with
 * less.
 *
 * Items that can be set on the form_state include:
 * - input: The source of input. If unset this will be $_POST.
 * - no_redirect: Absolutely do not redirect the form even if instructed
 *   to do so.
 * - rerender: If no_redirect is set and the form was successfully submitted,
 *   rerender the form. Otherwise it will just return.
 *
 */
function drupal_build_form($form_id, &$form_state) {
  views_include('form');
  return _drupal_build_form($form_id, $form_state);
}

/**
 * Substitute current time; this works with cached queries.
 */
function views_views_query_substitutions($view) {
  global $language;
  return array(
    '***CURRENT_VERSION***' => VERSION,
    '***CURRENT_TIME***' => time(),
    '***CURRENT_LANGUAGE***' => $language->language,
    '***DEFAULT_LANGUAGE***' => language_default('language'),
    '***NO_LANGUAGE***' => '',
  );
}

/**
 * Embed a view using a PHP snippet.
 *
 * This function is meant to be called from PHP snippets, should one wish to
 * embed a view in a node or something. It's meant to provide the simplest
 * solution and doesn't really offer a lot of options, but breaking the function
 * apart is pretty easy, and this provides a worthwhile guide to doing so.
 *
 * Note that this function does NOT display the title of the view. If you want
 * to do that, you will need to do what this function does manually, by
 * loading the view, getting the preview and then getting $view->get_title().
 *
 * @param $name
 *   The name of the view to embed.
 * @param $display_id
 *   The display id to embed. If unsure, use 'default', as it will always be
 *   valid. But things like 'page' or 'block' should work here.
 * @param ...
 *   Any additional parameters will be passed as arguments.
 */
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

/**
* Get the result of a view.
*
* @param string $name
*      The name of the view to retrieve the data from.
* @param string $display_id
*      The display id. On the edit page for the view in question, you'll find
*      a list of displays at the left side of the control area. "Defaults"
*      will be at the top of that list. Hover your cursor over the name of the
*      display you want to use. An URL will appear in the status bar of your
*      browser. This is usually at the bottom of the window, in the chrome.
*      Everything after #views-tab- is the display ID, e.g. page_1.
 * @param ...
 *   Any additional parameters will be passed as arguments.
* @return
*      array
*          An array containing an object for each view item.
*/
function views_get_view_result($name, $display_id = NULL) {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (is_object($view)) {
    if (is_array($args)) {
      $view->set_arguments($args);
    }
    if (is_string($display_id)) {
      $view->set_display($display_id);
    }
    else {
      $view->init_display();
    }
    $view->pre_execute();
    $view->execute();
    return $view->result;
  }
  else {
    return array();
  }
}

/**
 * Export a field.
 */
function views_var_export($var, $prefix = '', $init = TRUE) {
  if (is_array($var)) {
    if (empty($var)) {
      $output = 'array()';
    }
    else {
      $output = "array(\n";
      foreach ($var as $key => $value) {
        $output .= "  " . views_var_export($key, '', FALSE) . " => " . views_var_export($value, '  ', FALSE) . ",\n";
      }
      $output .= ')';
    }
  }
  else if (is_bool($var)) {
    $output = $var ? 'TRUE' : 'FALSE';
  }
  else if (is_string($var) && strpos($var, "\n") !== FALSE) {
    // Replace line breaks in strings with a token for replacement
    // at the very end. This protects multi-line strings from
    // unintentional indentation.
    $var = str_replace("\n", "***BREAK***", $var);
    $output = var_export($var, TRUE);
  }
  else {
    $output = var_export($var, TRUE);
  }

  if ($prefix) {
    $output = str_replace("\n", "\n$prefix", $output);
  }

  if ($init) {
    $output = str_replace("***BREAK***", "\n", $output);
  }

  return $output;
}

/**
 * Prepare the specified string for use as a CSS identifier.
 */
function views_css_safe($string) {
  return str_replace('_', '-', $string);
}

/**
 * Implementation of hook_views_exportables().
 */
function views_views_exportables($op = 'list', $views = NULL, $name = 'foo') {
  $all_views = views_get_all_views();
  if ($op == 'list') {

    foreach ($all_views as $name => $view) {
      // in list, $views is a list of tags.
      if (empty($views) || in_array($view->tag, $views)) {
        $return[$name] = array(
          'name' => check_plain($name),
          'desc' => check_plain($view->description),
          'tag' => check_plain($view->tag)
        );
      }
    }
    return $return;
  }

  if ($op == 'export') {
    $code = "/**\n";
    $code .= " * Implementation of hook_views_default_views().\n";
    $code .= " */\n";
    $code .= "function " . $name . "_views_default_views() {\n";
    foreach ($views as $view => $truth) {
      $code .= "  /*\n";
      $code .= "   * View ". var_export($all_views[$view]->name, TRUE) ."\n";
      $code .= "   */\n";
      $code .= $all_views[$view]->export('  ');
      $code .= '  $views[$view->name] = $view;' . "\n\n";
    }
    $code .= "  return \$views;\n";
    $code .= "}\n";

    return $code;
  }
}

/**
 * Microtime helper function to return a float time value (php4 & php5 safe).
 */
function views_microtime() {
  list($usec, $sec) = explode(' ', microtime());
  return (float)$sec + (float)$usec;
}

/**
 * Trim the field down to the specified length.
 *
 * @param $alter
 *   - max_length: Maximum lenght of the string, the rest gets truncated.
 *   - word_boundary: Trim only on a word boundary.
 *   - ellipsis: Trim only on a word boundary.
 *   - html: Take sure that the html is correct.
 */
function views_trim_text($alter, $value) {
  if (drupal_strlen($value) > $alter['max_length']) {
    $value = drupal_substr($value, 0, $alter['max_length']);
    // TODO: replace this with cleanstring of ctools
    if (!empty($alter['word_boundary'])) {
      $regex = "(.*)\b.+";
      if (function_exists('mb_ereg')) {
        mb_regex_encoding('UTF-8');
        $found = mb_ereg($regex, $value, $matches);
      }
      else {
        $found = preg_match("/$regex/us", $value, $matches);
      }
      if ($found) {
        $value = $matches[1];
      }
    }
    // Remove scraps of HTML entities from the end of a strings
    $value = rtrim(preg_replace('/(?:<(?!.+>)|&(?!.+;)).*$/us', '', $value));

    if (!empty($alter['ellipsis'])) {
      $value .= '...';
    }
  }
  if (!empty($alter['html'])) {
    $value = _filter_htmlcorrector($value);
  }

  return $value;
}