PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/Referers/Controller.php

https://github.com/quarkness/piwik
PHP | 467 lines | 383 code | 53 blank | 31 comment | 15 complexity | 2b57df5e751731fd0c554d4e5ece4552 MD5 | raw file
  1. <?php
  2. /**
  3. * Piwik - Open source web analytics
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. * @version $Id$
  8. *
  9. * @category Piwik_Plugins
  10. * @package Piwik_Referers
  11. */
  12. /**
  13. *
  14. * @package Piwik_Referers
  15. */
  16. class Piwik_Referers_Controller extends Piwik_Controller
  17. {
  18. function index()
  19. {
  20. $view = Piwik_View::factory('index');
  21. $view->graphEvolutionReferers = $this->getEvolutionGraph(true, Piwik_Common::REFERER_TYPE_DIRECT_ENTRY, array('nb_visits'));
  22. $view->nameGraphEvolutionReferers = 'ReferersgetEvolutionGraph';
  23. $view->numberDistinctSearchEngines = $this->getNumberOfDistinctSearchEngines(true);
  24. $view->numberDistinctKeywords = $this->getNumberOfDistinctKeywords(true);
  25. $view->numberDistinctWebsites = $this->getNumberOfDistinctWebsites(true);
  26. $view->numberDistinctWebsitesUrls = $this->getNumberOfDistinctWebsitesUrls(true);
  27. $view->numberDistinctCampaigns = $this->getNumberOfDistinctCampaigns(true);
  28. // building the referers summary report
  29. $view->dataTableRefererType = $this->getRefererType(true);
  30. $nameValues = $this->getReferersVisitorsByType();
  31. foreach($nameValues as $name => $value)
  32. {
  33. $view->$name = $value;
  34. }
  35. // sparkline for the historical data of the above values
  36. $view->urlSparklineSearchEngines = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_visits'), 'typeReferer' => Piwik_Common::REFERER_TYPE_SEARCH_ENGINE));
  37. $view->urlSparklineDirectEntry = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_visits'), 'typeReferer' => Piwik_Common::REFERER_TYPE_DIRECT_ENTRY));
  38. $view->urlSparklineWebsites = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_visits'), 'typeReferer' => Piwik_Common::REFERER_TYPE_WEBSITE));
  39. $view->urlSparklineCampaigns = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_visits'), 'typeReferer' => Piwik_Common::REFERER_TYPE_CAMPAIGN));
  40. // sparklines for the evolution of the distinct keywords count/websites count/ etc
  41. $view->urlSparklineDistinctSearchEngines = $this->getUrlSparkline('getLastDistinctSearchEnginesGraph');
  42. $view->urlSparklineDistinctKeywords = $this->getUrlSparkline('getLastDistinctKeywordsGraph');
  43. $view->urlSparklineDistinctWebsites = $this->getUrlSparkline('getLastDistinctWebsitesGraph');
  44. $view->urlSparklineDistinctCampaigns = $this->getUrlSparkline('getLastDistinctCampaignsGraph');
  45. echo $view->render();
  46. }
  47. function getSearchEnginesAndKeywords()
  48. {
  49. $view = Piwik_View::factory('searchEngines_Keywords');
  50. $view->searchEngines = $this->getSearchEngines(true) ;
  51. $view->keywords = $this->getKeywords(true);
  52. echo $view->render();
  53. }
  54. function getRefererType( $fetch = false)
  55. {
  56. $view = Piwik_ViewDataTable::factory('tableAllColumns');
  57. $view->init( $this->pluginName,
  58. __FUNCTION__,
  59. 'Referers.getRefererType'
  60. );
  61. $view->disableSearchBox();
  62. $view->disableOffsetInformationAndPaginationControls();
  63. $view->disableExcludeLowPopulation();
  64. $view->enableShowGoals();
  65. $view->setColumnsToDisplay( array('label', 'nb_visits') );
  66. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnRefererType'));
  67. $this->setMetricsVariablesView($view);
  68. return $this->renderView($view, $fetch);
  69. }
  70. function getKeywords( $fetch = false)
  71. {
  72. $view = Piwik_ViewDataTable::factory();
  73. $view->init( $this->pluginName, __FUNCTION__,
  74. 'Referers.getKeywords',
  75. 'getSearchEnginesFromKeywordId'
  76. );
  77. $view->disableExcludeLowPopulation();
  78. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnKeyword'));
  79. $view->enableShowGoals();
  80. $view->disableSubTableWhenShowGoals();
  81. $this->setMetricsVariablesView($view);
  82. return $this->renderView($view, $fetch);
  83. }
  84. function getSearchEnginesFromKeywordId( $fetch = false )
  85. {
  86. $view = Piwik_ViewDataTable::factory();
  87. $view->init( $this->pluginName, __FUNCTION__,
  88. 'Referers.getSearchEnginesFromKeywordId'
  89. );
  90. $view->disableSearchBox();
  91. $view->disableExcludeLowPopulation();
  92. $view->setColumnsToDisplay( array('label','nb_visits') );
  93. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnSearchEngine'));
  94. return $this->renderView($view, $fetch);
  95. }
  96. function getSearchEngines( $fetch = false)
  97. {
  98. $view = Piwik_ViewDataTable::factory();
  99. $view->init( $this->pluginName, __FUNCTION__,
  100. 'Referers.getSearchEngines',
  101. 'getKeywordsFromSearchEngineId'
  102. );
  103. $view->disableSearchBox();
  104. $view->disableExcludeLowPopulation();
  105. $view->enableShowGoals();
  106. $view->disableSubTableWhenShowGoals();
  107. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnSearchEngine'));
  108. $this->setMetricsVariablesView($view);
  109. return $this->renderView($view, $fetch);
  110. }
  111. function getKeywordsFromSearchEngineId( $fetch = false )
  112. {
  113. $view = Piwik_ViewDataTable::factory();
  114. $view->init( $this->pluginName, __FUNCTION__,
  115. 'Referers.getKeywordsFromSearchEngineId'
  116. );
  117. $view->disableSearchBox();
  118. $view->disableExcludeLowPopulation();
  119. $view->setColumnsToDisplay( array('label','nb_visits') );
  120. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnKeyword'));
  121. return $this->renderView($view, $fetch);
  122. }
  123. function indexWebsites($fetch = false)
  124. {
  125. return Piwik_View::singleReport(
  126. Piwik_Translate('Referers_Websites'),
  127. $this->getWebsites(true), $fetch);
  128. }
  129. function getWebsites( $fetch = false)
  130. {
  131. $view = Piwik_ViewDataTable::factory();
  132. $view->init( $this->pluginName, __FUNCTION__,
  133. 'Referers.getWebsites',
  134. 'getUrlsFromWebsiteId'
  135. );
  136. $view->disableExcludeLowPopulation();
  137. $view->setLimit(10);
  138. $view->enableShowGoals();
  139. $view->disableSubTableWhenShowGoals();
  140. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnWebsite'));
  141. $this->setMetricsVariablesView($view);
  142. return $this->renderView($view, $fetch);
  143. }
  144. function indexCampaigns($fetch = false)
  145. {
  146. return Piwik_View::singleReport(
  147. Piwik_Translate('Referers_Campaigns'),
  148. $this->getCampaigns(true), $fetch);
  149. }
  150. function getCampaigns( $fetch = false)
  151. {
  152. $view = Piwik_ViewDataTable::factory();
  153. $view->init( $this->pluginName, __FUNCTION__,
  154. 'Referers.getCampaigns',
  155. 'getKeywordsFromCampaignId'
  156. );
  157. $view->disableExcludeLowPopulation();
  158. $view->enableShowGoals();
  159. $view->setLimit( 10 );
  160. $view->setColumnsToDisplay( array('label','nb_visits') );
  161. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnCampaign'));
  162. $view->setFooterMessage( 'Help: <a target="_blank" href="http://piwik.org/docs/tracking-campaigns/">Tracking Campaigns in Piwik</a> - <a target="_blank" href="http://piwik.org/docs/tracking-campaigns/url-builder/">URL Builder tool</a>');
  163. $this->setMetricsVariablesView($view);
  164. return $this->renderView($view, $fetch);
  165. }
  166. function getKeywordsFromCampaignId( $fetch = false)
  167. {
  168. $view = Piwik_ViewDataTable::factory();
  169. $view->init( $this->pluginName, __FUNCTION__,
  170. 'Referers.getKeywordsFromCampaignId'
  171. );
  172. $view->disableSearchBox();
  173. $view->disableExcludeLowPopulation();
  174. $view->setColumnsToDisplay( array('label','nb_visits') );
  175. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnKeyword'));
  176. return $this->renderView($view, $fetch);
  177. }
  178. function getUrlsFromWebsiteId( $fetch = false)
  179. {
  180. $view = Piwik_ViewDataTable::factory();
  181. $view->init( $this->pluginName, __FUNCTION__,
  182. 'Referers.getUrlsFromWebsiteId'
  183. );
  184. $view->disableSearchBox();
  185. $view->disableExcludeLowPopulation();
  186. $view->setColumnsToDisplay( array('label','nb_visits') );
  187. $view->setColumnTranslation('label', Piwik_Translate('Referers_ColumnWebsitePage'));
  188. return $this->renderView($view, $fetch);
  189. }
  190. protected function getReferersVisitorsByType()
  191. {
  192. // we disable the queued filters because here we want to get the visits coming from search engines
  193. // if the filters were applied we would have to look up for a label looking like "Search Engines"
  194. // which is not good when we have translations
  195. $requestString = "method=Referers.getRefererType
  196. &format=original
  197. &disable_queued_filters=1";
  198. $request = new Piwik_API_Request($requestString);
  199. $dataTableReferersType = $request->process();
  200. $nameToColumnId = array(
  201. 'visitorsFromSearchEngines' => Piwik_Common::REFERER_TYPE_SEARCH_ENGINE,
  202. 'visitorsFromDirectEntry' => Piwik_Common::REFERER_TYPE_DIRECT_ENTRY,
  203. 'visitorsFromWebsites' => Piwik_Common::REFERER_TYPE_WEBSITE,
  204. 'visitorsFromCampaigns' => Piwik_Common::REFERER_TYPE_CAMPAIGN,
  205. );
  206. $return = array();
  207. foreach($nameToColumnId as $nameVar => $columnId)
  208. {
  209. $value = 0;
  210. $row = $dataTableReferersType->getRowFromLabel($columnId);
  211. if($row !== false)
  212. {
  213. $value = $row->getColumn(Piwik_Archive::INDEX_NB_VISITS);
  214. }
  215. $return[$nameVar] = $value;
  216. }
  217. return $return;
  218. }
  219. protected $referrerTypeToLabel = array(
  220. Piwik_Common::REFERER_TYPE_DIRECT_ENTRY => 'Referers_DirectEntry',
  221. Piwik_Common::REFERER_TYPE_SEARCH_ENGINE => 'Referers_SearchEngines',
  222. Piwik_Common::REFERER_TYPE_WEBSITE => 'Referers_Websites',
  223. Piwik_Common::REFERER_TYPE_CAMPAIGN => 'Referers_Campaigns',
  224. );
  225. public function getEvolutionGraph( $fetch = false, $typeReferer = false, $columns = false)
  226. {
  227. $view = $this->getLastUnitGraph($this->pluginName, __FUNCTION__, 'Referers.getRefererType');
  228. // configure displayed columns
  229. if(empty($columns))
  230. {
  231. $columns = Piwik_Common::getRequestVar('columns');
  232. $columns = Piwik::getArrayFromApiParameter($columns);
  233. }
  234. $columns = !is_array($columns) ? array($columns) : $columns;
  235. $view->setColumnsToDisplay($columns);
  236. // configure selectable columns
  237. if (Piwik_Common::getRequestVar('period', false) == 'day') {
  238. $selectable = array('nb_visits', 'nb_uniq_visitors', 'nb_actions');
  239. } else {
  240. $selectable = array('nb_visits', 'nb_actions');
  241. }
  242. $view->setSelectableColumns($selectable);
  243. // configure displayed rows
  244. $visibleRows = Piwik_Common::getRequestVar('rows', false);
  245. if ($visibleRows !== false)
  246. {
  247. // this happens when the row picker has been used
  248. $visibleRows = Piwik::getArrayFromApiParameter($visibleRows);
  249. }
  250. else
  251. {
  252. // use $typeReferer as default
  253. if($typeReferer === false)
  254. {
  255. $typeReferer = Piwik_Common::getRequestVar('typeReferer', false);
  256. }
  257. $label = Piwik_getRefererTypeLabel($typeReferer);
  258. $label = Piwik_Translate($label);
  259. $visibleRows = array($label);
  260. $view->setParametersToModify(array('rows' => $label));
  261. }
  262. $view->addRowPicker($visibleRows);
  263. $view->setReportDocumentation(Piwik_Translate('Referers_EvolutionDocumentation').'<br />'
  264. .Piwik_Translate('General_BrokenDownReportDocumentation').'<br />'
  265. .Piwik_Translate('Referers_EvolutionDocumentationMoreInfo', '&quot;'.Piwik_Translate('Referers_DetailsByRefererType').'&quot;'));
  266. return $this->renderView($view, $fetch);
  267. }
  268. function getLastDistinctSearchEnginesGraph( $fetch = false )
  269. {
  270. $view = $this->getLastUnitGraph($this->pluginName,__FUNCTION__, "Referers.getNumberOfDistinctSearchEngines");
  271. $view->setColumnTranslation('Referers_distinctSearchEngines', ucfirst(Piwik_Translate('Referers_DistinctSearchEngines')));
  272. $view->setColumnsToDisplay(array('Referers_distinctSearchEngines'));
  273. return $this->renderView($view, $fetch);
  274. }
  275. function getLastDistinctKeywordsGraph( $fetch = false )
  276. {
  277. $view = $this->getLastUnitGraph($this->pluginName,__FUNCTION__, "Referers.getNumberOfDistinctKeywords");
  278. $view->setColumnTranslation('Referers_distinctKeywords', ucfirst(Piwik_Translate('Referers_DistinctKeywords')));
  279. $view->setColumnsToDisplay(array('Referers_distinctKeywords'));
  280. return $this->renderView($view, $fetch);
  281. }
  282. function getLastDistinctWebsitesGraph( $fetch = false )
  283. {
  284. $view = $this->getLastUnitGraph($this->pluginName,__FUNCTION__, "Referers.getNumberOfDistinctWebsites");
  285. $view->setColumnTranslation('Referers_distinctWebsites', ucfirst(Piwik_Translate('Referers_DistinctWebsites')));
  286. $view->setColumnsToDisplay(array('Referers_distinctWebsites'));
  287. return $this->renderView($view, $fetch);
  288. }
  289. function getLastDistinctCampaignsGraph( $fetch = false )
  290. {
  291. $view = $this->getLastUnitGraph($this->pluginName,__FUNCTION__, "Referers.getNumberOfDistinctCampaigns");
  292. $view->setColumnTranslation('Referers_distinctCampaigns', ucfirst(Piwik_Translate('Referers_DistinctCampaigns')));
  293. $view->setColumnsToDisplay(array('Referers_distinctCampaigns'));
  294. return $this->renderView($view, $fetch);
  295. }
  296. function getNumberOfDistinctSearchEngines( $fetch = false)
  297. {
  298. return $this->getNumericValue('Referers.' . __FUNCTION__);
  299. }
  300. function getNumberOfDistinctKeywords( $fetch = false)
  301. {
  302. return $this->getNumericValue('Referers.' . __FUNCTION__);
  303. }
  304. function getNumberOfDistinctCampaigns( $fetch = false)
  305. {
  306. return $this->getNumericValue('Referers.' . __FUNCTION__);
  307. }
  308. function getNumberOfDistinctWebsites( $fetch = false)
  309. {
  310. return $this->getNumericValue('Referers.' . __FUNCTION__);
  311. }
  312. function getNumberOfDistinctWebsitesUrls( $fetch = false)
  313. {
  314. return $this->getNumericValue('Referers.' . __FUNCTION__);
  315. }
  316. function getKeywordsForPage()
  317. {
  318. Piwik::checkUserHasViewAccess($this->idSite);
  319. $requestUrl = '&date=previous1'
  320. .'&period=week'
  321. .'&idSite='.$this->idSite
  322. ;
  323. $topPageUrlRequest = $requestUrl
  324. .'&method=Actions.getPageUrls'
  325. .'&filter_limit=50'
  326. .'&format=original';
  327. $request = new Piwik_API_Request($topPageUrlRequest);
  328. $request = $request->process();
  329. $tables = $request->getArray();
  330. $topPageUrls = $tables[key($tables)];
  331. $topPageUrls = $topPageUrls->getRowsMetadata('url');
  332. $topPageUrl = current(array_values($topPageUrls));
  333. if(empty($topPageUrl))
  334. {
  335. $topPageUrl = $this->site->getMainUrl();
  336. }
  337. $url = $topPageUrl;
  338. // HTML
  339. $api = Piwik_Url::getCurrentUrlWithoutFileName()
  340. .'?module=API&method=Referers.getKeywordsForPageUrl'
  341. .'&format=php'
  342. .'&filter_limit=10'
  343. .'&token_auth='.Piwik::getCurrentUserTokenAuth();
  344. $api .= $requestUrl;
  345. $code = '
  346. // This function will call the API to get best keyword for current URL.
  347. // Then it writes the list of best keywords in a HTML list
  348. function DisplayTopKeywords($url = "")
  349. {
  350. // Do not spend more than 1 second fetching the data
  351. @ini_set("default_socket_timeout", $timeout = 1);
  352. // Get the Keywords data
  353. $url = empty($url) ? "http://". $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] : $url;
  354. $api = "'.$api.'&url=" . urlencode($url);
  355. $keywords = @unserialize(file_get_contents($api));
  356. if($keywords === false || isset($keywords["result"])) {
  357. // DEBUG ONLY: uncomment for troubleshooting an empty output (the URL output reveals the token_auth)
  358. // echo "Error while fetching the <a href=\'$api\'>Top Keywords from Piwik</a>";
  359. return;
  360. }
  361. // Display the list in HTML
  362. $output = "<h2>Top Keywords for <a href=\'$url\'>$url</a></h2><ul>";
  363. foreach($keywords as $keyword) {
  364. $output .= "<li>". $keyword[0]. "</li>";
  365. }
  366. if(empty($keywords)) { $output .= "Nothing yet..."; }
  367. $output .= "</ul>";
  368. echo $output;
  369. }
  370. ';
  371. $jsonRequest = str_replace('format=php', 'format=json', $api);
  372. echo "<p>This widget is designed to work in your website directly.
  373. This widget makes it easy to use Piwik to <i>automatically display the list of Top Keywords</i>, for each of your website Page URLs.</p>
  374. <p>
  375. <b>Example API URL</b> - For example if you would like to get the top 10 keywords, used last week, to land on the page <a target='_blank' href='$topPageUrl'>$topPageUrl</a>,
  376. in format JSON: you would dynamically fetch the data using <a target='_blank' href='$jsonRequest&url=".urlencode($topPageUrl)."'>this API request URL</a>. Make sure you encode the 'url' parameter in the URL.</p>
  377. <p><b>PHP Function ready to use!</b> - If you use PHP on your website, we have prepared a small code snippet that you can copy paste in your Website PHP files. You can then simply call the function <code>DisplayTopKeywords();</code> anywhere in your template, at the bottom of the content or in your blog sidebar.
  378. If you run this code in your page $topPageUrl, it would output the following:";
  379. echo "<div style='width:400px;margin-left:20px;padding:10px;border:1px solid black;'>";
  380. function DisplayTopKeywords($url = "", $api)
  381. {
  382. // Do not spend more than 1 second fetching the data
  383. @ini_set("default_socket_timeout", $timeout = 1);
  384. // Get the Keywords data
  385. $url = empty($url) ? "http://". $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] : $url;
  386. $api = $api."&url=" . urlencode($url);
  387. $keywords = @unserialize(file_get_contents($api));
  388. if($keywords === false || isset($keywords["result"])) {
  389. // DEBUG ONLY: uncomment for troubleshooting an empty output (the URL output reveals the token_auth)
  390. //echo "Error while fetching the <a href=\'".$api."\'>Top Keywords from Piwik</a>";
  391. return;
  392. }
  393. // Display the list in HTML
  394. $output = "<h2>Top Keywords for <a href=\'$url\'>$url</a></h2><ul>";
  395. foreach($keywords as $keyword) {
  396. $output .= "<li>". $keyword[0]. "</li>";
  397. }
  398. if(empty($keywords)) { $output .= "Nothing yet..."; }
  399. $output .= "</ul>";
  400. echo $output;
  401. }
  402. DisplayTopKeywords($topPageUrl, $api);
  403. echo "</div><br/>
  404. <p>Here is the PHP function that you can paste in your pages:</P>
  405. <textarea cols=60 rows=8>&lt;?php\n" . htmlspecialchars($code) . "\n DisplayTopKeywords();</textarea>
  406. ";
  407. echo "
  408. <p><b>Notes</b>: You can for example edit the code to to make the Top search keywords link to your Website search result pages.
  409. <br/>On medium to large traffic websites, we recommend to cache this data, as to minimize the performance impact of calling the Piwik API on each page view.
  410. </p>
  411. ";
  412. }
  413. }