-
Notifications
You must be signed in to change notification settings - Fork 1
/
oer_analytics.module
564 lines (466 loc) · 19.7 KB
/
oer_analytics.module
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
<?php
// $Id$
// TODO simplify nonmodifications
/*
* All original work,
* COPYRIGHT 2013
*
* The Regents of the University of Michigan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* any later version.
*
* You may not use the name of The University of Michigan in any
* advertising or publicity pertaining to the use of distribution of this software
* without specific, written prior authorization. If the above copyright notice
* or any other identification of the University of Michigan is included in any
* copy of any portion of this software, then the disclaimer below must
* also be included.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
* FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
* PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
* MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
* REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
* FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
* OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
* IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Form builder. Configure oer_analytics module.
*
* @see system_settings_form()
*/
function oer_analytics_admin() {
$form = array();
$form['oer_analytics_gac_key'] = array(
'#type' => 'textfield',
'#title' => t('YouTube account application key'),
'#size' => 128,
'#maxlength' => 1024,
'#default_value' => variable_get('oer_analytics_gac_key', NULL),
'#description' => t('The secret key your YouTube Data API requires.'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return system_settings_form($form);
}
// hook_menu -- will document properly shortly TODO
function oer_analytics_menu() {
$items = array();
$items['admin/settings/oer-analytics'] = array(
'title' => 'Open.Michigan Analytics module settings',
'description' => 'Description of your analytics settings page',
'page callback' => 'drupal_get_form',
'page arguments' => array('oer_analytics_admin'),
'access arguments' => array('administer oeranalytics settings'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* @file
* Implements functions to grab media analytics for OERbit site
* Displays analytics on appropriate course or resource pages.
*/
/** Helper Functions **/
function today() {
$today = getdate();
$mon = $today["mon"];
$day = $today["mday"];
$yr = $today["year"];
if ($mon < 10) {
$mon = "0".$mon;
}
if ($day < 10) {
$day = "0".$day;
}
$curr_date = $yr."-".$mon."-".$day;
return $curr_date;
}
// implements hook_init(), docs later
function oer_analytics_init(){
define('JQUERY_UPDATE_REPLACE_PATH', 'sites/all/libraries/jquery/1.5.2'); // hmmmm
drupal_add_css(drupal_get_path('module', 'oer_analytics') .'/oer_analytics.css');
drupal_add_js(drupal_get_path('module', 'oer_analytics') .'/oer_analytics.js');
$variables['scripts'] = drupal_get_js();
}
function hook_js_alter(&$javascript) {
// Swap out jQuery to use an updated version of the library.
$javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
}
function oer_analytics_counter_get_searched_path() { // keeping this for now, v useful
$path = check_plain(implode('/', arg()));
return $path;
//return trim(substr($path,1)); // no leading slash; this isn't needed
} // TODO check integration (fine for now)
/* get (correct, aliased) page path from an OERbit node number */
function get_pagepath($nodenum) {
$from_db = db_query("SELECT dst FROM {url_alias} WHERE src LIKE 'node/{$nodenum}'");
while ($paths = db_fetch_object($from_db)) {
$p = $paths->dst;
}
return $p;
} // TODO may need improved error checking -- may not be needed
// $path = explode("gac_get_count", $path);
// $path = $path[1];
// // We have something like /node/264455. Remove the leading slash.
// $path = trim(substr($path, 1));
// $sumarray = google_analytics_counter_get_sum_per_path($path);
function landingpg_path($fullpath) {
$fullpath = str_replace("/materials", "", $fullpath);
$fullpath = str_replace("/highlights", "", $fullpath);
$fullpath = str_replace("/sessions", "", $fullpath);
return $fullpath;
}
// Google Analytics Counter method calls (?)
function get_video_title($videoid) { // NEW
//$api_key = "AIzaSyAv0ljLFFoCpJ0PEsdyJ6ycmqfP6ZOQj6E";
$api_key = variable_get('oer_analytics_gac_key', array()); // excitement?
$baseurl = "https://www.googleapis.com/youtube/v3/videos?id={$videoid}&key={$api_key}&part=snippet";
$JSON_first = drupal_http_request($baseurl);
$JSON = $JSON_first->data;
$json_data = json_decode($JSON);
$title = $json_data->{'items'}[0]->{'snippet'}->{'title'};
return $title;
}
function get_video_data($videoid) { // NEW
//$api_key = "AIzaSyAv0ljLFFoCpJ0PEsdyJ6ycmqfP6ZOQj6E";
$api_key = variable_get('oer_analytics_gac_key', array()); // excitement?
$baseurl = "https://www.googleapis.com/youtube/v3/videos?id={$videoid}&key={$api_key}&part=snippet,statistics";
$JSON_first = drupal_http_request($baseurl);
$JSON = $JSON_first->data;
$json_data = json_decode($JSON);
// after requesting and json parsing and all that
// needs testing, of course
$tmp = $json_data->{'items'}[0]->{'statistics'};
//print $tmp;
$views = (int) $tmp->{'viewCount'};
$likes = (int) $tmp->{'likeCount'};
$dislikes = (int) $tmp->{'dislikeCount'};
$favs = (int) $tmp->{'favoriteCount'};
$comments = (int) $tmp->{'commentCount'};
$title = $json_data->{'items'}[0]->{'snippet'}->{'title'};
//return $title;
return $views; // can easily update to return and then store all other vals
}
/********* HOOK METHODS *********/
/**
* Implements Cron (parallel) via elysia_cron module.
*/
function oer_analytics_cronapi() { // $op and $job = NULL params -- ?? necessary, if so what here?
$items['oer_analytics_cron'] = array(
'description' => 'Perform updates/new population of db tables for oer_analytics module.',
'rule' => '0 2 * * *', // every day at 2am
'callback' => '_oer_analytics_prepcron',
'arguments' => array('all'), // ?
);
return $items;
}
// Would-be implementing hook_cron(); populates and updates database tables for analytics module.
function _oer_analytics_prepcron() {
//function oer_analytics_cron() { // for testingonly
$vid_db_info = db_query('SELECT field_course_reference_nid, field_video_value FROM {content_field_video} INNER JOIN {content_field_course_reference} WHERE content_field_video.vid = content_field_course_reference.vid AND content_field_video.field_video_provider="youtube" ORDER BY field_course_reference_nid');
$all_vids_arr = array();
while ($row = db_fetch_object($vid_db_info)) {
$vid = $row->field_video_value;
$cnid = $row->field_course_reference_nid;
$all_vids_arr[$vid] = array('course_nid' => $cnid, 'already_tracked' => 0);
}
//drupal_set_message('got the list of ALL the videos');
//dvm($all_vids_arr);
// Get the list of the video IDs we currently have numbers for
$currvids = db_query('SELECT videoid FROM {oer_analytics_vids}');
while ($row = db_fetch_object($currvids)) {
$vi = $row->videoid;
if (array_key_exists($vi, $all_vids_arr)) { // May have been deleted
//drupal_set_message("Video ID {$vi} is already being tracked");
$all_vids_arr[$vi]['already_tracked'] = TRUE;
} else {
//drupal_set_message("Video ID {$vi} appears to have been deleted");
}
}
//drupal_set_message('finished processing this list of currently tracked videos');
//dvm($all_vids_arr);
// For each current video, get the view count and write out the
// updated (or new) entry with the view count for that video
foreach($all_vids_arr as $vid_id => $info) {
if (strpos($vid_id, "PLAYLIST") !== FALSE) {
//drupal_set_message("Skipping video with id {$vid_id} (it is a PLAYLIST)");
continue;
}
$data_views = get_video_data($vid_id);
$inp_arr = array('videoid' => $vid_id,
'course_nid' => $info['course_nid'],
'totalviews' => $data_views);
if ($info['already_tracked'] === TRUE) {
//drupal_set_message("oer_analytics_vids already has an entry for videoid {$vid_id}");
drupal_write_record('oer_analytics_vids', $inp_arr, 'videoid');
} else {
//drupal_set_message("creating a new entry in oer_analytics_vids for videoid {$vid_id}");
drupal_write_record('oer_analytics_vids', $inp_arr);
}
}
// Get the list of the courses we currently have numbers for
$curr_courses_arr = array();
$currcourses = db_query('SELECT course_nid from {oer_analytics_youtube}');
while ($row = db_fetch_object($currcourses)) {
$curr_courses_arr[] = $row->course_nid;
}
//drupal_set_message('got the list of ALL the currently tracked courses from oer_analytics_youtube');
//dvm($curr_courses_arr);
// Acccumulate the view count for all the videos for each course
$yt_info = array();
$now_vids = db_query("SELECT course_nid, totalviews FROM {oer_analytics_vids}"); // TODO secure
while ($row = db_fetch_object($now_vids)) {
//$video_id = $row->videoid;
$coursenid = $row->course_nid;
$views = $row->totalviews;
// this one-element non-array is fragile for current setup TODO
if (array_key_exists($coursenid, $yt_info)) {
$yt_info[$coursenid] += (int) $views;
} else {
$yt_info[$coursenid] = (int) $views;
}
}
// Write out the updated (or new) entries with the total view count for each course
foreach($yt_info as $cnid => $yt_viewnum) {
$inp_arr = array('course_nid' => $cnid,
'totalviews' => $yt_viewnum);
if (array_search($cnid, $curr_courses_arr) !== FALSE) {
//drupal_set_message("oer_analytics_youtube already has an entry for course {$cnid}");
drupal_write_record('oer_analytics_youtube', $inp_arr, 'course_nid');
} else {
//drupal_set_message("creating a new entry in oer_analytics_youtube for course {$cnid}");
drupal_write_record('oer_analytics_youtube', $inp_arr);
}
}
// $all_courses = db_query("SELECT nid FROM {content_type_course}");
// $allcourses = array();
// while ($row = db_fetch_object($all_courses)) {
// array_push($allcourses, $row->nid); // this array will hold ALL things of type course in OERbit
// }
// $tracked = array();
// $tracked_courses = db_query("SELECT nid FROM {oer_analytics_courses}");
// while ($row = db_fetch_object($tracked_courses)) {
// array_push($tracked, $row->nid);
// }
// // Saving course views and downloads information in oer_analytics_courses table
// // Still using other module fxns to control for caching/rate limit issues, but will have this info accessible from db
// foreach($allcourses as $course_nid) {
// $path = "http://open.umich.edu/node/${course_nid}";
// $res_one = google_analytics_counter_get_sum_per_path($path);
// $res_dls = google_analytics_counter_get_sum_per_path($path . "/zip_download");
// $courseviews = (int) $res_one[0];
// $dlsviews = (int) $res_dls[0];
// if ($dlsviews >= 10) {
// $inparr = array('nid' => $course_nid, 'totalviews' => $courseviews, 'total_zipdownloads' => $dlsviews);
// } else {
// $inparr = array('nid' => $course_nid, 'totalviews' => $courseviews);
// }
// if (array_search($course_nid,$tracked) !== FALSE) {
// drupal_write_record('oer_analytics_courses', $inparr, 'nid'); // oer_analytics_courses already has a record for course {$course_nid}
// } else {
// drupal_write_record('oer_analytics_courses', $inparr); // create a new entry in oer_analytics_courses for this course
// }
// }
} // end cron block
/**
* Implementation of hook_block().
*/
function oer_analytics_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks['oer-analytics'] = array(
'info' => t('Course Analytics'),
//'cache' => BLOCK_CACHE_PER_PAGE, // remember day cached, for speeding things up
);
return $blocks;
case 'view':
if (arg(0) == 'node' && is_numeric(arg(1))) { // node_load() -- check node type
return _oer_analytics_block(arg(1)); // gets info that will be displayed
}
}
}
function _oer_analytics_block($nid) {
$node = node_load($nid);
if ($node->type == 'course') { // may not be necessary, TODO
$stats = array();
$full_stats = array();
$vidcount = array();
//tmp -- many following queries should be consolidated; TODO
$db_res = db_query('SELECT course_nid, totalviews, totalcomments FROM {oer_analytics_youtube} WHERE course_nid = %d', $nid);
while ($row = db_fetch_object($db_res)) {
//$yt_view = $row->oer_analytics_courses.totalviews;
$yt_views = $row->totalviews;
//$yt_comm = $row->totalcomments;
$stats[$row->course_nid] = array($yt_views);
}
foreach($stats as $num=>$arr) {
array_push($full_stats, number_format($arr[0]));
array_push($full_stats, $num_rows);
}
$path = oer_analytics_counter_get_searched_path();
$path = landingpg_path($path);
$course_path = $path; //landingpg_path($path);
//drupal_set_message("Path is: " . $course_path);
$mat_path = $course_path . "/materials";
$dls_path = $path . "/zip_download";
//drupal_set_message("Downloads path is: " . $dls_path);
$resultarr_one = google_analytics_counter_get_sum_per_path($course_path); // should be like $sumarray
$resultarr_dls = google_analytics_counter_get_sum_per_path($dls_path);
// dpr($resultarr_one);
// dpr($resultarr_dls);
$courseviews = $resultarr_one[0];
//drupal_set_message($courseviews);
$dls_views = $resultarr_dls[0];
//drupal_set_message($dls_views);
if ($dls_views > 10) {
$ga_stats = array(number_format($courseviews), number_format($dls_views));
} else {
$ga_stats = array(number_format($courseviews));
}
// fill in more later
if (!empty($full_stats) && count($ga_stats) == 2) {
//$most_watched_vid_val = most_watched_vid($nid);
return array(
//'subject' => t('Course Analytics'),
//'content' => theme_item_list(array_merge($ga_stats, $full_stats))
'content' => <<<EOD
<div class="oer-analytics-button" id="oer-analytics-button">
<button aria-text="close the analytics display" id="hiddenq"><p id="closebutton">✖</p></button>
<div class="oer-analytics" id="oer-analytics-visits">
<span id="visits-num">
<span id="googleanalytics-oer">
<p class="statsnums" id="visits-num">{$ga_stats[0]}</p>
<p class="oer-analytics-small-descr">views</p>
</span>
<span id="googleanalytics-dls">
<p class="statsnums" id="dls-num">{$ga_stats[1]}</p>
<p class="oer-analytics-small-descr">zip downloads</p>
</span>
</span>
</div>
<div class="oer-analytics" id="oer-analytics-yt-views">
<span id="visits-num">
<span id="yt-analytics">
<p class="statsnums" id="yt-views">{$full_stats[0]}</p>
<p class="oer-analytics-small-descr"><a href="/{$mat_path}">YouTube</a> views</p>
<!-- <p id="mostviewedvid" class="oer-analytics-small-descr">most viewed video:</p>
<p id="mostviewedvid_title" class="oer-analytics-small-descr">${most_watched_vid_val}</p> -->
</span>
</span>
</div>
</div>
<button class="hovershow" id="oer-analytics-buttona" aria-label="click this for usage data on this course or resource" type="button"></button>
EOD
);
} else if (!empty($full_stats) && count($ga_stats) < 2) {
return array(
//'subject' => t('Course Analytics'),
//'content' => theme_item_list(array_merge($ga_stats, $full_stats))
'content' => <<<EOD
<div class="oer-analytics-button" id="oer-analytics-button">
<button aria-text="close the analytics display" id="hiddenq"><p id="closebutton">✖</p></button>
<div class="oer-analytics" id="oer-analytics-visits">
<span id="visits-num">
<span id="googleanalytics-oer">
<p class="statsnums" id="visits-num">{$ga_stats[0]}</p>
<p class="oer-analytics-small-descr">views</p>
</span>
</span>
</div>
<div class="oer-analytics" id="oer-analytics-yt-views">
<span id="visits-num">
<span id="yt-analytics">
<p class="statsnums" id="yt-views">{$full_stats[0]}</p>
<p class="oer-analytics-small-descr"><a href="/{$mat_path}">YouTube</a> views</p>
<!-- <p id="mostviewedvid" class="oer-analytics-small-descr">most viewed video:</p>
<p id="mostviewedvid_title" class="oer-analytics-small-descr">${most_watched_vid_val}</p> -->
</span>
</span>
</div>
</div>
<button class="hovershow" id="oer-analytics-buttona" aria-label="click this for usage data on this course or resource" type="button"></button>
EOD
);
} else if (!empty($ga_stats)) {
if (!is_null($ga_stats[1])) {
return array(
//'subject' => t('Course Analytics'),
//'content' => theme_item_list($ga_stats)
'content' => <<<EOD
<div class="oer-analytics-button" id="oer-analytics-button">
<button aria-text="close the analytics display" id="hiddenq"><p id="closebutton">✖</p></button>
<div class="oer-analytics" id="oer-analytics-visits">
<span id="visits-num">
<span id="googleanalytics-oer">
<p class="statsnums" id="visits-num">{$ga_stats[0]}</p>
<p class="oer-analytics-small-descr">views</p>
</span>
<span id="googleanalytics-dls">
<p class="statsnums" id="dls-num">{$ga_stats[1]}</p>
<p class="oer-analytics-small-descr">zip downloads</p>
</span>
</span>
</div>
</div>
<button class="hovershow" id="oer-analytics-buttona" aria-label="click this for usage data on this course or resource" type="button"></button>
EOD
);
} else if (!empty($full_stats) && empty($ga_stats)) {
return array(
//'subject' => t('Course Analytics'),
//'content' => theme_item_list(array_merge($ga_stats, $full_stats))
'content' => <<<EOD
<div class="oer-analytics-button" id="oer-analytics-button">
<button aria-text="close the analytics display" id="hiddenq"><p id="closebutton">✖</p></button>
<div class="oer-analytics" id="oer-analytics-yt-views">
<span id="visits-num">
<span id="yt-analytics">
<p class="statsnums" id="yt-views">{$full_stats[0]}</p>
<p class="oer-analytics-small-descr"><a href="/{$mat_path}">YouTube</a> views</p>
</span>
</span>
</div>
</div>
<button class="hovershow" id="oer-analytics-buttona" aria-label="click this for usage data on this course or resource" type="button"></button>
EOD
);
} else {
return array(
//'subject' => t('Course Analytics'),
//'content' => theme_item_list($ga_stats)
'content' => <<<EOD
<div class="oer-analytics-button" id="oer-analytics-button">
<button aria-text="close the analytics display" id="hiddenq"><p id="closebutton">✖</p></button>
<div class="oer-analytics" id="oer-analytics-visits">
<span id="visits-num">
<span id="googleanalytics-oer">
<p class="statsnums" id="visits-num">{$ga_stats[0]}</p>
<p class="oer-analytics-small-descr">views</p>
</span>
</span>
</div>
</div>
<button class="hovershow" id="oer-analytics-buttona" aria-label="click this for usage data on this course or resource" type="button"></button>
EOD
);
}
} else {
return;
}
}
}