aboutsummaryrefslogtreecommitdiff
path: root/video.module
blob: c85ad1e921fb88986bcbc2baefb3e5f5cf2f8db1 (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
<?php
// $Id$

/**
 * @file
 * Display video in Quicktime MOV, Realmedia RM, Flash FLV & SWF,
 * or Windows Media WMV formats.
 *
 * @author Fabio Varesano <fvaresano at yahoo dot it>
 * @author David Norman <deekayen at: deekayen (dot) net>
 * @author Luke Last <luke [at] lukelast dot com>
 */

/********************************************************************
 * General Hooks
 ********************************************************************/

/**
 * Help hook
 *
 * @param $section
 *   string of the area of Drupal where help was requested
 *
 * @return
 *   string of help information
 */
function video_help($section = 'admin/help#video') {
  switch ($section) {
    case 'admin/help#video':
      $output = '<p>' . t('The video module (4.7 or with backport patch to 4.6) allows users to post video content to their site. The emergence of portable phones with video capture capabilities has made video capture ubiquitous. Video logging, or <a href="%elink-en-wikipedia-org">vlogging</a> as a medium for personal video broadcasting has proven to be popular and is following the blogging, and podcasting phenomena\'s. Videos are useful for creative collaboration among community members. If community members can not meet in person videos of meetings are valuable for enhancing the interaction between community members.', array('%elink-en-wikipedia-org' => 'http://en.wikipedia.org/wiki/Vlog')) . '</p>';
      $output .= '<p>' . t('The video module can be administered to flash player settings. There are a number of page and menu links which can be added to play and download video content on the site. Other configurable options include play and download counters. Multi-file downloads can also be configured under settings. There are also up to six custom fields and a group name which can be added.') . '</p>';
      $output .= t('<p>You can:</p>
<ul>
<li>Enable <em>most played videos</em>, <em>latest videos</em>, and <em>top videos</em> blocks at <a href="%admin-block">administer &gt;&gt; block</a>.</li>
<li>Create video posts at <a href="%node-add-video">create content &gt;&gt; video</a>.</li>
<li>Administer video module settings at <a href="%admin-settings-video">administer &gt;&gt; settings &gt;&gt; video</a>.</li>
</ul>
', array('%admin-block' => url('admin/block'), '%node-add-video' => url('node/add/video'), '%admin-settings-video' => url('admin/settings/video')));
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%video">Video page</a>.', array('%video' => 'http://www.drupal.org/handbook/modules/video/')) .'</p>';
      return $output;
    case 'admin/modules#description':
      return t('Allows video nodes.');
    case 'node/add#video':
      return t('Allows you to insert videos as nodes');
    case 'video/help':
      $help = '';
      $help .= '<a name="videofile"></a><h3>' . t('Video File Field') . '</h3>';
      $help .= '<p>' . t('This is the field where you enter the video file information. The Video module currently supports these file types:') . '</p>';
      $help .= '<ul><li><b>' . t('.mov, .wmv, .rm, .flv, .swf, .dir, .dcr') . '</b><ul><li>' . t('To play these file types you need to enter in the path to the file. If your video is on the same webserver as drupal, you can use a path relative to the drupal directory, like "downloads/video.mov". If your video is on another server you can enter the URI to the video like "http://www.example.com/videos/my-video.mov".') . '</li></ul><br /></li>';
      $help .= '<li><b><a href="http://www.youtube.com">' . t('YouTube.com support') . '</a></b><ul><li>' . t('You can host videos on youtube.com and put them on your site. To do this, after you upload the video on youtube.com enter the video ID into the "Video File" field. If the URI youtube.com gives you for the video is "http://www.youtube.com/watch.php?v=XM4QYXPf-s8" you would enter "XM4QYXPf-s8".') . '</li></ul><br /></li>';
      $help .= '<li><b><a href="http://video.google.com">' . t('Google Video support') . '</a></b><ul><li>' . t('You can host videos on video.google.com and put them on your site. 
  To do this, after you upload the video on Google video enter get the
  the embed code. In this code you will find an attribute like
  src="http://video.google.com/googleplayer.swf?docId=-1591729516923874694" .
  You will need the -1591729516923874694 like number just after docId= .
  Then use "google:-1591729516923874694" as video file value.') . '</li></ul></li></ul>';
      $help .= '<a name="multi-download"></a><h3>' . t('Multi-file Dowload Help') . '</h3>';
      $help .= '<p>' . t('If enabled, this group holds all the settings for multi-file downloads. Multi-file downloads allows you to have a list of any number of files on the download page. These files are usually scanned from a folder. This allows the listing of multiple sizes and video types for visitors to choose from, you can even zip the files up.') . '</p>';
      $help .= '<ul><li><b>' . t('Disable multi-file downloads') . '</b><ul><li>' . t('This checkbox will disable multi-file downloads for this video. This means the download tab and link will send visitors straight to download the same video as is set to play. Use this option if you only have one version of your video.') . '</li></ul><br /></li>';
      $help .= '<li><b>' . t('Multi-file download folder') . '</b><ul><li>' . t('Allows you to specify a folder on the local server containing the files you wish to show up on the download tab. This folder should be relative to the drupal root directory, so if the absolute path is "C:\inetpub\drupal\videos\projectfolder\" or "/usr/htdocs/drupal/videos/projectfolder/" then you would enter "videos/projectfolder/".') . '</li></ul><br /></li>';
      $help .= '<li><b>' . t('Show files in "play" folder') . '</b><ul><li>' . t('This option will list all the files in the same folder is the "play" file listed in the "Video File" field above. You can use this option in addition to the download folder to list the videos in both folders.') . '</li></ul></li></ul>';
      return $help;
  }
}

/**
 * Implementation of hook_menu().
 *
 * @param $may_cache
 *   boolean indicating whether cacheable menu items should be returned
 *
 * @return
 *   array of menu information
 */
function video_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'video',
      'title' => t('videos'),
      'callback' => 'video_page',
      'access' => user_access('access video'),
      'type' => MENU_SUGGESTED_ITEM);
    $items[] = array(
      'path' => 'video/feed',
      'title' => t('videos feed'),
      'callback' => 'video_feed',
      'access' => user_access('access video'),
      'type' => MENU_CALLBACK);
    $items[] = array(
      'path' => 'node/add/video',
      'title' => t('video'),
      'access' => user_access('create video'));
  }
  else { //If $may_cache is false.
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      if ($node = node_load(arg(1)) and $node->type == 'video') {
        if (variable_get('video_displayplaymenutab', 1) == 1) {
          $items[] = array('path' => 'node/'. arg(1) .'/play',
            'title' => t('play'),
            'callback' => 'video_play',
            'access' => user_access('access video'),
            'weight' => 3,
            'type' => MENU_LOCAL_TASK);
        }
        //If the video is of type youtube and multi-file downloads aren't turned on don't show the download tab.
        if (variable_get('video_displaydownloadmenutab', 1) == 1 and (_video_get_filetype(($node->vidfile) != 'youtube' and _video_get_filetype($node->vidfile) != 'googlevideo') or $node->disable_multidownload == 0)) {
          $items[] = array('path' => 'node/'.arg(1).'/download',
            'title' => t('download'),
            'callback' => 'video_download',
            'access' => user_access('access video'),
            'weight' => 5,
            'type' => MENU_LOCAL_TASK);
        }
      }
    }
  }
  return $items;
}

/**
 * Internal Drupal links hook
 *
 * @param $type
 *   string type of link to show
 *
 * @param $node
 *   object of node information
 *
 * @return
 *   array of link information
 */
function video_link($type, $node = NULL) {
  $link = '';
  // Node links for a video
  if ($type == 'node' && $node->type == 'video' && $node->vidfile && user_access('access video')) {
    //If the video is of type youtube and multi-file downloads aren't turned on don't show the download link.
    if ((_video_get_filetype($node->vidfile) == 'youtube' or _video_get_filetype($node->vidfile) == 'googlevideo') and $node->disable_multidownload == 1) {
      $display_download_link = 0;
    }
    else {
      $display_download_link = variable_get('video_displaydownloadlink', 1);
    }

    if (variable_get('video_displayplaylink', 1)) {
      $link .= l(t('play'), "node/$node->nid/play", array('class' => 'outgoing', 'title' => t('play %link', array('%link' => $node->title))));
      $link .= ($display_download_link == 1) ? ' ' . t('or') . ' ' : ' | ';
    }
    if ($display_download_link == 1) {
      $link .= l(t('download'), "node/$node->nid/download", array('class' => 'outgoing', 'title' => t('download %link', array('%link' => $node->title))));
      $link .= ' | ';
    }
    if (variable_get('video_displayplaytime', 1)) {
      $link .= format_interval($node->playtime_seconds) . ' | ';
    }
    if (variable_get('video_displayfilesize', 1) and $node->size != 0) {
      $link .= format_size($node->size) . ' | ';
    }
    if (variable_get('video_playcounter', 1) and user_access('view play counter')) {
      $link .= $node->play_counter . ' ' . t('plays') . ' | ';
    }
    if (variable_get('video_downloadcounter', 1) and user_access('view download counter')) {
      $link .= $node->download_counter . ' ' . t('downloads') . ' | ';
    }

    $link = substr($link, 0, -3); //Trim the last " | " off.
  }
  return array($link);
}

