PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/google-analytics-dashboard/ga-lib.php

https://bitbucket.org/nathancorbier/wastark.com
PHP | 400 lines | 311 code | 73 blank | 16 comment | 32 complexity | 5713ed3358848d634bc024cd49cc49e9 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /* Copyright 2009 Carson McDonald (carson@ioncannon.net)
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. */
  15. require_once(dirname(__FILE__) . '/OAuth.php');
  16. require_once(dirname(__FILE__) . '/simplefilecache.php');
  17. class GALib
  18. {
  19. var $auth_type;
  20. var $oauth_token;
  21. var $oauth_secret;
  22. var $auth;
  23. var $ids;
  24. var $base_url = 'https://www.googleapis.com/analytics/v2.4/';
  25. var $account_base_url = 'https://www.googleapis.com/analytics/v2.4/management/';
  26. var $http_code;
  27. var $error_message;
  28. var $cache_timeout;
  29. function GALib($auth_type, $auth, $oauth_token, $oauth_secret, $ids = '', $cache_timeout = 60)
  30. {
  31. $this->auth_type = $auth_type;
  32. $this->auth = $auth;
  33. $this->oauth_token = $oauth_token;
  34. $this->oauth_secret = $oauth_secret;
  35. $this->ids = $ids;
  36. $this->cache_timeout = $cache_timeout;
  37. }
  38. function setAuth($auth)
  39. {
  40. $this->auth = $auth;
  41. }
  42. function isError()
  43. {
  44. return $this->http_code != 200;
  45. }
  46. function isAuthError()
  47. {
  48. return $this->http_code == 401;
  49. }
  50. function isProfileAccessError()
  51. {
  52. return $this->http_code == 403;
  53. }
  54. function isRequestError()
  55. {
  56. return $this->http_code == 400;
  57. }
  58. function getErrorMessage()
  59. {
  60. return $this->error_message;
  61. }
  62. function createAuthHeader($url = null, $request_type = null)
  63. {
  64. if($this->auth_type == 'client')
  65. {
  66. return "Authorization: GoogleLogin auth=" . $this->auth;
  67. }
  68. else
  69. {
  70. if($url == NULL)
  71. {
  72. error_log('No URL to sign.');
  73. }
  74. $signature_method = new GADOAuthSignatureMethod_HMAC_SHA1();
  75. $params = array();
  76. $consumer = new GADOAuthConsumer('anonymous', 'anonymous', NULL);
  77. $token = new GADOAuthConsumer($this->oauth_token, $this->oauth_secret);
  78. $oauth_req = GADOAuthRequest::from_consumer_and_token($consumer, $token, $request_type, $url, $params);
  79. $oauth_req->sign_request($signature_method, $consumer, $token);
  80. return $oauth_req->to_header();
  81. }
  82. }
  83. function account_query()
  84. {
  85. $ch = curl_init();
  86. curl_setopt($ch, CURLOPT_URL, $this->account_base_url . 'accounts/~all/webproperties/~all/profiles');
  87. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  88. curl_setopt($ch, CURLOPT_HTTPHEADER, array($this->createAuthHeader($this->account_base_url . 'accounts/~all/webproperties/~all/profiles', 'GET')));
  89. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  90. $return = curl_exec($ch);
  91. if(curl_errno($ch))
  92. {
  93. $this->error_message = curl_error($ch);
  94. return false;
  95. }
  96. $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  97. if($this->http_code != 200)
  98. {
  99. $this->error_message = $return;
  100. return false;
  101. }
  102. else
  103. {
  104. $this->error_message = '';
  105. $xml = new SimpleXMLElement($return);
  106. curl_close($ch);
  107. $vhash = array();
  108. foreach($xml->entry as $entry)
  109. {
  110. $value = (string)$entry->id;
  111. list($part1, $part2) = split('profiles/', $value);
  112. $vhash['ga:' . $part2] = (string)$entry->title;
  113. }
  114. return $vhash;
  115. }
  116. }
  117. function simple_report_query($start_date, $end_date, $dimensions = '', $metrics = '', $sort = '', $filters = '')
  118. {
  119. $url = $this->base_url . 'data';
  120. $url .= '?ids=' . $this->ids;
  121. $url .= $dimensions != '' ? ('&dimensions=' . $dimensions) : '';
  122. $url .= $metrics != '' ? ('&metrics=' . $metrics) : '';
  123. $url .= $sort != '' ? ('&sort=' . $sort) : '';
  124. $url .= $filters != '' ? ('&filters=' . urlencode($filters)) : '';
  125. $url .= '&start-date=' . $start_date;
  126. $url .= '&end-date=' . $end_date;
  127. if(!SimpleFileCache::isExpired($url, $this->cache_timeout))
  128. {
  129. $this->http_code = 200; // We never cache bad requests
  130. return SimpleFileCache::cacheGet($url);
  131. }
  132. else
  133. {
  134. $ch = curl_init();
  135. curl_setopt($ch, CURLOPT_URL, $url);
  136. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  137. curl_setopt($ch, CURLOPT_HTTPHEADER, array($this->createAuthHeader($url, 'GET')));
  138. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  139. $return = curl_exec($ch);
  140. if(curl_errno($ch))
  141. {
  142. $this->error_message = curl_error($ch);
  143. return false;
  144. }
  145. $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  146. if($this->http_code != 200)
  147. {
  148. $this->error_message = $return;
  149. return false;
  150. }
  151. else
  152. {
  153. $xml = simplexml_load_string($return);
  154. curl_close($ch);
  155. $return_values = array();
  156. foreach($xml->entry as $entry)
  157. {
  158. if($dimensions == '')
  159. {
  160. $dim_name = 'value';
  161. }
  162. else
  163. {
  164. $dimension = $entry->xpath('dxp:dimension');
  165. $dimension_attributes = $dimension[0]->attributes();
  166. $dim_name = (string)$dimension_attributes['value'];
  167. }
  168. $metric = $entry->xpath('dxp:metric');
  169. if(sizeof($metric) > 1)
  170. {
  171. foreach($metric as $single_metric)
  172. {
  173. $metric_attributes = $single_metric->attributes();
  174. $return_values[$dim_name][(string)$metric_attributes['name']] = (string)$metric_attributes['value'];
  175. }
  176. }
  177. else
  178. {
  179. $metric_attributes = $metric[0]->attributes();
  180. $return_values[$dim_name] = (string)$metric_attributes['value'];
  181. }
  182. }
  183. SimpleFileCache::cachePut($url, $return_values, $this->cache_timeout);
  184. return $return_values;
  185. }
  186. }
  187. }
  188. function complex_report_query($start_date, $end_date, $dimensions = array(), $metrics = array(), $sort = array(), $filters = array())
  189. {
  190. $url = $this->base_url . 'data';
  191. $url .= '?ids=' . $this->ids;
  192. $url .= sizeof($dimensions) > 0 ? ('&dimensions=' . join(array_reverse($dimensions), ',')) : '';
  193. $url .= sizeof($metrics) > 0 ? ('&metrics=' . join($metrics, ',')) : '';
  194. $url .= sizeof($sort) > 0 ? '&sort=' . join($sort, ',') : '';
  195. $url .= sizeof($filters) > 0 ? '&filters=' . urlencode(join($filters, ',')) : '';
  196. $url .= '&start-date=' . $start_date;
  197. $url .= '&end-date=' .$end_date;
  198. if(!SimpleFileCache::isExpired($url, $this->cache_timeout))
  199. {
  200. $this->http_code = 200; // We never cache bad requests
  201. return SimpleFileCache::cacheGet($url);
  202. }
  203. else
  204. {
  205. $ch = curl_init();
  206. curl_setopt($ch, CURLOPT_URL, $url);
  207. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  208. curl_setopt($ch, CURLOPT_HTTPHEADER, array($this->createAuthHeader($url, 'GET')));
  209. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  210. $return = curl_exec($ch);
  211. if(curl_errno($ch))
  212. {
  213. $this->error_message = curl_error($ch);
  214. return false;
  215. }
  216. $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  217. if($this->http_code != 200)
  218. {
  219. $this->error_message = $return;
  220. return false;
  221. }
  222. else
  223. {
  224. $xml = simplexml_load_string($return);
  225. curl_close($ch);
  226. $return_values = array();
  227. foreach($xml->entry as $entry)
  228. {
  229. $metrics = array();
  230. foreach($entry->xpath('dxp:metric') as $metric)
  231. {
  232. $metric_attributes = $metric->attributes();
  233. $metrics[(string)$metric_attributes['name']] = (string)$metric_attributes['value'];
  234. }
  235. $last_dimension_var_name = null;
  236. foreach($entry->xpath('dxp:dimension') as $dimension)
  237. {
  238. $dimension_attributes = $dimension->attributes();
  239. $dimension_var_name = 'dimensions_' . strtr((string)$dimension_attributes['name'], ':', '_');
  240. $$dimension_var_name = array();
  241. if($last_dimension_var_name == null)
  242. {
  243. $$dimension_var_name = array('name' => (string)$dimension_attributes['name'],
  244. 'value' => (string)$dimension_attributes['value'],
  245. 'children' => $metrics);
  246. }
  247. else
  248. {
  249. $$dimension_var_name = array('name' => (string)$dimension_attributes['name'],
  250. 'value' => (string)$dimension_attributes['value'],
  251. 'children' => $$last_dimension_var_name);
  252. }
  253. $last_dimension_var_name = $dimension_var_name;
  254. }
  255. array_push($return_values, $$last_dimension_var_name);
  256. }
  257. SimpleFileCache::cachePut($url, $return_values, $this->cache_timeout);
  258. return $return_values;
  259. }
  260. }
  261. }
  262. function hour_pageviews_for_date_period($start_date, $end_date)
  263. {
  264. return $this->simple_report_query($start_date, $end_date, 'ga:hour', 'ga:visits');
  265. }
  266. function daily_pageviews_for_date_period($start_date, $end_date)
  267. {
  268. return $this->simple_report_query($start_date, $end_date, 'ga:date', 'ga:pageviews');
  269. }
  270. function weekly_pageviews_for_date_period($start_date, $end_date)
  271. {
  272. return $this->simple_report_query($start_date, $end_date, 'ga:week', 'ga:pageviews');
  273. }
  274. function monthly_pageviews_for_date_period($start_date, $end_date)
  275. {
  276. return $this->simple_report_query($start_date, $end_date, 'ga:month', 'ga:pageviews');
  277. }
  278. function total_visits_for_date_period($start_date, $end_date)
  279. {
  280. return $this->simple_report_query($start_date, $end_date, '', 'ga:visits');
  281. }
  282. function daily_uri_pageviews_for_date_period($partial_uri, $start_date, $end_date)
  283. {
  284. return $this->simple_report_query($start_date, $end_date, 'ga:date', 'ga:pageviews', '', 'ga:pagePath=~' . $partial_uri . '.*');
  285. }
  286. function total_uri_pageviews_for_date_period($partial_uri, $start_date, $end_date)
  287. {
  288. return $this->simple_report_query($start_date, $end_date, '', 'ga:pageviews', '', 'ga:pagePath=~' . $partial_uri . '.*');
  289. }
  290. function total_pageviews_for_date_period($start_date, $end_date)
  291. {
  292. return $this->simple_report_query($start_date, $end_date, '', 'ga:pageviews');
  293. }
  294. function keywords_for_date_period($start_date, $end_date, $limit = 20)
  295. {
  296. return $this->simple_report_query($start_date, $end_date, 'ga:keyword', 'ga:visits', '-ga:visits', 'ga:visits>' . $limit);
  297. }
  298. function sources_for_date_period($start_date, $end_date, $limit = 20)
  299. {
  300. return $this->simple_report_query($start_date, $end_date, 'ga:source', 'ga:visits', '-ga:visits', 'ga:visits>' . $limit);
  301. }
  302. function pages_for_date_period($start_date, $end_date, $limit = 20)
  303. {
  304. return $this->complex_report_query($start_date, $end_date, array('ga:pagePath', 'ga:pageTitle'), array('ga:pageviews'), array('-ga:pageviews'), array('ga:pageviews>' . $limit));
  305. }
  306. function summary_by_partial_uri_for_date_period($partial_uri, $start_date, $end_date)
  307. {
  308. return $this->simple_report_query($start_date, $end_date, 'ga:date', join(array('ga:pageviews', 'ga:exits', 'ga:uniquePageviews'), ','), 'ga:date', 'ga:pagePath=~' . $partial_uri . '.*');
  309. }
  310. function summary_for_date_period($start_date, $end_date)
  311. {
  312. return $this->simple_report_query($start_date, $end_date, '', join(array('ga:visits', 'ga:bounces', 'ga:entrances', 'ga:timeOnSite', 'ga:newVisits'), ','));
  313. }
  314. function goals_for_date_period($start_date, $end_date, $enabled_goals)
  315. {
  316. $goals = array();
  317. if($enabled_goals[0]) array_push($goals, 'ga:goal1Completions');
  318. if($enabled_goals[1]) array_push($goals, 'ga:goal2Completions');
  319. if($enabled_goals[2]) array_push($goals, 'ga:goal3Completions');
  320. if($enabled_goals[3]) array_push($goals, 'ga:goal4Completions');
  321. return $this->simple_report_query($start_date, $end_date, 'ga:date', join($goals, ','));
  322. }
  323. }
  324. ?>