-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathytca.php
1879 lines (1700 loc) · 64.7 KB
/
ytca.php
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
<?php
/*
* YouTube Captions Auditor (YTCA)
* version 1.1
*
*/
/*******************
* *
* CONFIGURATION *
* *
*******************/
// See the YouTube API reference for instructions on obtaining an API key
// https://developers.google.com/youtube/v3/docs/
// Store API key in a local file
$apiKeyFile = 'apikey'; // name of local file in which API key is stored
// Debug (can be overwritten with parameter 'debug' in URL)
// Value is either 1, 2, or false (default)
// 1 = Adds additional data to output: Expected # of videos per channel & Google cost (in units)
// 2 = Same as 1, plus displays YouTube API query URLs in output so user can inspect raw data directly
// Legacy value of 'true' = 2
$settings['debug'] = false;
// Path to channels ini file (can be overwritten with parameter 'channels' in URL)
$settings['channelsFile'] = 'channels.ini';
// Output (can be overwritten with parameter 'output' in URL)
// Supported values: html, xml, json
$settings['output'] = 'html';
// Report (can be overwritten with parameter 'report' in URL)
// Supported values:
// summary - counts and other stats for each channel
// details - metadata, traffic data, and caption data for each video in results
$settings['report'] = 'summary';
// Filter Type (can be overwritten with parameter 'filtertype' in URL)
// Used in conjunction with Filter Value to filter videos based on views
// This can be used to prioritize accessibility efforts on videos that have the highest traffic
// Supported values:
// views - limit results to videos that have X or more views
// percentile - limit results to videos that fall into the X percentile for the channel based on views (e.g., the top 10%)
// count - limit results to the top X videos for the channel, based on views
// NULL - do not filter; include all videos in audit
$filterType = NULL;
// Filter Value (can be overwritten with parameter 'filtervalue' in URL)
// Used to define the value of Filter Type, as explained above
// Set to NULL if no filtering is used
$filterValue = NULL;
// Title of report (can be overwritten with URL-encoded parameter 'title' in URL)
$settings['title'] = 'YouTube Caption Auditor (YTCA) Report';
// Time unit for "Duration" data (can be overwritten with 'timeunit' in URL)
// Supported values are 'seconds' (default), 'minutes', or 'hours'
$settings['timeUnit'] = 'seconds';
// Include Channel ID
// Set to true to include a YouTube Channel ID column in the HTML output of summary report; otherwise false
$settings['showChannelId'] = false;
// Highlights
// Optionally, the report can highlight channels that are either doing good or bad at captioning
// To use this feature, set the following variables
// if $highlights['use'] is false, all other variables are ignored
$highlights['use'] = true;
$highlights['goodPct'] = 50; // Percentages >= this value are "good"
$highlights['badPct'] = 0; // Percentages <= this value are "bad"
$highlights['goodLabel'] = 'Exemplary channel'; // title attribute on channel name for 'good' channels
$highlights['badLabel'] = 'Needs work'; // title attribute on channel name for 'bad' channels
/***********************
* *
* END CONFIGURATION *
* *
***********************/
error_reporting(E_ERROR | E_PARSE);
ini_set('max_execution_time',0); // in seconds; 0 = run until finished
// calculate time of execution
$timeStart = microtime(true);
$apiKey = file_get_contents($apiKeyFile);
// Override default variables with GET params
if (isset($_GET['debug'])) {
// convert to boolean; accept 'true', 1 or 2
if (strtolower($_GET['debug']) == 'true' || $_GET['debug'] == '2') {
$settings['debug'] = 2;
}
elseif ($_GET['debug'] == '1') {
$settings['debug'] = 1;
}
}
if (isset($_GET['output'])) {
if (isValid('output',strtolower($_GET['output']))) {
$settings['output'] = strtolower($_GET['output']);
}
}
if (isset($_GET['report'])) {
if (isValid('report',strtolower($_GET['report']))) {
$settings['report'] = strtolower($_GET['report']);
}
}
$filter = false;
$sortBy = 'title'; // default, conditionally overridden
if (isset($_GET['date-start'])) {
if (isValid('date',$_GET['date-start'])) {
$filter['dateStart'] = $_GET['date-start'];
$sortBy = 'date';
}
}
if (isset($_GET['date-end'])) {
if (isValid('date',$_GET['date-end'])) {
$filter['dateEnd'] = $_GET['date-end'];
$sortBy = 'date';
}
}
if (isset($_GET['filtertype']) && isset($_GET['filtervalue'])) {
if (isValid('filterType',strtolower($_GET['filtertype']))) {
if (isValid('filterValue',$_GET['filtervalue'],strtolower($_GET['filtertype']))) {
$filter['type'] = strtolower($_GET['filtertype']);
$filter['value'] = $_GET['filtervalue'];
$sortBy = 'viewCount'; // takes precedence over date filter
}
}
}
if (isset($_GET['title'])) {
if (isValid('title',strip_tags($_GET['title']))) {
$settings['title'] = urldecode(strip_tags($_GET['title']));
}
}
if (isset($_GET['timeunit'])) {
if (isValid('timeUnit',strtolower($_GET['timeunit']))) {
$settings['timeUnit'] = strtolower($_GET['timeunit']);
}
}
if (isset($_GET['channels'])) {
if (isValid('channels',strip_tags($_GET['channels']))) {
$settings['channelsFile'] = urldecode(strip_tags($_GET['channels']));
}
}
if (isset($_GET['show-channel-id'])) {
// convert to boolean; accept 'true', 'false' or 1 or 0
if (strtolower($_GET['show-channel-id']) == 'true' || $_GET['show-channel-id'] == '1') {
$settings['showChannelId'] = true;
}
}
// set default vars; may be conditionally overridden
$footnotes = NULL;
showTop($settings,$highlights['goodColor'],$highlights['badColor'],$filter);
// Get channel from URL (channelid and (optionally) channelname)
// if either parameter is included in URL, that channel is audited rather than using channels.ini
if ($channelId = $_GET['channelid']) {
if (!(ischannelId($channelId))) {
// this is not a valid channel ID; must be a username
$channelIdArray = getChannelId($apiKey,$channelId);
$channelId = $channelIdArray['id']; // returns null if getChannelId() fails to return an id
// initiate auditing vars
$initChannelCost = $channelIdArray['cost'];
$initChannelRequest = 1;
}
$channels[0]['id'] = $channelId;
if (isset($_GET['channelname'])) {
$channels[0]['name'] = $_GET['channelname'];
}
else { // get the channel name from YouTube
$channelNameArray = getChannelName($apiKey,$channelId);
$channels[0]['name'] = $channelNameArray['name'];
// initiate auditing vars
$initChannelCost = $channelNameArray['cost'];
$initChannelRequests++;
}
}
else {
// get channel(s) from ini file
$channels = parse_ini_file($settings['channelsFile'],true); // TODO: Handle syntax errors in .ini file
// initiate auditing vars (no API requests required so far)
$initChannelCost = 0;
$initChannelRequests = 0;
}
if (is_array($channels)) {
$numChannels = sizeof($channels);
if ($numChannels > 0) {
// initialize $totals
// all videos (count and duration)
$totals['all']['count'] = 0;
$totals['all']['duration'] = 0;
$totals['all']['views'] = 0;
$totals['all']['maxViews'] = 0;
if ($settings['debug'] > 0) {
$totals['all']['approxCount'] = 0;
$totals['all']['requests'] = $initChannelRequests;
$totals['all']['cost'] = $initChannelCost;
}
// captioned videos (count and duration)
$totals['cc']['count'] = 0;
$totals['cc']['duration'] = 0;
if (!$filter) {
// no reason to separate out high traffic videos if already filtering for high traffic
// high traffic videos (count and duration)
$totals['highTraffic']['count'] = 0;
$totals['highTraffic']['duration'] = 0;
// captioned high traffic videos (count and duration)
$totals['ccHighTraffic']['count'] = 0;
$totals['ccHighTraffic']['duration'] = 0;
}
$channelMeta = getChannelMeta($channels); // return an array of metadata for each channel, else false
if (function_exists('array_key_first')) { // function introduced in PHP 7.3.0
$k = array_key_first($channels);
}
else {
$k = getFirstKey($channels);
}
if (function_exists('array_key_last')) { // function introduced in PHP 7.3.0
$lastKey = array_key_last($channels);
}
else {
$lastKey = getLastKey($channels);
}
$c = 0; // counter
// prepare to write output immediately to screen (rather than wait for script to finish executing)
if (ob_get_level() == 0) {
ob_start();
}
if ($settings['output'] == 'html') {
if ($settings['report'] == 'summary') {
$firstChannelName = $channels[$k]['name'];
$footnotes = showSummaryTableTop($settings,$numChannels,$firstChannelName,$channelMeta,$filter);
}
}
elseif ($settings['output'] == 'xml') {
echo '<channels>'."\n";
}
elseif ($settings['output'] == 'json') {
echo '"channels": ['."\n";
}
// Step through each channel
while ($k <= $lastKey) {
$channelRequests = $initChannelRequests;
$channelCost = $initChannelCost;
if (!(ischannelId($channels[$k]['id']))) {
// this is not a valid channel ID; must be a username
// getChannelId() returns an array with 'id' and 'cost'
$channelIdArray = getChannelId($apiKey,$channels[$k]['id']);
$channels[$k]['id'] = $channelIdArray['id'];
$channelCost += $channelIdArray['cost'];
$channelRequests++;
}
$channelQueryArray = buildYouTubeQuery('search',$channels[$k]['id'],NULL,$apiKey,$sortBy);
$channelQuery = $channelQueryArray['url'];
$channelCost += $channelQueryArray['cost'];
$channelRequests++;
// create an array of metadata for this channel (if any exists)
$numKeys = sizeof($channels[$k]);
if ($numKeys > 2) {
// there is supplemental meta data in the array
$keys = array_keys($channels[$k]);
$i = 0;
while ($i < $numKeys) {
$key = $keys[$i];
if ($key !== 'name' && $key !== 'id') {
$metaKeys[] = $key;
}
$i++;
}
}
if ($settings['debug'] == 2 && $settings['output'] == 'html') {
echo '<div class="ytca_debug ytca_channel_query">';
echo '<span class="query_label">Initial channel query:</span>'."\n";
echo '<span class="query_url"><a href="'.$channelQuery.'">'.$channelQuery."</a></span>\n";
echo "</div>\n";
}
if ($content = fileGetContents($channelQuery)) {
$json = json_decode($content,true);
if ($channels[$k]['id'] == $channels[$k]['name']) {
// id and name are the same - reset with channel name from search results
$channels[$k]['name'] = $json['items'][0]['snippet']['channelTitle'];
}
$approxNumVideos = $json['pageInfo']['totalResults'];
$channel['videoCount'] = $numVideos;
if ($approxNumVideos > 0) {
// add a 'videos' key for this channel that point to all videos
$videosArray = getVideos($settings,$channels[$k]['id'],$json,$approxNumVideos,$apiKey,$sortBy);
$channels[$k]['videos'] = $videosArray;
$channelCost += $videosArray['cost'];
$channelRequests += $videosArray['requests'];
}
else {
// TODO: handle error: No videos returned by $channelQuery
}
}
else {
// TODO: handle error: Unable to retrieve file: $channelQuery
}
if ($filter) {
$videos = applyFilter($channels[$k]['videos'],$filter);
}
else {
$videos = $channels[$k]['videos'];
}
// $numVideos is the *actual* number of videos returned
// Note that it includes 2 additional keys ('requests' and 'costs') that must be removed from the total
$numVideos = sizeof($videos) - 2;
// add values to channel totals
if ($settings['debug'] > 0) {
$channelData['all']['approxCount'] = $approxNumVideos;
$channelData['all']['requests'] = $channelRequests;
$channelData['all']['cost'] = $channelCost;
}
$channelData['all']['count'] = $numVideos;
$channelData['all']['duration'] = calcDuration($videos,$numVideos);
$viewsData = countViews($videos,$numVideos); // returns array with keys 'count' and 'max'
$channelData['all']['views'] = $viewsData['count'];
$channelData['all']['maxViews'] = $viewsData['max'];
$channelData['all']['avgViews'] = round($channelData['all']['views']/$channelData['all']['count']);
$channelData['cc']['count'] = countCaptioned($videos,$numVideos);
$channelData['cc']['duration'] = calcDuration($videos,$numVideos,'true');
if (!$filter) {
// no reason to separate out high traffic videos if already filtering for high traffic
$highTrafficThreshold = $channelData['all']['avgViews'];
$channelData['highTraffic']['count'] = countHighTraffic($videos,$numVideos,$highTrafficThreshold);
$channelData['highTraffic']['duration'] = calcDuration($videos,$numVideos,NULL,$highTrafficThreshold);
$channelData['ccHighTraffic']['count'] = countCaptioned($videos,$numVideos,$highTrafficThreshold);
$channelData['ccHighTraffic']['duration'] = calcDuration($videos,$numVideos,'true',$highTrafficThreshold);
}
$rowNum = $c + 1;
if ($rowNum < $numChannels) {
$nextChannelName = $channels[$rowNum]['name'];
}
if ($settings['report'] == 'details') {
// show details for this channel
showDetails($settings,$rowNum,$numChannels,$channels[$k],$channelMeta[$k],$channelData,$videos,$numVideos,$filter,$sortBy);
}
else { // show a summary report
showSummaryTableRow($settings,$rowNum,$numChannels,$channels[$k],$nextChannelName,$channelMeta[$k],$channelData,$filter,$highlights);
// increment totals with values from this channel
if ($settings['debug'] > 0) {
$totals['all']['approxCount'] += $channelData['all']['approxCount'];
$totals['all']['requests'] += $channelData['all']['requests'];
$totals['all']['cost'] += $channelData['all']['cost'];
}
$totals['all']['count'] += $channelData['all']['count'];
$totals['all']['duration'] += $channelData['all']['duration'];
$totals['all']['views'] += $channelData['all']['views'];
if ($channelData['all']['maxViews'] > $totals['all']['maxViews']) {
$totals['all']['maxViews'] = $channelData['all']['maxViews'];
}
$totals['cc']['count'] += $channelData['cc']['count'];
$totals['cc']['duration'] += $channelData['cc']['duration'];
if (!$filter) {
// no reason to separate out high traffic videos if already filtering for high traffic
$totals['highTraffic']['count'] += $channelData['highTraffic']['count'];
$totals['highTraffic']['duration'] += $channelData['highTraffic']['duration'];
$totals['ccHighTraffic']['count'] += $channelData['ccHighTraffic']['count'];
$totals['ccHighTraffic']['duration'] += $channelData['ccHighTraffic']['duration'];
}
}
$c++;
$k++;
}
if ($settings['report'] == 'summary') {
// add totals row
showSummaryTableRow($settings,'totals',$numChannels,NULL,NULL,$channelMeta[0],$totals,$filter);
showSummaryTableBottom($settings['output'],$footnotes);
}
} // end if $numChannels > 0
else {
// TODO: handle error - no channels were found
}
} // end if $channels in an array
showBottom($settings['output']);
// stop calculating time of execution and display results
$timeEnd = microtime(true);
$time = round($timeEnd - $timeStart,2); // in seconds
if ($settings['output'] == 'html' && $settings['debug'] == 2) {
echo '<p class="runTime">Total run time: '.makeTimeReadable($time).'</p>'."\n";
}
ob_end_flush();
function showTop($settings,$goodColor,$badColor,$filter=NULL) {
if ($settings['output'] == 'html') {
echo "<!DOCTYPE html>\n";
echo '<html lang="en">'."\n";
echo "<head>\n";
echo '<meta charset="utf-8">'."\n";
echo '<title>'.$settings['title']."</title>\n";
echo '<link rel="stylesheet" type="text/css" href="styles/ytca.css">'."\n";
echo "</head>\n";
echo '<body id="ytca">'."\n";
echo '<h1>'.$settings['title']."</h1>\n";
echo '<p class="date">'.date('M d, Y')."</p>\n";
echo '<div id="status" role="alert"></div>'."\n";
echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>'."\n";
echo '<script src="scripts/ytca.js"></script>'."\n";
echo '<script src="scripts/tablesort.js"></script>'."\n";
if ($filter) {
echo '<p class="filterSettings">';
echo 'Filter on. Including only ';
$needAnd = false;
if ($filter['type'] == 'views') {
echo 'videos with <span class="filterValue">'.$filter['value'].'</span> views';
$needAnd = true;
}
elseif ($filter['type'] == 'percentile') {
echo 'videos in the <span class="filterValue">';
echo $filter['value'].getOrdinalSuffix($filter['value']);
echo '</span> percentile for each channel';
$needAnd = true;
}
elseif ($filter['type'] == 'count') {
echo 'the top <span class="filterValue">'.$filter['value'].'</span> videos in each channel ';
echo '(based on views)';
$needAnd = true;
}
if ($filter['dateStart'] || $filter['dateEnd']) {
if ($needAnd) {
echo ' and published ';
}
else {
echo 'videos published ';
}
if ($filter['dateStart'] && $filter['dateEnd']) {
echo 'between ';
echo '<span class="filterValue">'.$filter['dateStart'].'</span> and ';
echo '<span class="filterValue">'.$filter['dateEnd'].'</span>';
}
elseif ($filter['dateStart']) {
echo 'on or after ';
echo '<span class="filterValue">'.$filter['dateStart'].'</span>';
}
elseif ($filter['dateEnd']) {
echo 'on or before ';
echo '<span class="filterValue">'.$filter['dateEnd'].'</span>';
}
}
echo ".</p>\n";
}
}
elseif ($settings['output'] == 'xml') {
header("Content-type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
echo '<ytca>'."\n";
addMetaTags('xml',$settings,$filter);
}
elseif ($settings['output'] == 'json') {
header('Content-Type: application/json');
echo '{'."\n";
echo '"ytca": {'."\n";
addMetaTags('json',$settings,$filter);
}
}
function showSummaryTableTop($settings,$numChannels,$firstChannelName,$channelMeta,$filter) {
// $metaData is an array of 'keys' and 'values' for each channel; or false
// returns an array $footnotes
$numFootnotes = 0;
if ($settings['output'] == 'html') {
echo '<table id="report" class="summary">'."\n";
echo '<thead>'."\n";
echo '<tr';
// add a data-status attribute that's used by ytca.js to populate the status message at the top of the page
// this reflects the *next* channel, since it isn't written to the screen until the channel row is complete
if ($firstChannelName) {
echo ' data-status="Processing Channel 1 of '.$numChannels.': '.$firstChannelName.'..."';
}
echo '>'."\n";
echo '<th scope="col"><span>YouTube Channel</span></th>'."\n";
if ($settings['showChannelId']) {
echo '<th scope="col"><span>YouTube ID</span></th>'."\n";
}
if ($channelMeta) {
$metaKeys = array_keys($channelMeta[0]); // get keys from first channel in array
$numMeta = sizeof($metaKeys);
// there is supplemental meta data
// display a column header for each metaData key
$i = 0;
while ($i < $numMeta) {
echo '<th scope="col"><span>'.$metaKeys[$i]."</span></th>\n";
$i++;
}
}
if ($settings['debug'] > 0) {
echo '<th scope="col"><span># API Requests</span></th>'."\n";
echo '<th scope="col"><span>API Cost (units)</span></th>'."\n";
// The next item has a footnote
$numFootnotes++;
$footnotes[$numFootnotes] = getFootNote('approxTotal');
echo '<th scope="col"><span>Approx # Videos<sup>'.$numFootnotes.'</sup></span></th>'."\n";
}
echo '<th scope="col"><span># Videos</span></th>'."\n";
echo '<th scope="col"><span># Captioned</span></th>'."\n";
echo '<th scope="col"><span>% Captioned</span></th>'."\n";
echo '<th scope="col"><span># '.ucfirst($settings['timeUnit'])."</span></th>\n";
echo '<th scope="col"><span># '.ucfirst($settings['timeUnit']).' Captioned</span></th>'."\n";
echo '<th scope="col"><span>Mean Views per Video</span></th>'."\n";
echo '<th scope="col"><span>Max Views</span></th>'."\n";
if (!$filter) {
// no reason to separate out high traffic videos if already filtering for high traffic
// The next several items share a footnote
$numFootnotes++;
$footnotes[$numFootnotes] = getFootNote('highTraffic');
$highTrafficHeaders[] = '# Videos High Traffic';
$highTrafficHeaders[] = '# Captioned High Traffic';
$highTrafficHeaders[] = '% Captioned High Traffic';
$highTrafficHeaders[] = '# '.ucfirst($settings['timeUnit']).' High Traffic';
$highTrafficHeaders[] = '# '.ucfirst($settings['timeUnit']).' Captioned High Traffic';
$numHighTrafficHeaders = sizeof($highTrafficHeaders);
$i=0;
while ($i < $numHighTrafficHeaders) {
echo '<th scope="col"><span>'.$highTrafficHeaders[$i];
echo '<sup>'.$numFootnotes.'</sup></span></th>'."\n";
$i++;
}
}
echo "</tr>\n";
echo '</thead>'."\n";
echo '<tbody>'."\n";
}
elseif ($settings['output'] == 'xml') {
echo '<channels>'."\n";
}
elseif ($settings['output'] == 'json') {
// no output generated here - see showSummaryTableRow()
}
// write output immediatley to screen
ob_flush();
flush();
return $footnotes;
}
function addMetaTags($output,$settings,$filter) {
if ($output == 'xml') {
echo '<meta>'."\n";
echo '<report>'.$settings['report']."</report>\n";
echo '<title>'.$settings['title']."</title>\n";
echo '<time_unit>'.$settings['timeUnit']."</time_unit>\n";
echo '<filter_type>'.$filter['type']."</filter_type>\n";
echo '<filter_value>'.$filter['value']."</filter_value>\n";
echo '<date>'.date('Y-m-d')."</date>\n";
echo "</meta>\n";
}
elseif ($output == 'json') {
echo '"meta":'."\n";
echo "{\n";
echo '"report": "'.$settings['report'].'",'."\n";
echo '"title": "'.$settings['title'].'",'."\n";
echo '"time_unit": "'.$settings['timeUnit'].'",'."\n";
if ($filter['type']) {
echo '"filter_type": "'.$filter['type'].'",'."\n";
}
else {
echo '"filter_type": null,'."\n";
}
if ($filter['value']) {
echo '"filter_value": "'.$filter['value'].'",'."\n";
}
else {
echo '"filter_value": null,'."\n";
}
echo '"date": "'.date('Y-m-d').'"'."\n";
echo "},\n";
}
}
function showSummaryTableRow($settings,$rowNum,$numChannels,$channel=NULL,$nextChannelName=NULL,$metaData=NULL,$channelData,$filter,$highlights=NULL) {
// $rowNum is either an integer, or 'totals'
// $channel, $metaData, and $channelData are all arrays
$numMeta = sizeof($metaData);
// calculate percentages and averages
$pctCaptioned = round($channelData['cc']['count']/$channelData['all']['count'] * 100,1);
if (!$filter) {
// high traffic data is only included for non-filtered channels
$pctCaptionedHighTraffic = round($channelData['ccHighTraffic']['count']/$channelData['highTraffic']['count'] * 100,1);
}
// start of row
if ($settings['output'] == 'html') {
echo '<tr ';
// add a data-status attribute that's used by ytca.js to populate the status message at the top of the page
// this reflects the *next* channel, since it isn't written to the screen until the channel row is complete
if ($nextChannelName) {
$nextRow = $rowNum + 1;
echo ' data-status="Processing Channel '.$nextRow.' of '.$numChannels.': '.$nextChannelName.'..."';
}
elseif ($rowNum == 'totals') {
echo ' data-status="Analysis complete."';
}
if ($rowNum == 'totals') {
echo ' class="totals" data-numMeta="'.$numMeta.'" >'."\n";
// calculate colspan for Totals row header
// always span ID and Name columns
if ($settings['showChannelId']) { // span that too, plus all metadata columns
$colSpan = $numMeta + 2;
}
else { // span all metadata columns
$colSpan = $numMeta + 1;
}
echo '<th scope="row" colspan="'.$colSpan.'">TOTALS</th>'."\n";
}
else {
$channelTitle = NULL;
if ($highlights['use']) {
if ($pctCaptioned >= $highlights['goodPct']) {
$classes[] = 'goodChannel';
$channelTitle = ' title="'.$highlights['goodLabel'].'"';
}
elseif ($pctCaptioned <= $highlights['badPct']) {
$classes[] = 'badChannel';
$channelTitle = ' title="'.$highlights['badLabel'].'"';
}
}
if ($numMeta) {
// add a class for each metadata value
foreach ($metaData as $key => $value) {
$classes[] = 'meta_'.$value;
}
}
if (is_array($classes) && sizeof($classes) > 0) {
echo ' class="';
$i=0;
while ($i < sizeof($classes)) {
if ($i > 0) {
echo ' ';
}
echo $classes[$i];
$i++;
}
echo '"';
}
echo ">\n";
}
}
elseif ($settings['output'] == 'xml' && $rowNum !== 'totals') {
echo '<channel>'."\n";
}
elseif ($settings['output'] == 'json' && $rowNum !== 'totals') {
echo "{\n";
}
// channel name (optionally linked to YouTube channel)
if ($rowNum !== 'totals') {
if ($settings['output'] == 'html') {
echo '<th scope="row">';
echo '<a href="https://www.youtube.com/channel/'.$channel['id'].'">';
echo $channel['name'];
echo '</a>';
echo "</th>\n";
}
elseif ($settings['output'] == 'xml') {
echo '<name>'.$channel['name']."</name>\n";
}
elseif ($settings['output'] == 'json') {
echo '"name": "'.$channel['name'].'",'."\n";
}
}
// channelId
if ($rowNum !== 'totals') {
if ($settings['showChannelId']) {
if ($settings['output'] == 'html') {
echo '<td>'.$channel['id']."</td>\n";
}
elseif ($settings['output'] == 'xml') {
echo '<channelId>'.$channel['id']."</channelId>\n";
}
elseif ($settings['output'] == 'json') {
echo '"channelId": "'.$channel['id'].'",'."\n";
}
}
}
// Display supplemental meta data, if any exists
if ($rowNum !== 'totals') {
if ($metaData) {
foreach ($metaData as $key => $value) {
if ($settings['output'] == 'html') {
echo '<td>'.$value."</td>\n";
}
elseif ($settings['output'] == 'xml') {
echo '<'.$key.'>'.$value.'</'.$key.'>'."\n";
}
elseif ($settings['output'] == 'json') {
echo '"'.$key.'": "'.$value.'",'."\n";
}
}
}
}
// Display data
if ($settings['output'] == 'html') {
if ($settings['debug'] > 0) {
echo '<td class="data">'.number_format($channelData['all']['requests'])."</td>\n";
echo '<td class="data">'.number_format($channelData['all']['cost'])."</td>\n";
echo '<td class="data">'.number_format($channelData['all']['approxCount'])."</td>\n";
}
echo '<td class="data">'.number_format($channelData['all']['count'])."</td>\n";
echo '<td class="data">'.number_format($channelData['cc']['count'])."</td>\n";
echo '<td class="data">'.number_format($pctCaptioned,1)."%</td>\n";
echo '<td class="data">'.formatDuration($channelData['all']['duration'],$settings['timeUnit'])."</td>\n";
echo '<td class="data">'.formatDuration($channelData['cc']['duration'],$settings['timeUnit'])."</td>\n";
if ($rowNum == 'totals') {
echo '<td class="data">--</td>'."\n";
}
else {
echo '<td class="data">'.number_format($channelData['all']['avgViews'])."</td>\n";
}
echo '<td class="data">'.number_format($channelData['all']['maxViews'])."</td>\n";
if (!$filter) {
// high traffic data is only included for non-filtered channels
echo '<td class="data">'.number_format($channelData['highTraffic']['count'])."</td>\n";
echo '<td class="data">'.number_format($channelData['ccHighTraffic']['count'])."</td>\n";
echo '<td class="data">'.number_format($pctCaptionedHighTraffic,1)."%</td>\n";
echo '<td class="data">'.formatDuration($channelData['highTraffic']['duration'],$settings['timeUnit'])."</td>\n";
echo '<td class="data">'.formatDuration($channelData['ccHighTraffic']['duration'],$settings['timeUnit'])."</td>\n";
}
}
elseif ($settings['output'] == 'xml') {
if ($rowNum !== 'totals') { // no totals in xml output
if ($settings['debug'] > 0) {
echo '<num_api_requests>'.number_format($channelData['all']['requests'])."</num_api_requests>\n";
echo '<api_cost>'.number_format($channelData['all']['cost'])."</api_cost>\n";
echo '<num_videos_est>'.number_format($channelData['all']['approxCount'])."</num_videos_est>\n";
}
echo '<num_videos>'.number_format($channelData['all']['count'])."</num_videos>\n";
echo '<num_captioned>'.number_format($channelData['cc']['count'])."</num_captioned>\n";
echo '<pct_captioned>'.number_format($pctCaptioned,1)."</pct_captioned>\n";
// num_seconds (or num_minutes or num_hours, depending on value of timeUnit)
echo '<num_'.strtolower($settings['timeUnit']).'>';
echo formatDuration($channelData['all']['duration'],$settings['timeUnit']);
echo '</num_'.strtolower($settings['timeUnit']).">\n";
// num_seconds_captioned (or comparable element name for minutes or hours, depending on value of timeUnit)
echo '<num_'.strtolower($settings['timeUnit']).'_captioned>';
echo formatDuration($channelData['cc']['duration'],$settings['timeUnit']);
echo '</num_'.strtolower($settings['timeUnit'])."_captioned>\n";
echo '<avg_views>'.number_format($channelData['all']['avgViews'])."</avg_views>\n";
echo '<max_views>'.number_format($channelData['all']['maxViews'])."</max_views>\n";
if (!$filter) {
// high traffic data is only included for non-filtered channels
echo '<num_high_traffic>'.number_format($channelData['highTraffic']['count'])."</num_high_traffic>\n";
echo '<num_captioned_high_traffic>'.number_format($channelData['ccHighTraffic']['count'])."</num_captioned_high_traffic>\n";
echo '<pct_captioned_high_traffic>'.number_format($pctCaptionedHighTraffic,1)."%</pct_captioned_high_traffic>\n";
// num_seconds_high_traffic (or comparable element name for minutes or hours, depending on value of timeUnit)
echo '<num_'.strtolower($settings['timeUnit']).'_high_traffic>';
echo formatDuration($channelData['highTraffic']['duration'],$settings['timeUnit']);
echo '</num_'.strtolower($settings['timeUnit'])."_high_traffic>\n";
// num_seconds_captioned_high_traffic (or comparable element name for minutes or hours, depending on value of timeUnit)
echo '<num_'.strtolower($settings['timeUnit']).'_captioned_high_traffic>';
echo formatDuration($channelData['ccHighTraffic']['duration'],$settings['timeUnit']);
echo '</num_'.strtolower($settings['timeUnit'])."_captioned_high_traffic>\n";
}
}
}
elseif ($settings['output'] == 'json') {
if ($rowNum !== 'totals') { // no totals in json output
if ($settings['debug'] > 0) {
echo '"num_api_requests": "'.number_format($channelData['all']['requests']).'",'."\n";
echo '"api_cost": "'.number_format($channelData['all']['cost']).'",'."\n";
echo '"num_videos_est": "'.number_format($channelData['all']['approxCount']).'",'."\n";
}
echo '"num_videos": "'.number_format($channelData['all']['count']).'",'."\n";
echo '"num_captioned": "'.number_format($channelData['cc']['count']).'",'."\n";
echo '"pct_captioned": "'.number_format($pctCaptioned,1).'",'."\n";
// num_seconds (or num_minutes or num_hours, depending on value of timeUnit)
echo '"num_'.strtolower($settings['timeUnit']).'": "';
echo formatDuration($channelData['all']['duration'],$settings['timeUnit']).'",'."\n";
// num_seconds_captioned (or comparable element name for minutes or hours, depending on value of timeUnit)
echo '"num_'.strtolower($settings['timeUnit']).'_captioned": "';
echo formatDuration($channelData['cc']['duration'],$settings['timeUnit']).'",'."\n";
echo '"avg_views": "'.number_format($channelData['all']['avgViews']).'",'."\n";
if ($filter) {
// max_views is the last element (no comma)
echo '"max_views": "'.number_format($channelData['all']['maxViews']).'"'."\n";
}
else {
echo '"max_views": "'.number_format($channelData['all']['maxViews']).'",'."\n";
// high traffic data is only included for non-filtered channels
echo '"num_high_traffic": "'.number_format($channelData['highTraffic']['count']).'",'."\n";
echo '"num_captioned_high_traffic": "'.number_format($channelData['ccHighTraffic']['count']).'",'."\n";
echo '"pct_captioned_high_traffic": "'.number_format($pctCaptionedHighTraffic,1).'%",'."\n";
// num_seconds_high_traffic (or comparable element name for minutes or hours, depending on value of timeUnit)
echo '"num_'.strtolower($settings['timeUnit']).'_high_traffic": "';
echo formatDuration($channelData['highTraffic']['duration'],$settings['timeUnit']).'",'."\n";
// num_seconds_captioned_high_traffic (or comparable element name for minutes or hours, depending on value of timeUnit)
echo '"num_'.strtolower($settings['timeUnit']).'_captioned_high_traffic": "';
echo formatDuration($channelData['ccHighTraffic']['duration'],$settings['timeUnit']).'"'."\n";
}
}
}
// end of row
if ($settings['output'] == 'html') {
echo "</tr>\n";
}
elseif ($settings['output'] == 'xml' && $rowNum !== 'totals') {
echo "</channel>\n";
}
elseif ($settings['output'] == 'json' && $rowNum !== 'totals') {
if ($rowNum == $numChannels) { // this is the last channel; no comma
echo "}\n";
}
else {
echo "},\n";
}
}
// write output immediately to screen
ob_flush();
flush();
}
function showSummaryTableBottom($output,$footnotes=NULL) {
if ($output == 'html') {
echo "</tbody>\n";
echo "</table>\n";
if ($footnotes) {
$numFootnotes = sizeof($footnotes);
if ($numFootnotes > 0) {
$i = 1;
while ($i <= $numFootnotes) {
echo '<p class="footnote">';
echo '<sup>'.$i.'</sup> ';
echo $footnotes[$i];
echo "</p>\n";
$i++;
}
}
}
}
elseif ($output == 'xml') {
echo "</channels>\n";
}
elseif ($output == 'json') {
echo "]\n"; // end "channels"
}
}
function showBottom($output) {
if ($output == 'html'){
echo "</body>\n";
echo "</html>";
}
elseif ($output == 'xml') {
echo '</ytca>';
}
elseif ($output == 'json') {
echo "}\n"; // end "ytca"
echo "}"; // end json
}
}
function showDetails($settings,$rowNum,$numChannels,$channel,$channelMeta,$channelData,$videos,$numVideos,$filter,$sortBy) {
// $channel is an array that includes 'id', 'name', plus 'videos' (an array of *unfiltered* videos)
// $channelMeta is an array of metadata fields and their values for this channel
// $channelData is an array of statistical summary data for this channel
// $videos is an array of *filtered* videos (if filters are used, this is a subset of $channel['videos'])
$numMeta = sizeof($channelMeta);
// calculate percentages
$pctCaptioned = round($channelData['cc']['count']/$channelData['all']['count'] * 100,1);
if ($settings['output'] == 'html') {
echo '<h2>Channel '.$rowNum.' of '.$numChannels.': '.$channel['name']."</h2>\n";
// show a list of summary data
echo '<ul class="channelDetails">'."\n";
// link to YouTube channel
if ($settings['showChannelId']) {
$channelLink = 'https://www.youtube.com/channel/'.$channel['id'];
echo '<li><a href="'.$channelLink.'">'.$channelLink.'</a></li>'."\n";
}
// channel meta data
if ($numMeta) {
foreach ($channelMeta as $key => $value) {
echo '<li>'.$key.': <span class="value">'.$value."</span></li>\n";
}
}
if ($settings['debug'] > 0) {
echo '<li>Number of API requests: <span class="value">';
echo number_format($channelData['all']['requests'])."</span></li>\n";
echo '<li>API cost (units): <span class="value">';
echo number_format($channelData['all']['cost'])."</span></li>\n";
echo '<li>Number of videos (estimated): <span class="value">';
echo number_format($channelData['all']['approxCount'])."</span></li>\n";
}
// Number of videos
if ($filter) {
// if videos are filtered, show count for both filtered and unfiltered
echo '<li>Number of videos (unfiltered): ';
echo '<span class="value">'.number_format(sizeof($channel['videos'])-2).'</span></li>'."\n";
// and filtered
echo '<li>Number of videos (filtered): ';
echo '<span class="value">'.number_format($channelData['all']['count']).'</span></li>'."\n";
}
else {
// no filter? Show count for all videos
echo '<li>Number of videos: ';
echo '<span class="value">'.number_format($channelData['all']['count']).'</span></li>'."\n";
}
// Number / percent captioned
echo '<li>Number captioned: <span class="value">';
echo number_format($channelData['cc']['count']).'</span> ';
echo '(<span class="value">'.number_format($pctCaptioned,1).'%</span>)</li>'."\n";
// Duration
echo '<li>Total '.$settings['timeUnit'].': <span class="value">';
echo formatDuration($channelData['all']['duration'],$settings['timeUnit']).'</span></li>'."\n";
// Duration (captioned)
echo '<li>'.ucfirst($settings['timeUnit']).' captioned: <span class="value">';
echo formatDuration($channelData['cc']['duration'],$settings['timeUnit'])."</span></td>\n";
// Avg views:
echo '<li>Average views: <span class="value">'.number_format($channelData['all']['avgViews'])."</span></li>\n";
if (!$filter) {
// high traffic data is only included for non-filtered channels
$pctCaptionedHighTraffic = round($channelData['ccHighTraffic']['count']/$channelData['highTraffic']['count'] * 100,1);
echo '<li>Number of high traffic videos: <span class="value">';
echo number_format($channelData['highTraffic']['count'])."</span></li>\n";
echo '<li>Number captioned (high traffic): <span class="value">';
echo number_format($channelData['ccHighTraffic']['count']).'</span> ';
echo '(<span class="value">'.number_format($pctCaptionedHighTraffic,1)."%</span>)</li>\n";
echo '<li>'.ucfirst($settings['timeUnit']).' captioned (high traffic): <span class="value">';
echo formatDuration($channelData['ccHighTraffic']['duration'],$settings['timeUnit'])."</span></li>\n";
}
echo "</ul>\n";
ob_flush();
flush();
}
elseif ($settings['output'] == 'xml') {
echo '<channel>'."\n";