PageRenderTime 30ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/core/Controller.php

https://github.com/quarkness/piwik
PHP | 750 lines | 454 code | 66 blank | 230 comment | 63 complexity | 60517eb8d65e1a4738462515b41ec62d 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
  10. * @package Piwik
  11. */
  12. /**
  13. * Parent class of all plugins Controllers (located in /plugins/PluginName/Controller.php
  14. * It defines some helper functions controllers can use.
  15. *
  16. * @package Piwik
  17. */
  18. abstract class Piwik_Controller
  19. {
  20. /**
  21. * Plugin name, eg. Referers
  22. * @var string
  23. */
  24. protected $pluginName;
  25. /**
  26. * Date string
  27. *
  28. * @var string
  29. */
  30. protected $strDate;
  31. /**
  32. * Piwik_Date object or null if the requested date is a range
  33. *
  34. * @var Piwik_Date|null
  35. */
  36. protected $date;
  37. protected $idSite;
  38. /**
  39. * @var Piwik_Site
  40. */
  41. protected $site = null;
  42. /**
  43. * Builds the controller object, reads the date from the request, extracts plugin name from
  44. */
  45. function __construct()
  46. {
  47. $this->init();
  48. }
  49. protected function init()
  50. {
  51. $aPluginName = explode('_', get_class($this));
  52. $this->pluginName = $aPluginName[1];
  53. $date = Piwik_Common::getRequestVar('date', 'yesterday', 'string');
  54. try {
  55. $this->idSite = Piwik_Common::getRequestVar('idSite', false, 'int');
  56. $this->site = new Piwik_Site($this->idSite);
  57. $date = $this->getDateParameterInTimezone($date, $this->site->getTimezone());
  58. $this->setDate($date);
  59. } catch(Exception $e){
  60. // the date looks like YYYY-MM-DD,YYYY-MM-DD or other format
  61. $this->date = null;
  62. }
  63. }
  64. /**
  65. * Helper method to convert "today" or "yesterday" to the default timezone specified.
  66. * If the date is absolute, ie. YYYY-MM-DD, it will not be converted to the timezone
  67. * @param string $date today, yesterday, YYYY-MM-DD
  68. * @param string $defaultTimezone
  69. * @return Piwik_Date
  70. */
  71. protected function getDateParameterInTimezone($date, $defaultTimezone )
  72. {
  73. $timezone = null;
  74. // if the requested date is not YYYY-MM-DD, we need to ensure
  75. // it is relative to the website's timezone
  76. if(in_array($date, array('today', 'yesterday')))
  77. {
  78. // today is at midnight; we really want to get the time now, so that
  79. // * if the website is UTC+12 and it is 5PM now in UTC, the calendar will allow to select the UTC "tomorrow"
  80. // * if the website is UTC-12 and it is 5AM now in UTC, the calendar will allow to select the UTC "yesterday"
  81. if($date == 'today')
  82. {
  83. $date = 'now';
  84. }
  85. elseif($date == 'yesterday')
  86. {
  87. $date = 'yesterdaySameTime';
  88. }
  89. $timezone = $defaultTimezone;
  90. }
  91. return Piwik_Date::factory($date, $timezone);
  92. }
  93. /**
  94. * Sets the date to be used by all other methods in the controller.
  95. * If the date has to be modified, it should be called just after the controller construct
  96. * @param Piwik_Date $date
  97. * @return void
  98. */
  99. protected function setDate(Piwik_Date $date)
  100. {
  101. $this->date = $date;
  102. $strDate = $this->date->toString();
  103. $this->strDate = $strDate;
  104. }
  105. /**
  106. * Returns the name of the default method that will be called
  107. * when visiting: index.php?module=PluginName without the action parameter
  108. *
  109. * @return string
  110. */
  111. function getDefaultAction()
  112. {
  113. return 'index';
  114. }
  115. /**
  116. * Given an Object implementing Piwik_View_Interface, we either:
  117. * - echo the output of the rendering if fetch = false
  118. * - returns the output of the rendering if fetch = true
  119. *
  120. * @param Piwik_ViewDataTable $view
  121. * @param bool $fetch
  122. * @return string|void
  123. */
  124. protected function renderView( Piwik_ViewDataTable $view, $fetch = false)
  125. {
  126. Piwik_PostEvent( 'Controller.renderView',
  127. $this,
  128. array( 'view' => $view,
  129. 'controllerName' => $view->getCurrentControllerName(),
  130. 'controllerAction' => $view->getCurrentControllerAction(),
  131. 'apiMethodToRequestDataTable' => $view->getApiMethodToRequestDataTable(),
  132. 'controllerActionCalledWhenRequestSubTable' => $view->getControllerActionCalledWhenRequestSubTable(),
  133. )
  134. );
  135. $view->main();
  136. $rendered = $view->getView()->render();
  137. if($fetch)
  138. {
  139. return $rendered;
  140. }
  141. echo $rendered;
  142. }
  143. /**
  144. * Returns a ViewDataTable object of an Evolution graph
  145. * for the last30 days/weeks/etc. of the current period, relative to the current date.
  146. *
  147. * @param string $currentModuleName
  148. * @param string $currentControllerAction
  149. * @param string $apiMethod
  150. * @return Piwik_ViewDataTable_GenerateGraphHTML_ChartEvolution
  151. */
  152. protected function getLastUnitGraph($currentModuleName, $currentControllerAction, $apiMethod)
  153. {
  154. $view = Piwik_ViewDataTable::factory('graphEvolution');
  155. $view->init( $currentModuleName, $currentControllerAction, $apiMethod );
  156. // if the date is not yet a nicely formatted date range ie. YYYY-MM-DD,YYYY-MM-DD we build it
  157. // otherwise the current controller action is being called with the good date format already so it's fine
  158. // see constructor
  159. if( !is_null($this->date))
  160. {
  161. $view->setParametersToModify(
  162. $this->getGraphParamsModified( array('date' => $this->strDate))
  163. );
  164. }
  165. return $view;
  166. }
  167. /**
  168. * This method is similar to self::getLastUnitGraph. It works with API.get to combine metrics
  169. * of different *.get reports. The returned ViewDataTable is configured with column
  170. * translations and selectable metrics.
  171. *
  172. * @param string $currentModuleName
  173. * @param string $currentControllerAction
  174. * @param array $columnsToDisplay
  175. * @param array $selectableColumns
  176. * @param string $reportDocumentation
  177. * @param string $apiMethod The method to request the report from
  178. * (by default, this is API.get but it can be changed for custom stuff)
  179. * @return Piwik_ViewDataTable_GenerateGraphHTML_ChartEvolution
  180. */
  181. protected function getLastUnitGraphAcrossPlugins($currentModuleName, $currentControllerAction,
  182. $columnsToDisplay, $selectableColumns=array(), $reportDocumentation=false, $apiMethod='API.get')
  183. {
  184. // back up and manipulate the columns parameter
  185. $backupColumns = false;
  186. if (isset($_GET['columns']))
  187. {
  188. $backupColumns = $_GET['columns'];
  189. }
  190. $_GET['columns'] = implode(',', $columnsToDisplay);
  191. // load translations from meta data
  192. $idSite = Piwik_Common::getRequestVar('idSite');
  193. $period = Piwik_Common::getRequestVar('period');
  194. $date = Piwik_Common::getRequestVar('date');
  195. $meta = Piwik_API_API::getInstance()->getReportMetadata($idSite, $period, $date);
  196. $columns = array_merge($columnsToDisplay, $selectableColumns);
  197. $translations = array();
  198. foreach ($meta as $reportMeta)
  199. {
  200. if ($reportMeta['action'] == 'get' && !isset($reportMeta['parameters']))
  201. {
  202. foreach ($columns as $column)
  203. {
  204. if (isset($reportMeta['metrics'][$column]))
  205. {
  206. $translations[$column] = $reportMeta['metrics'][$column];
  207. }
  208. }
  209. }
  210. }
  211. // initialize the graph and load the data
  212. $view = $this->getLastUnitGraph($currentModuleName, $currentControllerAction, $apiMethod);
  213. $view->setColumnsToDisplay($columnsToDisplay);
  214. $view->setSelectableColumns($selectableColumns);
  215. $view->setColumnsTranslations($translations);
  216. if ($reportDocumentation)
  217. {
  218. $view->setReportDocumentation($reportDocumentation);
  219. }
  220. $view->main();
  221. // restore the columns parameter
  222. if ($backupColumns !== false)
  223. {
  224. $_GET['columns'] = $backupColumns;
  225. }
  226. else
  227. {
  228. unset($_GET['columns']);
  229. }
  230. return $view;
  231. }
  232. /**
  233. * Returns the array of new processed parameters once the parameters are applied.
  234. * For example: if you set range=last30 and date=2008-03-10,
  235. * the date element of the returned array will be "2008-02-10,2008-03-10"
  236. *
  237. * Parameters you can set:
  238. * - range: last30, previous10, etc.
  239. * - date: YYYY-MM-DD, today, yesterday
  240. * - period: day, week, month, year
  241. *
  242. * @param array paramsToSet = array( 'date' => 'last50', 'viewDataTable' =>'sparkline' )
  243. */
  244. protected function getGraphParamsModified($paramsToSet = array())
  245. {
  246. if(!isset($paramsToSet['period']))
  247. {
  248. $period = Piwik_Common::getRequestVar('period');
  249. }
  250. else
  251. {
  252. $period = $paramsToSet['period'];
  253. }
  254. if($period == 'range')
  255. {
  256. return $paramsToSet;
  257. }
  258. if(!isset($paramsToSet['range']))
  259. {
  260. $range = 'last30';
  261. }
  262. else
  263. {
  264. $range = $paramsToSet['range'];
  265. }
  266. if(!isset($paramsToSet['date']))
  267. {
  268. $endDate = $this->strDate;
  269. }
  270. else
  271. {
  272. $endDate = $paramsToSet['date'];
  273. }
  274. if(is_null($this->site))
  275. {
  276. throw new Piwik_Access_NoAccessException("Website not initialized, check that you are logged in and/or using the correct token_auth.");
  277. }
  278. $paramDate = self::getDateRangeRelativeToEndDate($period, $range, $endDate, $this->site);
  279. $params = array_merge($paramsToSet , array( 'date' => $paramDate ) );
  280. return $params;
  281. }
  282. /**
  283. * Given for example, $period = month, $lastN = 'last6', $endDate = '2011-07-01',
  284. * It will return the $date = '2011-01-01,2011-07-01' which is useful to draw graphs for the last N periods
  285. *
  286. * @param string $period
  287. * @param string $lastN
  288. * @param string $endDate
  289. * @param Piwik_Site $site
  290. */
  291. static public function getDateRangeRelativeToEndDate($period, $lastN, $endDate, $site )
  292. {
  293. $last30Relative = new Piwik_Period_Range($period, $lastN, $site->getTimezone() );
  294. $last30Relative->setDefaultEndDate(Piwik_Date::factory($endDate));
  295. $date = $last30Relative->getDateStart()->toString() . "," . $last30Relative->getDateEnd()->toString();
  296. return $date;
  297. }
  298. /**
  299. * Returns a numeric value from the API.
  300. * Works only for API methods that originally returns numeric values (there is no cast here)
  301. *
  302. * @param string $methodToCall Name of method to call, eg. Referers.getNumberOfDistinctSearchEngines
  303. * @return int|float
  304. */
  305. protected function getNumericValue( $methodToCall )
  306. {
  307. $requestString = 'method='.$methodToCall.'&format=original';
  308. $request = new Piwik_API_Request($requestString);
  309. return $request->process();
  310. }
  311. /**
  312. * Returns the current URL to use in a img src=X to display a sparkline.
  313. * $action must be the name of a Controller method that requests data using the Piwik_ViewDataTable::factory
  314. * It will automatically build a sparkline by setting the viewDataTable=sparkline parameter in the URL.
  315. * It will also computes automatically the 'date' for the 'last30' days/weeks/etc.
  316. *
  317. * @param string $action Method name of the controller to call in the img src
  318. * @param array Array of name => value of parameters to set in the generated GET url
  319. * @return string The generated URL
  320. */
  321. protected function getUrlSparkline( $action, $customParameters = array() )
  322. {
  323. $params = $this->getGraphParamsModified(
  324. array( 'viewDataTable' => 'sparkline',
  325. 'action' => $action,
  326. 'module' => $this->pluginName)
  327. + $customParameters
  328. );
  329. // convert array values to comma separated
  330. foreach($params as &$value)
  331. {
  332. if(is_array($value))
  333. {
  334. $value = implode(',', $value);
  335. }
  336. }
  337. $url = Piwik_Url::getCurrentQueryStringWithParametersModified($params);
  338. return $url;
  339. }
  340. /**
  341. * Sets the first date available in the calendar
  342. * @param Piwik_Date $minDate
  343. * @param Piwik_View $view
  344. * @return void
  345. */
  346. protected function setMinDateView(Piwik_Date $minDate, $view)
  347. {
  348. $view->minDateYear = $minDate->toString('Y');
  349. $view->minDateMonth = $minDate->toString('m');
  350. $view->minDateDay = $minDate->toString('d');
  351. }
  352. /**
  353. * Sets "today" in the calendar. Today does not always mean "UTC" today, eg. for websites in UTC+12.
  354. * @param Piwik_Date $maxDate
  355. * @param Piwik_View $view
  356. * @return void
  357. */
  358. protected function setMaxDateView(Piwik_Date $maxDate, $view)
  359. {
  360. $view->maxDateYear = $maxDate->toString('Y');
  361. $view->maxDateMonth = $maxDate->toString('m');
  362. $view->maxDateDay = $maxDate->toString('d');
  363. }
  364. /**
  365. * Sets general variables to the view that are used by various templates and Javascript.
  366. * If any error happens, displays the login screen
  367. * @param Piwik_View $view
  368. * @return void
  369. */
  370. protected function setGeneralVariablesView($view)
  371. {
  372. $view->date = $this->strDate;
  373. try {
  374. $view->idSite = $this->idSite;
  375. if(empty($this->site) || empty($this->idSite))
  376. {
  377. throw new Exception("The requested website idSite is not found in the request, or is invalid.
  378. Please check that you are logged in Piwik and have permission to access the specified website.");
  379. }
  380. $this->setPeriodVariablesView($view);
  381. $rawDate = Piwik_Common::getRequestVar('date');
  382. $periodStr = Piwik_Common::getRequestVar('period');
  383. if($periodStr != 'range')
  384. {
  385. $date = Piwik_Date::factory($this->strDate);
  386. $period = Piwik_Period::factory($periodStr, $date);
  387. }
  388. else
  389. {
  390. $period = new Piwik_Period_Range($periodStr, $rawDate, $this->site->getTimezone());
  391. }
  392. $view->rawDate = $rawDate;
  393. $view->prettyDate = $period->getPrettyString();
  394. $view->siteName = $this->site->getName();
  395. $view->siteMainUrl = $this->site->getMainUrl();
  396. $datetimeMinDate = $this->site->getCreationDate()->getDatetime();
  397. $minDate = Piwik_Date::factory($datetimeMinDate, $this->site->getTimezone());
  398. $this->setMinDateView($minDate, $view);
  399. $maxDate = Piwik_Date::factory('now', $this->site->getTimezone());
  400. $this->setMaxDateView($maxDate, $view);
  401. // Setting current period start & end dates, for pre-setting the calendar when "Date Range" is selected
  402. $dateStart = $period->getDateStart();
  403. if($dateStart->isEarlier($minDate)) { $dateStart = $minDate; }
  404. $dateEnd = $period->getDateEnd();
  405. if($dateEnd->isLater($maxDate)) { $dateEnd = $maxDate; }
  406. $view->startDate = $dateStart;
  407. $view->endDate = $dateEnd;
  408. $language = Piwik_LanguagesManager::getLanguageForSession();
  409. $view->language = !empty($language) ? $language : Piwik_LanguagesManager::getLanguageCodeForCurrentUser();
  410. $this->setBasicVariablesView($view);
  411. } catch(Exception $e) {
  412. Piwik_ExitWithMessage($e->getMessage());
  413. }
  414. }
  415. /**
  416. * Set the minimal variables in the view object
  417. *
  418. * @param Piwik_View $view
  419. */
  420. protected function setBasicVariablesView($view)
  421. {
  422. $view->topMenu = Piwik_GetTopMenu();
  423. $view->debugTrackVisitsInsidePiwikUI = Zend_Registry::get('config')->Debug->track_visits_inside_piwik_ui;
  424. $view->isSuperUser = Zend_Registry::get('access')->isSuperUser();
  425. $view->isCustomLogo = Zend_Registry::get('config')->branding->use_custom_logo;
  426. $view->logoHeader = Piwik_API_API::getInstance()->getHeaderLogoUrl();
  427. $view->logoLarge = Piwik_API_API::getInstance()->getLogoUrl();
  428. $view->piwikUrl = Piwik::getPiwikUrl();
  429. }
  430. /**
  431. * Sets general period variables (available periods, current period, period labels) used by templates
  432. * @param Piwik_View $view
  433. * @return void
  434. */
  435. public static function setPeriodVariablesView($view)
  436. {
  437. if(isset($view->period))
  438. {
  439. return;
  440. }
  441. $currentPeriod = Piwik_Common::getRequestVar('period');
  442. $view->displayUniqueVisitors = Piwik::isUniqueVisitorsEnabled($currentPeriod);
  443. $availablePeriods = array('day', 'week', 'month', 'year', 'range');
  444. if(!in_array($currentPeriod,$availablePeriods))
  445. {
  446. throw new Exception("Period must be one of: ".implode(",",$availablePeriods));
  447. }
  448. $periodNames = array(
  449. 'day' => array('singular' => Piwik_Translate('CoreHome_PeriodDay'), 'plural' => Piwik_Translate('CoreHome_PeriodDays')),
  450. 'week' => array('singular' => Piwik_Translate('CoreHome_PeriodWeek'), 'plural' => Piwik_Translate('CoreHome_PeriodWeeks')),
  451. 'month' => array('singular' => Piwik_Translate('CoreHome_PeriodMonth'), 'plural' => Piwik_Translate('CoreHome_PeriodMonths')),
  452. 'year' => array('singular' => Piwik_Translate('CoreHome_PeriodYear'), 'plural' => Piwik_Translate('CoreHome_PeriodYears')),
  453. // Note: plural is not used for date range
  454. 'range' => array('singular' => Piwik_Translate('General_DateRangeInPeriodList'), 'plural' => Piwik_Translate('General_DateRangeInPeriodList') ),
  455. );
  456. $found = array_search($currentPeriod,$availablePeriods);
  457. if($found !== false)
  458. {
  459. unset($availablePeriods[$found]);
  460. }
  461. $view->period = $currentPeriod;
  462. $view->otherPeriods = $availablePeriods;
  463. $view->periodsNames = $periodNames;
  464. }
  465. /**
  466. * Set metrics variables (displayed metrics, available metrics) used by template
  467. * Handles the server-side of the metrics picker
  468. * @param Piwik_View $view
  469. * @param string $defaultMetricDay name of the default metric for period=day
  470. * @param string $defaultMetric name of the default metric for other periods
  471. * @param array $metricsForDay metrics that are only available for period=day
  472. * @param array $metricsForAllPeriods metrics that are available for all periods
  473. * @param bool $labelDisplayed add 'label' to columns to display?
  474. * @return void
  475. */
  476. protected function setMetricsVariablesView(Piwik_ViewDataTable $view, $defaultMetricDay='nb_uniq_visitors',
  477. $defaultMetric='nb_visits', $metricsForDay=array('nb_uniq_visitors'),
  478. $metricsForAllPeriods=array('nb_visits', 'nb_actions'), $labelDisplayed=true)
  479. {
  480. // columns is set in the request if metrics picker has been used
  481. $columns = Piwik_Common::getRequestVar('columns', false);
  482. if ($columns !== false)
  483. {
  484. $columns = Piwik::getArrayFromApiParameter($columns);
  485. $firstColumn = $columns[0];
  486. }
  487. else
  488. {
  489. // default columns
  490. $firstColumn = isset($view->period) && $view->period == 'day' ? $defaultMetricDay : $defaultMetric;
  491. $columns = array($firstColumn);
  492. }
  493. // displayed columns
  494. if ($labelDisplayed)
  495. {
  496. array_unshift($columns, 'label');
  497. }
  498. $view->setColumnsToDisplay($columns);
  499. // Continue only for graphs
  500. if(!($view instanceof Piwik_ViewDataTable_GenerateGraphData))
  501. {
  502. return;
  503. }
  504. // do not sort if sorted column was initially "label" or eg. it would make "Visits by Server time" not pretty
  505. if($view->getSortedColumn() != 'label')
  506. {
  507. $view->setSortedColumn($firstColumn);
  508. }
  509. // selectable columns
  510. if (isset($view->period) && $view->period == 'day')
  511. {
  512. $selectableColumns = array_merge($metricsForDay, $metricsForAllPeriods);
  513. }
  514. else
  515. {
  516. $selectableColumns = $metricsForAllPeriods;
  517. }
  518. $view->setSelectableColumns($selectableColumns);
  519. }
  520. /**
  521. * Helper method used to redirect the current http request to another module/action
  522. * If specified, will also redirect to a given website, period and /or date
  523. *
  524. * @param string $moduleToRedirect Module, eg. "MultiSites"
  525. * @param string $actionToRedirect Action, eg. "index"
  526. * @param string $websiteId Website ID, eg. 1
  527. * @param string $defaultPeriod Default period, eg. "day"
  528. * @param string $defaultDate Default date, eg. "today"
  529. */
  530. function redirectToIndex($moduleToRedirect, $actionToRedirect, $websiteId = null, $defaultPeriod = null, $defaultDate = null, $parameters = array())
  531. {
  532. if(is_null($websiteId))
  533. {
  534. $websiteId = $this->getDefaultWebsiteId();
  535. }
  536. if(is_null($defaultDate))
  537. {
  538. $defaultDate = $this->getDefaultDate();
  539. }
  540. if(is_null($defaultPeriod))
  541. {
  542. $defaultPeriod = $this->getDefaultPeriod();
  543. }
  544. $parametersString = '';
  545. if(!empty($parameters))
  546. {
  547. $parametersString = '&' . Piwik_Url::getQueryStringFromParameters($parameters);
  548. }
  549. if($websiteId) {
  550. $url = "Location: index.php?module=".$moduleToRedirect
  551. ."&action=".$actionToRedirect
  552. ."&idSite=".$websiteId
  553. ."&period=".$defaultPeriod
  554. ."&date=".$defaultDate
  555. .$parametersString;
  556. header($url);
  557. exit;
  558. }
  559. if(Piwik::isUserIsSuperUser())
  560. {
  561. Piwik_ExitWithMessage("Error: no website was found in this Piwik installation.
  562. <br />Check the table '". Piwik_Common::prefixTable('site') ."' that should contain your Piwik websites.", false, true);
  563. }
  564. $currentLogin = Piwik::getCurrentUserLogin();
  565. if(!empty($currentLogin)
  566. && $currentLogin != 'anonymous')
  567. {
  568. $errorMessage = sprintf(Piwik_Translate('CoreHome_NoPrivilegesAskPiwikAdmin'), $currentLogin, "<br/><a href='mailto:".Piwik::getSuperUserEmail()."?subject=Access to Piwik for user $currentLogin'>", "</a>");
  569. $errorMessage .= "<br /><br />&nbsp;&nbsp;&nbsp;<b><a href='index.php?module=". Zend_Registry::get('auth')->getName() ."&amp;action=logout'>&rsaquo; ". Piwik_Translate('General_Logout'). "</a></b><br />";
  570. Piwik_ExitWithMessage($errorMessage, false, true);
  571. }
  572. Piwik_FrontController::getInstance()->dispatch(Piwik::getLoginPluginName(), false);
  573. exit;
  574. }
  575. /**
  576. * Returns default website that Piwik should load
  577. * @return Piwik_Site
  578. */
  579. protected function getDefaultWebsiteId()
  580. {
  581. $defaultWebsiteId = false;
  582. // User preference: default website ID to load
  583. $defaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT);
  584. if(is_numeric($defaultReport))
  585. {
  586. $defaultWebsiteId = $defaultReport;
  587. }
  588. Piwik_PostEvent( 'Controller.getDefaultWebsiteId', $defaultWebsiteId );
  589. if($defaultWebsiteId)
  590. {
  591. return $defaultWebsiteId;
  592. }
  593. $sitesId = Piwik_SitesManager_API::getInstance()->getSitesIdWithAtLeastViewAccess();
  594. if(!empty($sitesId))
  595. {
  596. return $sitesId[0];
  597. }
  598. return false;
  599. }
  600. /**
  601. * Returns default date for Piwik reports
  602. * @return string today, 2010-01-01, etc.
  603. */
  604. protected function getDefaultDate()
  605. {
  606. // NOTE: a change in this function might mean a change in plugins/UsersManager/templates/userSettings.js as well
  607. $userSettingsDate = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE);
  608. if($userSettingsDate === false)
  609. {
  610. return Zend_Registry::get('config')->General->default_day;
  611. }
  612. if($userSettingsDate == 'yesterday')
  613. {
  614. return $userSettingsDate;
  615. }
  616. // if last7, last30, etc.
  617. if(strpos($userSettingsDate, 'last') === 0
  618. || strpos($userSettingsDate, 'previous') === 0)
  619. {
  620. return $userSettingsDate;
  621. }
  622. return 'today';
  623. }
  624. /**
  625. * Returns default date for Piwik reports
  626. * @return string today, 2010-01-01, etc.
  627. */
  628. protected function getDefaultPeriod()
  629. {
  630. $userSettingsDate = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE);
  631. if($userSettingsDate === false)
  632. {
  633. return Zend_Registry::get('config')->General->default_period;
  634. }
  635. if(in_array($userSettingsDate, array('today','yesterday')))
  636. {
  637. return 'day';
  638. }
  639. if(strpos($userSettingsDate, 'last') === 0
  640. || strpos($userSettingsDate, 'previous') === 0)
  641. {
  642. return 'range';
  643. }
  644. return $userSettingsDate;
  645. }
  646. /**
  647. * Checks that the specified token matches the current logged in user token.
  648. * Note: this protection against CSRF should be limited to controller
  649. * actions that are either invoked via AJAX or redirect to a page
  650. * within the site. The token should never appear in the browser's
  651. * address bar.
  652. *
  653. * @return throws exception if token doesn't match
  654. */
  655. protected function checkTokenInUrl()
  656. {
  657. if(Piwik_Common::getRequestVar('token_auth', false) != Piwik::getCurrentUserTokenAuth()) {
  658. throw new Piwik_Access_NoAccessException(Piwik_TranslateException('General_ExceptionInvalidToken'));
  659. }
  660. }
  661. }
  662. /**
  663. * Parent class of all plugins Controllers with admin functions
  664. *
  665. * @package Piwik
  666. */
  667. abstract class Piwik_Controller_Admin extends Piwik_Controller
  668. {
  669. /**
  670. * Used by Admin screens
  671. *
  672. * @param Piwik_View $view
  673. */
  674. protected function setBasicVariablesView($view)
  675. {
  676. parent::setBasicVariablesView($view);
  677. $view->currentAdminMenuName = Piwik_GetCurrentAdminMenuName();
  678. $view->enableFrames = Zend_Registry::get('config')->General->enable_framed_settings;
  679. if(!$view->enableFrames)
  680. {
  681. $view->setXFrameOptions('sameorigin');
  682. }
  683. }
  684. }