/**
 * Displays a Drupal page containing recently added videos
 *
 * @return
 *   string HTML output
 */
function video_page() {
  $output = '';
  if (arg(1) != 'help') { //We are not reading help so output a list of recent video nodes.
    $result = pager_query(db_rewrite_sql("SELECT n.nid, n.created FROM {node} n WHERE n.type = 'video' AND n.status = 1 ORDER BY n.created DESC"), variable_get('default_nodes_main', 10));
    while ($node = db_fetch_object($result)) {
      $output .= node_view(node_load($node->nid), 1);
    }
    $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
    // adds feed icon and link
    drupal_add_link(array('rel' => 'alternate',
      'type' => 'application/rss+xml',
      'title' => variable_get('site_name', 'drupal') . ' ' . t('videos'),
      'href' => url('video/feed/')));

    $output .= '<br />' . theme('feed_icon', url('video/feed'));
  }
  return $output;
}

/**
 * Generate an RSS feed for videos
 *
 * @return
 *   feed
 */
function video_feed() {
  $channel = array(
    'title' => variable_get('site_name', 'drupal') . ' ' . t('videos'),
    'description' => t('Latest videos on') . ' ' . variable_get('site_name', 'drupal'),
    'link' => url('video', NULL, NULL, TRUE)
  );

  $result = db_query('SELECT n.nid FROM {node} n WHERE n.type = "video" AND n.status = 1 ORDER BY n.created DESC');
  node_feed($result, $channel);
}

/**
 * Permissions hook
 *
 * @return
 *   array of permissions
 */
function video_perm() {
  $array = array('create video', 'access video', 'administer video', 'download video', 'view play counter', 'view download counter');
  if (variable_get('video_multidownload', '0')) { //Only display permission if turned on in settings.
    $array[] = 'create multi-file downloads';
  }
  return $array;
}

/**
 * Settings Hook
 *
 * @return
 *   string of form content or error message
 */
function video_settings() {
  //Must have "administer site configuration" and "administer video" privilages.
  if (!user_access('administer video')) {
    drupal_access_denied();
  }
  $options = array(1 => 'Yes', 0 => 'No');

  $form = array();
  $form['tabs'] = array('#type' => 'fieldset', '#title' => t('Tab menu options'));
  $form['tabs']['video_displayplaymenutab'] = array(
    '#type' => 'radios',
    '#title' => t('Display play menu tab'),
    '#options' => $options,
    '#default_value' => variable_get('video_displayplaymenutab', 1),
    '#description' => t('Toggle display of menu link to play video from the node page.'));
  $form['tabs']['video_displaydownloadmenutab'] = array(
    '#type' => 'radios',
    '#title' => t('Display download menu tab'),
    '#options' => $options,
    '#default_value' => variable_get('video_displaydownloadmenutab', 1),
    '#description' => t('Toggle display of menu link to download video from the node page.'));

  $form['flash'] = array('#type' => 'fieldset', '#title' => t('Flash settings'));
  $form['flash']['video_flvplayerloader'] = array(
    '#type' => 'textfield',
    '#title' => t('Filename of Flash loader'),
    '#default_value' => variable_get('video_flvplayerloader', 'Player.swf'),
    '#description' => t('The name of the Shockwave file that manages loading the FLV movie.'));

  $form['menu'] = array('#type' => 'fieldset', '#title' => t('Items to display in the node menu'), '#weight' => -5, '#collapsible' => TRUE, '#collapsed' => TRUE);
  $form['menu']['video_displayplaylink'] = array(
    '#type' => 'radios',
    '#title' => t('Display play link'),
    '#options' => $options,
    '#default_value' => variable_get('video_displayplaylink', 1),
    '#description' => t('Toggle display of "play" link (below the node content in most themes).'));
  $form['menu']['video_displaydownloadlink'] = array(
    '#type' => 'radios',
    '#title' => t('Display download link'),
    '#options' => $options,
    '#default_value' => variable_get('video_displaydownloadlink', 1),
    '#description' => t('Toggle display of "download" link (below the node content in most themes).'));
  $form['menu']['video_displayplaytime'] = array(
    '#type' => 'radios',
    '#title' => t('Display playtime'),
    '#options' => $options,
    '#default_value' => variable_get('video_displayplaytime', 1),
    '#description' => t('Toggle the display of the playtime for a video.'));
  $form['menu']['video_displayfilesize'] = array(
    '#type' => 'radios',
    '#title' => t('Display filesize'),
    '#options' => $options,
    '#default_value' => variable_get('video_displayfilesize', 1),
    '#description' => t('Toggle the display of the filesize for a video.'));

  $form['counters'] = array('#type' => 'fieldset', '#title' => t('Statistics counters'), '#description' => t('To allow users to view counters visit: ') . l(t('access control'), 'admin/access'));
  $form['counters']['video_playcounter'] = array(
    '#type' => 'radios',
    '#title' => t('Count play hits'),
    '#options' => $options,
    '#default_value' => variable_get('video_playcounter', 1),
    '#description' => t('Counts a hit everytime someone views the play page.'));
  $form['counters']['video_downloadcounter'] = array(
    '#type' => 'radios',
    '#title' => t('Count downloads'),
    '#options' => $options,
    '#default_value' => variable_get('video_downloadcounter', 1),
    '#description' => t('Counts a hit everytime someone downloads a video.'));

  $form['multifile'] = array('#type' => 'fieldset', '#title' => t('Multi-file download options'), '#description' => t('Allows a list of files to be shown on the download page. The list is usually gotten from a specified folder. This ability is useful for providing different sizes and video types for download.'));
  $form['multifile']['video_multidownload'] = array(
    '#type' => 'radios',
    '#title' => t('Allow Multi-file Downloads'),
    '#options' => $options,
    '#default_value' => variable_get('video_multidownload', 0),
    '#description' => t('This feature can be disabled separately for each node. If turned on make sure you set the permissions so users can use this feature.') . ' ' . l(t('access control'), 'admin/access'));
  $form['multifile']['video_download_ext'] = array(
    '#type' => 'textfield',
    '#title' => t('File extensions to show'),
    '#default_value' => variable_get('video_download_ext', 'mov,wmv,rm,flv,avi,divx,mpg,mpeg,mp4,zip'),
    '#description' => t('The extensions of files to list from the multi-file download folder on the download page. Extensions should be comma seperated with no spaces, for example (mov,wmv,rm).'));

  $form['video_display_metadata'] = array(
    '#type' => 'radios',
    '#title' => t('Display Optional Metadata'),
    '#options' => $options,
    '#default_value' => variable_get('video_display_metadata', 0),
    '#description' => t('Allows displaying a list of videos metadata: Video bitrate, Audio bitrate, Audio Sampling Rate and Audio Channels.'));

  $form['video_object_parameters'] = array(
    '#type' => 'radios',
    '#title' => t('Allow adding of parameters to object HTML'),
    '#options' => $options,
    '#default_value' => variable_get('video_object_parameters', 0),
    '#description' => t('Turns on a text box that takes parameter=value pairs and puts them into parameter tags in the embedded object tag for each video.'));

  $form['video_image'] = array(
    '#type' => 'radios',
    '#title' => t('Allow adding image to nodes and node teasers'),
    '#options' => $options,
    '#default_value' => variable_get('video_image', 0),
    '#description' => t('This will allow users to put images in the node teaser and node view.'));

  $form['customfields'] = array('#type' => 'fieldset', '#weight' => -1, '#collapsible' => TRUE, '#collapsed' => TRUE, '#title' => t('Custom display fields'), '#description' => t('Creates custom fields. Fields only show up if you give them a name.'));
  $form['customfields']['video_customfieldtitle'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom field group title'),
    '#default_value' => variable_get('video_customfieldtitle', ''),
    '#description' => t('Title of the group of all custom fields.'));
  $form['customfields']['video_customfield1'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom field 1 title'),
    '#default_value' => variable_get('video_customfield1', ''));
  $form['customfields']['video_customfield2'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom field 2 title'),
    '#default_value' => variable_get('video_customfield2', ''));
  $form['customfields']['video_customfield3'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom field 3 title'),
    '#default_value' => variable_get('video_customfield3', ''));
  $form['customfields']['video_customfield4'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom field 4 title'),
    '#default_value' => variable_get('video_customfield4', ''));
  $form['customfields']['video_customfield5'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom field 5 title'),
    '#default_value' => variable_get('video_customfield5', ''));
  $form['customfields']['video_customfield6'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom field 6 title'),
    '#default_value' => variable_get('video_customfield6', ''));
  $form['customfields']['video_customgroupcollapsed'] = array(
    '#type' => 'radios',
    '#title' => t('Start group initially collapsed'),
    '#options' => $options,
    '#default_value' => variable_get('video_customgroupcollapsed', 1),
    '#description' => t('Should the custom fields group be initially collapsed when creating and editing video nodes?'));

  return $form;
}

/******************************************************************************
 * Node Hooks
 ******************************************************************************/

/**
 * Implementation of _node_info().
 *
 * @return
 *   array
 */
function video_node_info() {
  return array('video' => array('name' => t('video'), 'base' => 'video'));
}

/**
 * access hook
 */
function video_access($op, $node) {
  switch($op) {
    case 'view':
      return $node->status;   // see book.module for reference
    case 'create':
      return user_access('create video');
  }
}

/**
 * Implementation of hook_nodeapi().
 * We use this to append <enclosure> tags to the RSS feeds Drupal generates.
 */
function video_nodeapi($node, $op, $arg) {
  switch ($op) {
    case 'rss item':
      if ($node->type == 'video') {
        $attributes['url'] = _video_get_fileurl($node->vidfile) . basename($node->vidfile);
        $attributes['length'] = $node->size;
        $mime_type = _video_get_mime_type($node);
        if ($mime_type) {
          $attributes['type'] = $mime_type;
        }
        $media['url'] = $attributes['url'];
        $media['fileSize'] = $attributes['length'];
        $media['type'] = $attributes['type'];
        return array(array('key' => 'enclosure', 'attributes' => $attributes), array('key' => 'media', 'value' => '', 'attributes' => $media));
      }
    case 'revision delete':
      db_query('DELETE FROM {video} WHERE vid = %d', $node->vid);
      break;
  }
}

/**
 * Hook, displays the contents of the node form page for creating and editing nodes.
 *
 * @param $node
 *   object
 *
 * @return
 *   string value of form content
 */
function video_form($node) {
  //We must unserialize the array for display in the forms.
  $node->serial_data = unserialize($node->serialized_data);

  $form = array();
  $form['title'] = array('#type' => 'textfield', '#title' => t('Title'),
    '#size' => 60, '#maxlength' => 128, '#required' => TRUE,
    '#default_value' => $node->title, '#weight' => -20);
  $form['body_filter']['body'] = array('#type' => 'textarea',
    '#title' => t('Body'), '#default_value' => $node->body,
    '#required' => TRUE, '#weight' => -15);
  $form['body_filter']['filter'] = filter_form($node->format);
  $form['log'] = array('#type' => 'fieldset', '#title' => t('Log message'),
    '#collapsible' => TRUE, '#collapsed' => TRUE);
  $form['log']['message'] = array(
    '#type' => 'textarea', '#default_value' => $node->log, '#rows' => 5,
    '#description' => t('An explanation of the additions or updates being made to help other authors understand your motivations.')
  );

  $form['video'] = array('#type' => 'fieldset', '#title' => t('Video File'), '#weight' => -19);
  $form['video']['vidfile'] = array(
    '#type' => 'textfield',
    '#title' => t('Video File'),
    '#default_value' => $node->vidfile,
    '#maxlength' => 700,
    '#required' => TRUE,
    '#description' => t('Put here the video file path. You can use either relative to the drupal root directory (something/video.mov) or absolute (http://www.example.com/videos/videos.mov). Windows Media currently requires a fully qualified URL to function. Flash movies may not play with spaces in the path or filename. To add youtube.com videos enter the video ID. If your video was at (http://www.youtube.com/watch.php?v=aBM4QYXPf-s) you would enter (aBM4QYXPf-s). To add Google videos you will need the docId values available on the embed code google provide with "google:" as heading. ') . l(t('More information.'), 'video/help', NULL, NULL, 'videofile'));
  $form['video']['videox'] = array(
    '#type' => 'textfield',
    '#title' => t('Video Size Width (x)'),
    '#required' => TRUE,
    '#length' => 4,
    '#maxlength' => 4,
    '#default_value' => $node->videox,
    '#description' => t('Horizontal video pixel size.'));
  $form['video']['videoy'] = array(
    '#type' => 'textfield',
    '#title' => t('Video Size Height (y)'),
    '#required' => TRUE,
    '#length' => 4,
    '#maxlength' => 4,
    '#default_value' => $node->videoy,
    '#description' => t('Vertical video pixel size.'));

  $form['video']['filesize'] = array('#type' => 'fieldset', '#title' => t('Filesize'));
  $form['video']['filesize']['size'] = array(
    '#type' => 'textfield',
    '#title' => t('Size'),
    '#required' => TRUE,
    '#length' => 12,
    '#maxlength' => 12,
    '#default_value' => $node->size,
    '#description' => t('If the video is on the local server the size will be set automatically. Otherwise enter a value. Entering 0 will turn the display off. Must be less than 2GB.'));
  $form['video']['filesize']['size_format'] = array(
    '#type' => 'select',
    '#title' => t('size units'),
    '#options' => array('B' => t('bytes'), 'Kb' => t('Kilobits'), 'KB' => t('KiloBytes'), 'Mb' => t('Megabits'), 'MB' => t('MegaBytes'), 'Gb' => t('Gigabits'), 'GB' => t('GigaBytes')),
    '#default_value' => 'B');

  $form['video']['playtime'] = array('#type' => 'fieldset', '#title' => t('Playtime'), '#description' => t('Values may be entered in excess of their normal "clock maximum" (the seconds field may be 3600 to represent 1 hour), however each value will be summed for a total of all three.'));
  $playtime = _video_sec2hms($node->playtime_seconds);
  $form['video']['playtime']['playtime_hours'] = array(
    '#type' => 'textfield',
    '#title' => t('Hours'),
    '#length' => 11,
    '#maxlength' => 11,
    '#default_value' => $playtime['hours'],
    '#description' => t('Integer of hours.'));
  $form['video']['playtime']['playtime_minutes'] = array(
    '#type' => 'textfield',
    '#title' => t('Minutes'),
    '#length' => 11,
    '#maxlength' => 11,
    '#default_value' => $playtime['minutes'],
    '#description' => t('Integer of minutes.'));
  $form['video']['playtime']['playtime_seconds'] = array(
    '#type' => 'textfield',
    '#title' => t('Seconds'),
    '#required' => TRUE,
    '#length' => 11,
    '#maxlength' => 11,
    '#default_value' => $playtime['seconds'],
    '#description' => t('Integer of seconds.'));

  if (variable_get('video_multidownload', 0) and user_access('create multi-file downloads')) { //If multi-file downloading is turned on display settings group.
    $form['multi-file'] = array('#type' => 'fieldset', '#title' => t('Multiple files in download tab'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => -18, '#description' => t('These options allow you to have multiple files shown on the download page. This is useful for allowing users to download different file sizes and video formats. ') . l(t('More information.'), 'video/help', NULL, NULL, 'multi-download'));
    $form['multi-file']['disable_multidownload'] = array(
      '#type' => 'checkbox',
      '#title' => t('Disable multi-file downloads'),
      '#default_value' => isset($node->disable_multidownload) ? $node->disable_multidownload : 1,
      '#description' => t('Disables multi-file downloads for this video only.'));
    $form['multi-file']['download_folder'] = array(
      '#type' => 'textfield',
      '#title' => t('Multi-file download folder'),
      '#default_value' => $node->download_folder,
      '#maxlength' => 250,
      '#description' => t('Enter the folder containing your videos. It must be relative from the drupal directory. If the absolute path is "C:\inetpub\drupal\videos\projectfolder\" or "/usr/htdocs/drupal/videos/projectfolder/" then enter something like "videos/projectfolder/".'));
    $form['multi-file']['use_play_folder'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show files in "play" folder'),
      '#default_value' => $node->use_play_folder,
      '#description' => t('Display videos in the same directory as the "play" video. If folder above is entered this will be in addition.'));
  }

  if (variable_get('video_object_parameters', 0)) { //Only display the option if it is turned on in settings.
    //We must convert the array data back to something that can go in the textarea.
    $textarea = '';
    if(is_array($node->serial_data['object_parameters'])) {
      foreach ($node->serial_data['object_parameters'] as $param => $value) {
        $textarea .= $param . '=' . $value . "\n";
      }
      $textarea = substr($textarea, 0, -1); //Remove the last newline "\n" from the end.
    }
    $form['parameters'] = array('#type' => 'fieldset', '#title' => t('HTML object parameters'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => -17);
    $form['parameters']['object_parameters'] = array(
      '#title' => t('Embedded object parameters'),
      '#type' => 'textarea',
      '#rows' => 5,
      '#default_value' => $textarea,
      '#description' => t('Enter the values that you would like to be embedded in &#60;param name="param_1" value="value_1" /&#62; tags. Each parameter should be on a seperate line with an equal sign between the parameter and its assigned value. Like param=value for example.'));
  }

  if (variable_get('video_image', 0)) { //Only display the option if it is turned on in settings.
    $form['image'] = array('#type' => 'fieldset', '#title' => t('Image thumbnails'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => -17, '#description' => t('Please enter full URL value to the image.'));
    $form['image']['image_teaser'] = array(
      '#title' => t('Image thumbnail for node teaser'),
      '#type' => 'textfield',
      '#maxlength' => 255,
      '#default_value' => $node->serial_data['image_teaser'],
      '#description' => t('This image will be displayed in the node teaser.'));
    $form['image']['image_view'] = array(
      '#title' => t('Image for node view'),
      '#type' => 'textfield',
      '#maxlength' => 255,
      '#default_value' => $node->serial_data['image_view'],
      '#description' => t('This image will be displayed on the full node view.'));
  }

  $title1 = variable_get('video_customfield1', '');
  $title2 = variable_get('video_customfield2', '');
  $title3 = variable_get('video_customfield3', '');
  $title4 = variable_get('video_customfield4', '');
  $title5 = variable_get('video_customfield5', '');
  $title6 = variable_get('video_customfield6', '');
  //Only display the custom fields group if atleast one field has a title.
  if ($title1 . $title2 . $title3 . $title4 . $title5 . $title6 != '') {
    $form['customfields'] = array('#type' => 'fieldset', '#title' => variable_get('video_customfieldtitle', 'Custom Fields'), '#collapsible' => TRUE, '#collapsed' => variable_get('video_customgroupcollapsed', FALSE), '#weight' => -17);
    //If the custom field title is not blank, then display it.
    if ($title1 != '') {
      $form['customfields']['custom_field_1'] = array(
        '#type' => 'textfield', '#title' => $title1, '#maxlength' => 250, '#default_value' => $node->custom_field_1);
    }
    if ($title2 != '') {
      $form['customfields']['custom_field_2'] = array(
        '#type' => 'textfield', '#title' => $title2, '#maxlength' => 250, '#default_value' => $node->custom_field_2);
    }
    if ($title3 != '') {
      $form['customfields']['custom_field_3'] = array(
        '#type' => 'textfield', '#title' => $title3, '#maxlength' => 250, '#default_value' => $node->custom_field_3);
    }
    if ($title4 != '') {
      $form['customfields']['custom_field_4'] = array(
        '#type' => 'textfield', '#title' => $title4, '#maxlength' => 250, '#default_value' => $node->custom_field_4);
    }
    if ($title5 != '') {
      $form['customfields']['custom_field_5'] = array(
        '#type' => 'textarea', '#title' => $title5, '#rows' => 4, '#default_value' => $node->custom_field_5);
    }
    if ($title6 != '') {
      $form['customfields']['custom_field_6'] = array(
        '#type' => 'textarea', '#title' => $title6, '#rows' => 4, '#default_value' => $node->custom_field_6);
    }
  }

  // Optional Video Metadata. We display this group expanded only if displaying of optional metadata is enabled.
  $form['metadata'] = array('#type' => 'fieldset', '#title' => t('Optional Metadata'), '#collapsible' => TRUE, '#collapsed' => !variable_get('video_display_metadata', FALSE), '#weight' => -16, '#description' => t('Metadata entered here will be displayed only if administrator enables displaying on the '.l(t('administration page'),'admin/settings/video', array('title'=>t('administration page'))).'.'));
  $form['metadata']['video_bitrate'] = array(
    '#type' => 'textfield',
    '#title' => t('Video Bitrate'),
    '#length' => 11,
    '#maxlength' => 11,
    '#default_value' => $node->video_bitrate,
    '#description' => t('Video bitrate in kbits/sec.'));
  $form['metadata']['audio_bitrate'] = array(
    '#type' => 'textfield',
    '#title' => t('Audio Bitrate'),
    '#length' => 11,
    '#maxlength' => 11,
    '#default_value' => $node->audio_bitrate,
    '#description' => t('Audio bitrate in kbits/sec.'));
  $form['metadata']['audio_sampling_rate'] = array(
    '#type' => 'select',
    '#title' => t('Audio Sampling Rate'),
    '#options' => array(0 => 'none', 8000 => '8 kHz', 11025 => '11 kHz', 16000 => '16 kHz', 22050 => '22 kHz', 32000 => '32 kHz', 44100 => '44.1 kHz', 48000 => '48 kHz', 96000 => '96 kHz', 192400 => '192 kHz'),
    '#default_value' => $node->audio_sampling_rate,
    '#description' => t('Integer value of audio sampling rate in Hz.'));
  $form['metadata']['audio_channels'] = array(
    '#type' => 'select',
    '#title' => t('Audio Channels'),
    '#options' => array('' => 'none', '5.1' => t('5.1'), 'stereo' => t('Stereo'), 'mono' => t('Mono')),
    '#default_value' => $node->audio_channels);
  // Ends Video Optional Metadata

  return $form;
}

/**
 * Hook: Create video record in video table
 *
 * @return
 *   TRUE on success, FALSE on error
 */
function video_insert($node) {
  _video_db_preprocess($node); //Make changes to data before inserting into DB.
  return db_query("INSERT INTO {video} (vid, nid, vidfile, size, videox, videoy, video_bitrate, audio_bitrate, audio_sampling_rate, audio_channels, playtime_seconds, disable_multidownload, download_folder, use_play_folder, custom_field_1, custom_field_2, custom_field_3, custom_field_4, custom_field_5, custom_field_6, serialized_data) VALUES ('%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%s', '%d', '%d', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
    $node->vid, $node->nid, $node->vidfile, $node->size, $node->videox, $node->videoy, $node->video_bitrate, $node->audio_bitrate, $node->audio_sampling_rate, $node->audio_channels, $node->playtime_seconds, $node->disable_multidownload, $node->download_folder, $node->use_play_folder, $node->custom_field_1, $node->custom_field_2, $node->custom_field_3, $node->custom_field_4, $node->custom_field_5, $node->custom_field_6, $node->serialized_data);
}

/**
 * Hook
 *
 * @return
 *   TRUE on success, FALSE on error
 */
function video_update($node) {
  _video_db_preprocess($node); //Make changes to data before updating DB.
  if ($node->revision) { //If a new node revision is being added then insert a new row.
    return video_insert($node);
  }
  else {
    return db_query("UPDATE {video} SET vidfile='%s', size='%d', videox='%d', videoy='%d', video_bitrate='%d', audio_bitrate='%d', audio_sampling_rate='%d', audio_channels='%s', playtime_seconds='%d', disable_multidownload='%d', download_folder='%s', use_play_folder='%d', custom_field_1='%s', custom_field_2='%s', custom_field_3='%s', custom_field_4='%s', custom_field_5='%s', custom_field_6='%s', serialized_data='%s' WHERE vid = '%d'",
         $node->vidfile, $node->size, $node->videox, $node->videoy, $node->video_bitrate, $node->audio_bitrate, $node->audio_sampling_rate, $node->audio_channels, $node->playtime_seconds, $node->disable_multidownload, $node->download_folder, $node->use_play_folder, $node->custom_field_1, $node->custom_field_2, $node->custom_field_3, $node->custom_field_4, $node->custom_field_5, $node->custom_field_6, $node->serialized_data, $node->vid);
  }
}

/**
 * This function makes changes to node data before it is put into the database.
 *
 * @param $node
 *   object a reference to a $node object to modify.
 *
 * @return
 *   nothing
 */
function _video_db_preprocess(&$node) {
  $serial_data = array();
  //Calculate the time in seconds.
  $node->playtime_seconds += ($node->playtime_hours * 3600) + ($node->playtime_minutes * 60);

  //If video type is youtube or googlevideo, don't attempt to get filesize (googlevideo filenames are too long to stat)
  if (_video_get_filetype($node->vidfile) != 'youtube' and _video_get_filetype($node->vidfile) != 'googlevideo') {
    //If file is on the local server get size, otherwise get size from function.
    $path = getcwd() . '/' . $node->vidfile; //Local path to video file.
    if (is_file($path)) { //If file exists locally set size.
      $node->size = filesize($path);
    }
    else {
      $node->size = _video_size2bytes($node); //Change the size to be correctly shown in bytes.
    }
  }

  //If the user doesn't have permission to use multi-download then disable it for the node.
  if (!user_access('create multi-file downloads')) {
    $node->disable_multidownload = 1;
  }

  //Stick the data from the image fields into the array.
  $serial_data['image_teaser'] = $node->image_teaser;
  $serial_data['image_view'] = $node->image_view;

  //Process the data in the object_parameters textarea.
  if ($node->object_parameters != '') { //Make sure the textarea was not empty.
    $lines = explode("\r\n", $node->object_parameters); //Make an array of each line from the textarea.
    foreach ($lines as $line) { //Loop through each line.
      $array = explode('=', $line); //Break apart at the "=" sign. $line should be in format param=value
      $serial_data['object_parameters'][$array[0]] = $array[1]; //Assign the "param" as the key and "value" as the value.
    }
  }

  $node->serialized_data = serialize($serial_data); //Serialize the data for insertion into the database.
}

/**
 * Hook
 *
 * @param $node
 *   object
 */
function video_delete($node) {
    db_query("DELETE FROM {video} WHERE nid = '%d'", $node->nid);
}

/**
 * Hook to see if every video field has been filled
 * and contains a valid value.
 *
 * @param $node
 *   object
 */
function video_validate($node) {
  if (isset($node->vidfile)) {
    if ($node->vidfile == '') {
      form_set_error('vidfile', t('You have to insert a valid file path for this video'));
    }
    else {
      //let's see if we have it yet
      $result = db_query("SELECT * from {video} WHERE vidfile = '%s' and nid <> '%d'", $node->vidfile, $node->nid);
      if (db_num_rows($result) > 0) {
        $video = db_fetch_object($result);
        $othernode = node_load($video->nid);
        form_set_error('vidfile', t('A video %link-to-existing using that link already exists', array("%link-to-existing" => l($othernode->title, 'node/' . $othernode->nid . '/edit'))));
      }
    }
  }
  if (_video_get_filetype($node->vidfile) != 'youtube' and _video_get_filetype($node->vidfile) != 'googlevideo') { //If video is of type youtube don't check size.
    if (isset($node->videox) && $node->videox <= 0) {
      form_set_error('videox', t('You have to insert a valid horizontal pixel size for this video'));
    }
    if (isset($node->videoy) && $node->videoy <= 0) {
      form_set_error('videoy', t('You have to insert a valid vertical pixel size for this video'));
    }
  }
  //Make sure file size is valid.
  $path = getcwd() . '/' . $node->vidfile; //Local path to video file.
  if (isset($node->size) and !is_file($path) and !is_numeric($node->size)) { //If the file is not local or a number then set error.
    form_set_error('size', t('You have to insert a valid file size for this video.'));
  }
  //Validate multi-file download values.
  if (user_access('create multi-file downloads')) { //Make sure the user has permission.
    //Checks to make sure either multi-downloads are disabled, or a valid folder is given, or use_play_folder is checked.
    if ($node->disable_multidownload == 0 and !is_dir(getcwd() . '/' . $node->download_folder) and $node->use_play_folder == 0) {
        form_set_error('disable_multidownload', t("Please disable multi-file downloads if you are not going to use the feature."));
        form_set_error('download_folder', t('Download directory does not exist. Make sure it has a trailing forward slash "/".'));
    }
  }
  //Makes sure the total playtime is greater than 0.
  $time = $node->playtime_seconds + $node->playtime_minutes + $node->playtime_hours;
  if ((isset($node->playtime_minutes) and isset($node->playtime_hours) and isset($node->playtime_seconds)) and $time == 0) {
    form_set_error('playtime_seconds', t('Please enter valid playtime information for this video.'));
  }
}

/**
 * Hook
 *
 * @param $node
 *   object or boolean FALSE on error
 */
function video_load($node) {
  if (is_numeric($node->vid)) {
    return db_fetch_object(db_query("SELECT * FROM {video} WHERE vid = '%d'", $node->vid));
  }
  else {
    return false;
  }
}

/**
 * Implementation of hook_view().
 * In addition to standard uses, it adds the 6 custom fields to the body of the node.
 *
 * @return
 *   Nothing, modifies $node which is passed by reference.
 */
function video_view(&$node, $teaser = FALSE, $page = FALSE) {
  $node = node_prepare($node, $teaser); //Run the body through the standard filters.
  $node->serial_data = unserialize($node->serialized_data);
  //If the main node view is being displayed then add the extra video information.
  if ($teaser == FALSE) {
    if ($node->serial_data['image_view'] and variable_get('video_image', 0)) {
      $node->body = theme('video_image_body', $node) . $node->body;
    }
    if (($node->custom_field_1 . $node->custom_field_2 . $node->custom_field_3 . $node->custom_field_4 . $node->custom_field_5 . $node->custom_field_6) != '') { //Make sure there is data to display.
      //Add the HTML formatted output of the custom fields to the bottom.
      $node->body .= theme('video_customfields', $node);
    }
    if(variable_get('video_display_metadata', FALSE)) {
      //Add the HTML formatted output of the optional video metadata to the bottom.
      $node->body .= theme('video_metadata', $node);
    }
  }
  else if ($node->serial_data['image_teaser'] and variable_get('video_image', 0)) { //If we are dealing with a teaser.
    $node->teaser = theme('video_image_teaser', $node);
  }
}

/********************************************************************
 * Block display functions
 ********************************************************************/

/**
 * Hook block. Does all the interaction with the drupal block system. Uses video_block_list() for DB queries.
 *
 * @param $op
 *   string type of block
 *
 * @param $delta
 *   integer 0 for latest, 1 for played+downloaded, 2 for most played, 3 for most downloaded.
 *
 * @param $edit
 *   array holds the data submitted by the configure forms.
 *
 * @return
 *   array
 */
function video_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0]['info'] = t('Latest videos');
    $blocks[1]['info'] = t('Top videos');
    $blocks[2]['info'] = t('Most played videos');
    $blocks[3]['info'] = t('Most downloaded');
    $blocks[4]['info'] = t('Random video');
    return $blocks;
  }
  else if ($op == 'view') {
    switch ($delta) {
      case 0:
        return array(
          'subject' => variable_get('video_block_title_0', t('Latest videos')),
          'content' => video_block_list($delta)
        );
      case 1:
        return array(
          'subject' => variable_get('video_block_title_1', t('Top videos')),
          'content' => video_block_list($delta)
        );
      case 2:
        return array(
          'subject' => variable_get('video_block_title_2', t('Most played videos')),
          'content' => video_block_list($delta)
        );
      case 3:
        return array(
          'subject' => variable_get('video_block_title_3', t('Most downloaded')),
          'content' => video_block_list($delta)
        );
      case 4:
        return array(
          'subject' => variable_get('video_block_title_4', t('Random video')),
          'content' => video_block_list($delta)
        );
    }
  }
  else if ($op == 'configure') {
    switch ($delta) { //Get the default title of the block incase the variable is not set yet.
      case 0:
        $default_title = t('Latest videos');
        break;
      case 1:
        $default_title = t('Top videos');
        break;
      case 2:
        $default_title = t('Most played videos');
        break;
      case 3:
        $default_title = t('Most downloaded');
        break;
      case 4:
        $default_title = t('Random video');
    }
    $form['video_block_title'] = array(
      '#type' => 'textfield',
      '#title' => t('Block display title'),
      '#default_value' => variable_get("video_block_title_$delta", $default_title));
    $form['video_block_limit'] = array(
      '#type' => 'select',
      '#title' => t('Number of videos to list in block'),
      '#default_value' => variable_get("video_block_limit_$delta", 10),
      '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)));
    return $form;
  }
  else if ($op == 'save') {
    variable_set("video_block_title_$delta", $edit['video_block_title']);
    variable_set("video_block_limit_$delta", $edit['video_block_limit']);
  }
}

/**
 * Query DB for block content
 *
 * @param $delta
 *   int 0, 1, 2, or 3. Determines which type of block is being accessed.
 *
 * @return
 *   string HTML content for a block
 */
function video_block_list($delta = 0) {
  $count = variable_get("video_block_limit_$delta", 10);
  switch ($delta) {
    case 0:
      $orderby = 'n.created';
      break;
    case 1:
      $orderby = 'v.download_counter + v.play_counter';
      break;
    case 2:
      $orderby = 'v.play_counter';
      break;
    case 3:
      $orderby = 'v.download_counter';
      break;
    case 4:
      $count = 1;
      $orderby = 'RAND()';
      break;
  }
  return node_title_list(db_query_range(db_rewrite_sql("SELECT n.nid, n.title FROM {node} n, {video} v WHERE n.vid = v.vid AND n.type = 'video' AND n.status = 1 AND n.moderate = 0 ORDER BY $orderby DESC"),0, $count));
}

/****************************************************
 * Menu callback functions
 ****************************************************/

/**
 * Either redirects to download the video file.
 * Or displays a list of files to download.
 */
function video_download() {
  if ($node = node_load(arg(1))) {
    if (variable_get("video_multidownload", 0) == 0 or $node->disable_multidownload == 1) {
      if (_video_get_filetype($node->vidfile) != 'youtube' and _video_get_filetype($node->vidfile) != 'googlevideo') { //Make sure the video type is not youtube before downloading.
        _video_download_goto($node->vidfile, $node->vid);
      }
      else { //If video is type youtube then it can't be downloaded.
        drupal_set_message(t('There are no files to download for this video.'), 'error');
        print theme('page', '');
      }
    }
    else if (arg(3) != '') { //If we are passed an encoded URL redirect to the downloader.
      _video_download_goto(arg(3), $node->vid, TRUE);
    }
    else { //Multiple file downloads is turned on.
      $download_error = FALSE; //Initialize and clear the error flag.
      $node->file_array = array(); //Initialize the final file array.
      global $base_url;
      $full_download_folder = getcwd() . '/' . $node->download_folder; //Get absolute path to folder.
      //If the download folder is set and valid scan it for files.
      if ($node->download_folder != '' and file_exists($full_download_folder)) {
        $scan_download_folder = _video_scandir($full_download_folder); //Get array of file names in the directory.
        $scan_download_folder['local_dir'] = $full_download_folder; //For getting filesize.
        $scan_download_folder['dir_stub'] = $node->download_folder; //To put in the URL.
        $folder_array[] = $scan_download_folder;
      }
      //If option is set to use "play" folder and it exists, scan it for files.
      $play_dir_stub = str_replace(basename($node->vidfile), "", $node->vidfile); //Remove the filename from the play file to get directory.
      $play_dir = getcwd() . '/' . $play_dir_stub; //Get the local directory path where the file is kept.
      if ($node->use_play_folder == 1 and file_exists($play_dir) and $play_dir_stub != '/') { //Make sure play stub won't allow scanning base drupal directory.
        $scan_play_folder = _video_scandir($play_dir);
        $scan_play_folder['local_dir'] = $play_dir; //For getting filesize.
        $scan_play_folder['dir_stub'] = $play_dir_stub; //To put in the URL.
        $folder_array[] = $scan_play_folder;
      }

      if (count($folder_array) > 0) { //Make sure we have a folder to scan.
        foreach ($folder_array as $dir_scan) { //Scan through one or both folders results.
          foreach ($dir_scan as $file) { //Go through each file in the directory.
            if (is_file($dir_scan['local_dir'] . "/" . $file)) { //Make sure it's a valid file.
              //Checks the new file with the files already in the array to eliminate dupes.
              $match = false;
              foreach ($node->file_array as $file_array_file) {
                if ($file_array_file['file'] == $file) { //If the file is already in the array.
                  $match = TRUE;
                }
              } //If we get here with $match still set FALSE we don't have a dupe.

              $file_ext = substr($file, strrpos($file, '.') + 1); //Get the file extension.
              $ext_array = explode(',', variable_get('video_download_ext', 'mov,wmv,avi'));

              if (!$match and in_array($file_ext, $ext_array)) { //Only add file if it's not already in the array and it's extension shouldn't be hidden.
                $file_array_size[] = filesize($dir_scan['local_dir'] . $file); //Create an array of the file sizes for sorting.

                global $base_url;
                $file_url = $base_url . '/' . $dir_scan['dir_stub'] . $file; //Generate absolute URL to video.
                $file_url = str_replace(' ', '%20', $file_url); //Replace any spaces in filename.
                $encoded_url = base64_encode($file_url); //Encode URL to base64 MIME value so it can be passed in URL.
                $encoded_url = str_replace('/', '-', $encoded_url); //Replace "/" with "-" so it doesn't mess up the URL.

                $node->file_array[] = array( 'file' => $file
                  , 'type' => $file_ext
                  , 'size' => filesize($dir_scan['local_dir'] . $file)
                  , 'encoded_url' => $encoded_url
                  );
              }
            } //Close the valid file check.
          } //Close the directory scan.
        } //Close scan location array.

        if (count($node->file_array) > 0) { //Make sure atleast 1 file was found.
          array_multisort($file_array_size, SORT_ASC, $node->file_array); //Sort based of file size.

        }
        else { //Else if no files were found in the directory.
          $download_error = TRUE;
        }
      }
      else { //Else if we have no valid folders to scan.
        $download_error = TRUE;
      }

      //If there was no error send the files array to the theme function for display.
      if($download_error == FALSE){
        print theme('video_download', $node); //Print to the screen from the theme_video_download function.
      }
      else { //Else if there is an error download the play file.
        _video_download_goto($node->vidfile, $node->vid);
      }

    } //Close multi-file downloads is turned on.
  }
  else {
    drupal_not_found();
  }
}

/**
 * Implements play callback function from node menu
 */
function video_play() {
  if ($node = node_load(arg(1))) {
    drupal_set_title(t('Playing') . ' ' . $node->title);
    switch (_video_get_filetype($node->vidfile)) {
      case 'mov':
      case 'mp4':
      case '3gp':
        print theme('video_play_quicktime', $node);
        break;
      case 'rm':
        print theme('video_play_realmedia', $node);
        break;
      case 'flv':
        print theme('video_play_flash', $node);
        break;
      case 'swf':
        print theme('video_play_swf', $node);
        break;
      case 'dir':
      case 'dcr':
        print theme('video_play_dcr', $node);
        break;
      case 'wmv':
        print theme('video_play_windowsmedia', $node);
        break;
      case 'youtube':
        print theme('video_play_youtube', $node);
        break;
      case 'googlevideo':
        print theme('video_play_googlevideo', $node);
        break;
      default:
        drupal_set_message('Video type not supported', 'error');
        drupal_goto("node/$node->nid");
        break;
    }
    if (variable_get('video_playcounter', 1)) {
      db_query("UPDATE {video} SET play_counter = play_counter + 1 where vid = '%d'", $node->vid); //Increment play counter.
    }
  }
  else {
    drupal_not_found();
  }
}

/*********************************************************************
 * Themeable functions for playing videos. They print a page with a player embedded.
 *********************************************************************/

/**
 * Play videos from in Flash video format
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_play_flash($node) {
  $loader_location = variable_get('video_flvplayerloader', 'Player.swf');
  $file = basename($node->vidfile);
  $url = _video_get_fileurl($node->vidfile);
  $output = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'.$node->videox.'" height="'.$node->videoy.'" id="Player">
               <param name="allowScriptAccess" value="sameDomain" />
               <param name="movie" value="'.$loader_location.'" />
               <param name="quality" value="high" />
               <param name="FlashVars" value="baseURL='. $url .'&videoFile='. $file .'&autoPlay=true&bufferLength=5" />
               <embed src="'.$loader_location.'" flashvars="baseURL='. $url .'&videoFile='. $file .'&autoPlay=true&bufferLength=5"  width="'.$node->videox.'" height="'.$node->videoy.'" name="Player" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
             </object>';
  $output = _theme_video_format_play($output, t('http://www.macromedia.com/go/getflashplayer'),
                                      t('Link to Macromedia Flash Player Download Page'),
                                      t('Download latest Flash Player'));
   return theme('page', $output);
}

/**
 * Play Flash .swf files.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_play_swf($node) {
  $output = "<object width=\"$node->videox\" height=\"$node->videoy\">
               <param name=\"movie\" value=\"$node->vidfile\" />"
               . _video_get_parameters($node->serialized_data) .
               "<embed src=\"$node->vidfile\" width=\"$node->videox\" height=\"$node->videoy\" />
             </object>";
  $output = _theme_video_format_play($output, t('http://www.macromedia.com/go/getflashplayer'), t('Link to Flash player download'), t('Download the latest Flash player'));
  return theme('page', $output);
}

/**
 * Play Director .dcr/.dir files.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */

function theme_video_play_dcr($node) {
  $file = basename($node->vidfile);
  $url = _video_get_fileurl($node->vidfile);
  $output = '<object classid="clsid:166B1BCA-3F9C-11CF-8075-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=10,0,0,0" width="'.$node->videox.'" height="'.$node->videoy.'" ID="player" />
  			 <param name="src" value="'.$node->vidfile.'" />
  			 '. _video_get_parameters($node->serialized_data) .'
  			 <embed src="'.$node->vidfile.'" width="'.$node->videox.'" height="'.$node->videoy.'" type="application/x-director" pluginspace="http://www.macromedia.com/shockwave/download/" />
  			 </object>';
  $output = _theme_video_format_play($output, t('http://www.macromedia.com/shockwave/download/'),
                                      t('Link to Macromedia Shockwave Player Download Page'),
                                      t('Download latest Shockwave Player'));
   return theme('page', $output);
}

/**
 * Play videos from in Quicktime format
 *
 * @see http://developer.apple.com/internet/ieembedprep.html
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_play_quicktime($node) {
  drupal_set_html_head('<script src="'. drupal_get_path('module', 'video') .'/video_insert.js" language="JavaScript" type="text/javascript"></script>');
  $height = $node->videoy + 16; //Increase the height to accommodate the player controls on the bottom.
  $output = '<script language="JavaScript" type="text/javascript">';
  $output .= "InsertQuicktimeVideo('{$node->vidfile}','$height','{$node->videox}');";
  $output .= '</script>';
  $output = _theme_video_format_play($output, t('http://www.apple.com/quicktime/download'),
                                      t('Link to QuickTime Download Page'),
                                      t('Download latest Quicktime Player'));
  return theme('page', $output);
}

/**
 * Play videos from in Realmedia format
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_play_realmedia($node) {
  // Real's embeded player includes the controls
  // in the height
  $node->videoy += 40;
  $output = '<object id="video1" classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" height="'.$node->videoy.'" width="'.$node->videox.'">
              <param name="_ExtentX" value="7276" />
              <param name="_ExtentY" value="3307" />
              <param name="AUTOSTART" value="1" />
              <param name="SHUFFLE" value="0" />
              <param name="PREFETCH" value="0" />
              <param name="NOLABELS" value="0" />
              <param name="SRC" value="'.$node->vidfile.'" ref />
              <param name="CONTROLS" value="All" />
              <param name="CONSOLE" value="Clip1" />
              <param name="LOOP" value="0" />
              <param name="NUMLOOP" value="0" />
              <param name="CENTER" value="0" />
              <param name="MAINTAINASPECT" value="0" />
              <param name="BACKGROUNDCOLOR" value="#000000" />
              <embed src="'.$node->vidfile.'" type="audio/x-pn-realaudio-plugin" console="Clip1" controls="All" height="'.$node->videoy.'" width="'.$node->videox.'" autostart="true"></embed>
            </object>';
  $output = _theme_video_format_play($output, t('http://www.real.com/'),
                                      t('Link to Real'),
                                      t('Download latest Realmedia Player'));
  return theme('page', $output);
}

/**
 * Play videos from in WindowsMediaVideo format
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_play_windowsmedia($node) {
  // Windows Media's embeded player includes the controls in the height
  $node->videoy += 68;
  $vidfile = _video_get_fileurl($node->vidfile) . basename($node->vidfile);
  $output = '<object id="video1" width="'.$node->videox.'" height="'.$node->videoy.'"
              classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95"
              codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
              standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject">
              <param name="fileName" value="'.$vidfile.'" />
              <param name="animationatStart" value="true" />
              <param name="transparentatStart" value="true" />
              <param name="autoStart" value="true" />
              <param name="showControls" value="true" />
              <param name="loop" value="true" />
              <embed type="application/x-mplayer2"
                pluginspage="http://microsoft.com/windows/mediaplayer/en/download/"
                id="mediaPlayer" name="mediaPlayer" displaysize="4" autosize="-1"
                showcontrols="true" showtracker="-1"
                showdisplay="0" showstatusbar="-1" videoborder3d="-1" width="'.$node->videox.'" height="'.$node->videoy.'"
                src="'.$vidfile.'" autostart="true" loop="true"></embed>
             </object>';

  $output = _theme_video_format_play($output, t('http://windowsupdate.microsoft.com/'),
                                      t('Link to Windows Update'),
                                      t('Download latest Windows Media Player'));
  return theme('page', $output);
}

/**
 * Play videos hosted on youtube.com
 * Allows users to host videos on youtube.com and then use the video ID to post it in the module.
 * In the future it could also use the youtube developer API to get info and comments of the video.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_play_youtube($node) {
  $width = ($node->videox ? $node->videox : '425');
  $height = ($node->videoy ? $node->videoy : '350');
  $output = '<object width="'.$width.'" height="'.$height.'">
               <param name="movie" value="http://www.youtube.com/v/' . $node->vidfile . '" />
               <embed src="http://www.youtube.com/v/' . $node->vidfile . '" type="application/x-shockwave-flash" width="'.$width.'" height="'.$height.'"></embed>
             </object>';
  $output = _theme_video_format_play($output, t('http://www.youtube.com/help.php'), t('Link to youtube.com'), t('youtube.com'));
  return theme('page', $output);
}

/**
 * Play videos hosted on video.google.com
 * Allows users to host videos on video.google.com and then use the video ID to post it in the module.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_play_googlevideo($node) {
  $width = ($node->videox ? $node->videox : '425');
  $height = ($node->videoy ? $node->videoy : '350');
  // Strip heading "google:"
  $videoid = substr($node->vidfile, 7);
  $output = '<object width="'.$width.'" height="'.$height.'">
               <param name="movie" value="http://video.google.com/googleplayer.swf?docId=' . $videoid . '"></param>
               <embed style="width:' . $width . 'px; height=' . $height . 'px;"  src="http://video.google.com/googleplayer.swf?docId=' . $videoid . '" type="application/x-shockwave-flash" width="'.$width.'" height="'.$height.'" allowScriptAccess="sameDomain" quality="best" bgcolor="#ffffff" scale="noScale" wmode="window" salign="TL"  FlashVars="playerMode=embedded"></embed>
             </object>';

  $output = _theme_video_format_play($output, t('http://video.google.com/support'), t('Link to video.google.com'), t('video.google.com'));
  return theme('page', $output);
}

/**
 * Cut down on redundant link text
 *
 * @param $url
 *   string URL to link to
 *
 * @param $title
 *   string title of link to show on mouseover
 *
 * @param $link_text
 *   string text of the link
 *
 * @return
 *   string HTML link
 */
function _theme_video_format_play($output, $url, $title, $link_text) {
  $output = "\n<div id=\"video-player\">\n" . $output;
  $output .= "<p>\n". t('Problems viewing videos?');
  $output .= "<br />\n<a href=\"$url\" title=\"$title\">$link_text</a>";
  return $output ."\n</p> \n </div>\n";
}

/**
 * Display custom fields on the view page.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_customfields($node) {
  //Adds the custom fields.
  $group_title = variable_get('video_customfieldtitle', ''); //Title of the custom fields.
  $title1 = variable_get('video_customfield1', '');
  $title2 = variable_get('video_customfield2', '');
  $title3 = variable_get('video_customfield3', '');
  $title4 = variable_get('video_customfield4', '');
  $title5 = variable_get('video_customfield5', '');
  $title6 = variable_get('video_customfield6', '');
  //Run the fields through the input filter set for the node, then remove paragraphs.
  //Removes the <p> and </p> tags from the filter pass return. This allows each field to be on one line.
  //A better system might be to remove only the first and last <p></P> tags.
  $field1 = str_replace(array('<p>', '</p>'), '', check_markup($node->custom_field_1, $node->format, FALSE));
  $field2 = str_replace(array('<p>', '</p>'), '', check_markup($node->custom_field_2, $node->format, FALSE));
  $field3 = str_replace(array('<p>', '</p>'), '', check_markup($node->custom_field_3, $node->format, FALSE));
  $field4 = str_replace(array('<p>', '</p>'), '', check_markup($node->custom_field_4, $node->format, FALSE));
  $field5 = str_replace(array('<p>', '</p>'), '', check_markup($node->custom_field_5, $node->format, FALSE));
  $field6 = str_replace(array('<p>', '</p>'), '', check_markup($node->custom_field_6, $node->format, FALSE));

  $output = '';
  //Make sure all the titles are not blank, if not then display them.
  if (($title1 . $title2 . $title3 . $title4 . $title5 . $title6) != '') {
    $output = '<div class="videofields">'; //Enclose all output in "videofields" div class.
    if ($group_title != '') {
      $output .= '<div class="title"><h2>' . $group_title . '</h2></div>' . "\n";
    }
    if ($title1 != '' and $node->custom_field_1 != '') {
      $fields[] = array('title' => $title1, 'body' => $field1);
    }
    if ($title2 != '' and $node->custom_field_2 != '') {
      $fields[] = array('title' => $title2, 'body' => $field2);
    }
    if ($title3 != '' and $node->custom_field_3 != '') {
      $fields[] = array('title' => $title3, 'body' => $field3);
    }
    if ($title4 != '' and $node->custom_field_4 != '') {
      $fields[] = array('title' => $title4, 'body' => $field4);
    }
    if ($title5 != '' and $node->custom_field_5 != '') {
      $fields[] = array('title' => $title5, 'body' => $field5);
    }
    if ($title6 != '' and $node->custom_field_6 != '') {
      $fields[] = array('title' => $title6, 'body' => $field6);
    }
    $output .= theme('video_fields', $fields); //Generate all the fields HTML.

    $output .= '</div><br />'; //Close the "videofields" class div.
  }
  return $output;
}

/**
 * Display optional metadata (Video and Audio bitrate,..) on the view page.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 $node->video_bitrate, $node->audio_bitrate, $node->audio_sampling_rate, $node->audio_channels,
 */
function theme_video_metadata($node) {
  //Make sure atleast one fields had data.
  if ($node->video_bitrate != 0 or $node->audio_bitrate != 0 or $node->audio_sampling_rate != 0 or $node->audio_channels != 0) {
    $output = "\n\n<div class=\"video_metadata\">\n";
    $output .= '  <div class="title"><h2>'.t('Video Metadata')."</h2></div>\n";
    if($node->video_bitrate != 0) {
      $fields[] = array('title' => t('Video Bitrate') . ':', 'body' => $node->video_bitrate . ' ' . t('kbits/sec'));
    }
    if($node->audio_bitrate != 0) {
      $fields[] = array('title' => t('Audio Bitrate') . ':', 'body' => $node->audio_bitrate . ' ' . t('kbits/sec'));
    }
    if($node->audio_sampling_rate != 0) {
      $fields[] = array('title' => t('Audio Sampling Rate') . ':', 'body' => $node->audio_sampling_rate . ' ' . t('Hz'));
    }
    if($node->audio_channels != '') {
      $fields[] = array('title' => t('Audio Channels') . ':', 'body' => $node->audio_channels);
    }
    $output .= theme('video_fields', $fields); //Generate the fields HTML.
    $output .= '</div>'; //Closing div video_metadata
  }
  else { //If all the fields are blank then display nothing.
    $output = '';
  }
  return $output;
}

/**
 * Takes an associative array of $fields with 'title' and 'body' keys and outputs the HTML.
 * This theme function allows the same HTML code to generate all the custom and metadata fields.
 *
 * @param $fields
 *   array with 'title' and 'body' keys
 *
 * @return
 *   string of content to display
 */
function theme_video_fields($fields) {
  $output = '';
  $odd_even = 'odd';
  foreach ($fields as $field) {
    $output .= "<div class=\"$odd_even\"><b>" . $field['title'] . '</b> ' . $field['body'] . "</div>\n";
    $odd_even = ($odd_even == 'odd') ? 'even' : 'odd'; //Always switch its value.
  }
  return $output;
}

/**
 * Render the output for the node teaser.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_image_teaser($node) {
  $output = '<table border="0" cellpadding="6"><tr><td>';
  $output .= l(theme('image', $node->serial_data['image_teaser'], $node->title, $node->title, NULL, FALSE), "node/$node->nid", array(), NULL, NULL, FALSE, TRUE); //Create a link with an image in it.
  $output .= '</td><td valign="top">' . $node->teaser . '</td></tr></table>';
  return $output;
}

/**
 * Generates the image HTML displayed in the Node body.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_image_body($node) {
  $image = theme('image', $node->serial_data['image_view'], $node->title, $node->title, NULL, FALSE); //Create image HTML
  $output = l($image, "node/$node->nid/play", array(), NULL, NULL, FALSE, TRUE); //Create link HTML with image in it.
  return $output;
}

/**
 * Outputs the HTML for the download page when multi-file download are turned on.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_download($node) {
  $output = '';
  //Replace some common file types with full name and links.
  $find = array('mov', 'wmv', 'rm', 'avi', 'zip', 'divx', 'flv');
  $replace = array('<a href="http://www.apple.com/quicktime" title="'. t('QuickTime Homepage') . '">' . t('Quicktime') . '</a>'
             , '<a href="http://www.microsoft.com/windowsmedia" title="'. t('Windows Media Homepage') . '">' . t('Windows Media') . '</a>'
             , '<a href="http://www.real.com" title="'. t('Real Media Homepage') . '">' . t('Real Media') . '</a>'
             , '<a href="http://en.wikipedia.org/wiki/AVI" title="'. t('AVI Information at wikipedia.org') . '">' . t('AVI') . '</a>'
             , '<a href="http://en.wikipedia.org/wiki/ZIP_file_format" title="'. t('ZIP Information at wikipedia.org') . '">' . t('ZIP') . '</a>'
             , '<a href="http://www.divx.com" title="'. t('Divx Homepage') . '">' . t('DIVX') . '</a>'
             , '<a href="http://www.macromedia.com/go/getflashplayer" title="'. t('Macromedia Flash Homepage') . '">' .t('Flash FLV') . '</a>'
             );
  $output .= '<br /><div class="videodownload">'; //Enclose all HTML in "videodownload" class.
  foreach($node->file_array as $file) { //Goes through the array of video files and gets them ready for display.
    $file_type = str_replace($find, $replace, $file['type']); //Match and replace common file types.
    $link = l($file['file'], "node/$node->nid/download/" . $file['encoded_url']); //Create link to download file.
    $file_array_table[] = array($link, format_size($file['size']), $file_type); //Create table row.
  }
  $headers = array(t('File Link'), t('File Size'), t('File Type'));
  $output .= theme_table($headers, $file_array_table); //Create the table of files.
  $output .= '</div>'; //Close the "videodownload" class.

  //Adds a breadcrumb back to view on the download page. This may not be needed but some better breadcrumbs are.
  $breadcrumb = drupal_get_breadcrumb();
  $breadcrumb[] = l(t('View'), "node/$node->nid");
  drupal_set_breadcrumb($breadcrumb);

  drupal_set_title(t('Downloading').' '.$node->title);
  return theme("page", $output);
}

/******************************************************************************
 * End theme functions
 ******************************************************************************
 * Start private functions created for this module.
 ******************************************************************************/

/**
 * Pull the file extension from a filename
 *
 * @param $vidfile
 *   string filename to get the filetype from.
 *
 * @return
 *   string value of file type or boolean FALSE on error
 */
function _video_get_filetype($vidfile) {
    //If the filename doesn't contain a ".", "/", or "\" and is exactly 11 characters then consider it a youtube video ID.
    if (!strpos($vidfile, '.') and !strpos($vidfile, '/') and !strpos($vidfile, '\\') and strlen($vidfile) == 11) {
      $file_type = 'youtube';
    }
    else if (strpos($vidfile, 'google:') === 0) {
      $file_type = 'googlevideo';
    }
    else if (strstr($vidfile, '.')) { //If file contains a "." then get the file extension after the "."
      $file_type = substr($vidfile, strrpos($vidfile, '.') + 1);
    }
    else {
      $file_type = FALSE;
    }
    return $file_type;
}

/**
 * Forward user directly to the file for downloading
 *
 * @param $input_url
 *   string should be either a base64 encoded absolute URL, relative URL, or absolute URL.
 *
 * @param $vid
 *   integer node version ID of the node to have it's download counter updated.
 *
 * @param $base64_encoded
 *   boolean value determines whether the $input is base64 encoded.
 *
 * @return
 *   Nothing
 */
function _video_download_goto($input_url, $vid, $base64_encoded = FALSE) {
  if (user_access('download video')) {
    if ($base64_encoded) {
      $encoded_url = str_replace('-', '/', $input_url); //Replace "-" to "/" for MIME base64.
      $location = base64_decode($encoded_url);
    }
    else { //$input URL is not base64 encoded.
      $location = _video_get_fileurl($input_url) . basename($input_url);
    }
    if (variable_get('video_downloadcounter', 1)) {
      db_query("UPDATE {video} SET download_counter = download_counter + 1 where vid = '%d'", $vid); //Increment download counter.
    }
    header("Location: $location"); //Redirect to the video files URL.
  }
  else { //If the user does not have access to download videos.
    drupal_set_message(t('You do not have permission to download videos.'), 'error');
    $node = node_load(array('vid' => $vid)); //Load a node with the $vid so we can get the nid.
    drupal_goto("node/$node->nid"); //Use the nid we just loaded to go back to the node page.
  }
}

/**
 * Scans a directory and returns an array of all the filenames in the directory.
 * This function is only necessary to maintain PHP 4 support.
 *
 * @param $dir
 *   The directory. Can be an absolute path or relative from the current working directory.
 *
 * @return
 *   array of filenames.
 */
function _video_scandir($dir) {
  //Try a few different ways to open the directory.
  if (is_dir($dir)) {
    $dir_open = opendir($dir);
  }
  else if (is_dir($new_dir = getcwd() . $dir)) {
    $dir_open = opendir($new_dir);
  }
  else if (is_dir($new_dir = getcwd() . '/' . $dir)) {
    $dir_open = opendir($new_dir);
  }
  else { //If directory does not exist.
    return FALSE;
  }
  if (!$dir_open) { //If opendir returned false then return false.
    return FALSE;
  }
  //If it makes it this far $dir_open should be valid.
  while (($dir_content = readdir($dir_open)) !== FALSE) {
    $files[] = $dir_content;
  }
  return $files;
}

/**
 * Convert filesize to bytes
 *
 * @return
 *   integer bytes
 */
function _video_size2bytes($node) {
  if (!empty($node->size)) {
    switch ($node->size_format) {
      case 'Kb': // KiloBits
        return intval($node->size * 128);
        break;
      case 'KB': // KiloBytes
        return intval($node->size * 1024);
        break;
      case 'Mb': // MegaBits
        return intval($node->size * 131072);
        break;
      case 'MB': // MegaBytes
        return intval($node->size * 1048576);
        break;
      case 'Gb': // GigaBits
        return intval($node->size * 134217728);
        break;
      case 'GB': // GigaBytes
        return intval($node->size * 1073741824);
        break;
      default:
        return (int)$node->size;
        break;
    }
  }
  else {
    return 0;
  }
}

/**
 * Convert seconds to hours, minutes, and seconds.
 * Derived from h:m:s example by Jon Haworth
 *
 * @link
 *   http://www.laughing-buddha.net/jon/php/sec2hms/
 *
 * @param $sec
 *   integer value of seconds.
 *
 * @return
 *   array associative with key values of hours, minutes, and seconds.
 */
function _video_sec2hms($sec = 0) {
  $hms = array();
  // 3600 seconds in an hour and trash remainder
  $hms['hours'] = intval(intval($sec) / 3600);
  // dividing the total seconds by 60 will give us
  // the number of minutes, but we're interested in
  // minutes past the hour: to get that, we need to
  // divide by 60 again and keep the remainder
  $hms['minutes'] = intval(($sec / 60) % 60);
  $hms['seconds'] = intval($sec % 60); //keep the remainder.
  return $hms;
}

/**
 * Returns an absolute url which references
 * to the folder containing the video file
 *
 * @param $video_file
 *   string containing absolute or relative URL to video.
 *
 * @return
 *   string containing absolute URL path to video without the filename.
 */
function _video_get_fileurl($video_file) {
  global $base_url;
  //removing filename from path
  $video_path = rtrim($video_file, basename($video_file));
  //creation of absolute url
  if (!preg_match("/^(ht|f)tp(s?):\/\//", $video_path)) { //If path is not absolute.
    $video_path = $base_url . '/' . $video_path;
  }
  return $video_path;
}

/**
 * Returns the correct mime-type for the video. Returns false if the
 * mime-type cannot be detected.
 */
function _video_get_mime_type($node) {
  switch (_video_get_filetype($node->vidfile)) {
    case 'mov':
      return 'video/quicktime';
    case 'rm':
      return 'application/vnd.rn-realmedia';
    case 'flv':
      return 'flv-application/octet-stream';
    case 'wmv':
      return 'video/x-ms-wmv';
    case '3gp':
      return 'video/3gpp';
    case 'mp4':
      return 'video/mp4';
    case 'dir':
    case 'dcr':
      return 'application/x-director';
    // We can't support this sources properly, so return false.
    case 'youtube':
    case 'googlevideo':
      return false;
    default:
      // We couldn't detect the mime-type, so return false.
      return false;
  }
}

/**
 * Generates the HTML for any object parameters in an embedded video.
 *
 * @param $serialized_data
 *   string of the serialized data directly from the database.
 *
 * @return
 *   string with the parameters in HTML form.
 */
function _video_get_parameters($serialized_data) {
  $serial_data = unserialize($serialized_data);
  if(is_array($serial_data)  && array_key_exists('object_parameters', $serial_data) && !empty($serial_data['object_parameters'])) {
    $output = '';
    foreach ($serial_data['object_parameters'] as $param => $value) {
      $output .= "<param name=\"$param\" value=\"$value\" />\n";
    }
  }
  return $output;
}