processRequest() public static method

Helper method that processes an API request in one line using the variables in $_GET and $_POST.
public static processRequest ( string $method, array $paramOverride = [], array $defaultRequest = null ) : mixed
$method string The API method to call, ie, `'Actions.getPageTitles'`.
$paramOverride array The parameter name-value pairs to use instead of what's in `$_GET` & `$_POST`.
$defaultRequest array Default query parameters. If a query parameter is absent in `$request`, it will be loaded from this. Defaults to `$_GET + $_POST`. To avoid using any parameters from $_GET or $_POST, set this to an empty `array()`.
return mixed The result of the API request. See {@link process()}.
Ejemplo n.º 1
0
 protected function getContentNames($websiteId = null, $date = null)
 {
     if (!is_null($websiteId)) {
         return \Piwik\API\Request::processRequest('Contents.getContentNames', array('idSite' => $websiteId, 'period' => 'year', 'date' => $date));
     }
     return Db::fetchAssoc("select `idaction`, `name` from `{$this->tablePrefix}log_action` where `type` = ?", array(\Piwik\Tracker\Action::TYPE_CONTENT_NAME));
 }
 private function createTrackToOwnPiwikSetting()
 {
     return $this->makeSetting('ownPiwikSiteId', $default = 0, FieldConfig::TYPE_INT, function (FieldConfig $field) {
         $field->title = 'Site Id';
         // ideally we would use a SELECT control and let user choose an existing site but this would make performance slow
         // since we'd always have to get all site ids in each request
         $field->uiControl = FieldConfig::UI_CONTROL_TEXT;
         $field->introduction = 'Send anonymize usage data to this Piwik';
         $field->description = 'If specified, anonymized usage data will be sent to the specified site in this Piwik.';
         $field->validate = function ($idSite) {
             if (empty($idSite)) {
                 return;
             }
             if (!is_numeric($idSite)) {
                 throw new Exception("Site Id '{$idSite}' should be a number");
             }
             $idSite = (int) $idSite;
             try {
                 $siteExists = Request::processRequest('SitesManager.getSiteFromId', array('idSite' => $idSite));
             } catch (Exception $e) {
                 $siteExists = false;
             }
             if (!$siteExists) {
                 throw new Exception("The specified idSite '{$idSite}' does not exist");
             }
         };
     });
 }
Ejemplo n.º 3
0
 /**
  * This widget shows horizontal bars with cpu load, memory use, network traffic and disk use
  **/
 function elementLiveLoadBars()
 {
     $result = Request::processRequest('SimpleSysMon.getLiveSysLoadData');
     $view = new View('@SimpleSysMon/widgetLiveSysLoadBars.twig');
     $this->setBasicVariablesView($view);
     $view->sysLoad = array('avgload' => array('used' => round($result['AvgLoad'], 0), 'free' => round(100.0 - $result['AvgLoad'], 0)), 'memory' => array('procUsed' => round($result['UsedMemProc'], 0), 'procCached' => round($result['CachedMemProc'], 0), 'procFree' => round(100.0 - $result['UsedMemProc'], 0), 'valUsed' => round($result['UsedMemVal'], 0), 'valCached' => round($result['CachedMemVal'], 0), 'valFree' => round($result['FreeMemProc'], 0)), 'net' => array('procUpload' => round($result['UpNetProc'], 0), 'procDownload' => round($result['DownNetProc'], 0), 'procFree' => round(100.0 - $result['DownNetProc'], 0), 'valUpload' => round($result['UpNetVal'], 0), 'valDownload' => round($result['DownNetVal'], 0)), 'disk' => array('procUsed' => round($result['UsedDiskProc'], 0), 'procFree' => round($result['FreeDiskProc'], 0), 'valUsed' => round($result['UsedDiskVal'], 0), 'valFree' => round($result['FreeDiskVal'], 0)));
     return $view->render();
 }
Ejemplo n.º 4
0
 /**
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param bool|string $segment
  * @param bool|array $columns
  * @return mixed
  */
 public function get($idSite, $period, $date, $segment = false, $columns = false)
 {
     $segment = $this->appendReturningVisitorSegment($segment);
     $this->unprefixColumns($columns);
     $params = array('idSite' => $idSite, 'period' => $period, 'date' => $date, 'segment' => $segment, 'columns' => implode(',', $columns), 'format' => 'original', 'serialize' => 0);
     $table = Request::processRequest('VisitsSummary.get', $params);
     $this->prefixColumns($table, $period);
     return $table;
 }
Ejemplo n.º 5
0
 public function findSegment($segmentName, $idSite)
 {
     $segments = Request::processRequest('API.getSegmentsMetadata', array('idSites' => array($idSite)));
     foreach ($segments as $segment) {
         if ($segment['segment'] == $segmentName && !empty($segmentName)) {
             return $segment;
         }
     }
 }
Ejemplo n.º 6
0
 public function render()
 {
     $userLogins = Request::processRequest('UsersManager.getUsersLogin', array('filter_limit' => '-1'));
     $websites = Request::processRequest('SitesManager.getAllSites', array('filter_limit' => '-1'));
     $numUsers = count($userLogins);
     if (in_array('anonymous', $userLogins)) {
         $numUsers--;
     }
     return $this->renderTemplate('getSystemSummary', array('numWebsites' => count($websites), 'numUsers' => $numUsers, 'numSegments' => $this->getNumSegments(), 'numPlugins' => $this->getNumPlugins(), 'piwikVersion' => Version::VERSION, 'mySqlVersion' => $this->getMySqlVersion(), 'phpVersion' => phpversion()));
 }
 private function executeSomeApiMethods()
 {
     Request::processRequest('API.getPiwikVersion');
     Request::processRequest('API.getSettings');
     Request::processRequest('UsersManager.getUsers');
     Request::processRequest('API.getPiwikVersion');
     Request::processRequest('VisitsSummary.get', array('idSite' => 1, 'period' => 'year', 'date' => 'today'));
     $date = Date::factory('today')->toString();
     Request::processRequest('CoreAdminHome.invalidateArchivedReports', array('idSites' => '1', 'period' => 'year', 'dates' => $date, 'cascadeDown' => '1'));
 }
Ejemplo n.º 8
0
 public function goalConversionsOverview()
 {
     $view = new View('@Goals/conversionOverview');
     $idGoal = Common::getRequestVar('idGoal', null, 'string');
     $view->topDimensions = $this->getTopDimensions($idGoal);
     $goalMetrics = Request::processRequest('Goals.get', array('idGoal' => $idGoal));
     // conversion rate for new and returning visitors
     $view->conversion_rate_returning = $this->formatConversionRate($goalMetrics, 'conversion_rate_returning_visit');
     $view->conversion_rate_new = $this->formatConversionRate($goalMetrics, 'conversion_rate_new_visit');
     $view->idGoal = $idGoal;
     return $view->render();
 }
 /**
  * We send this data via server to not expose eg PHP version to users
  * @return array
  */
 public function getServerVisitCustomVariables()
 {
     $users = Request::processRequest('UsersManager.getUsers', array('filter_limit' => '-1'));
     $websites = Request::processRequest('SitesManager.getAllSites', array('filter_limit' => '-1'));
     $customVars = array(array('id' => 1, 'name' => 'Piwik Version', 'value' => StaticContainer::get('AnonymousPiwikUsageMeasurement.piwikVersion')), array('id' => 2, 'name' => 'PHP Version', 'value' => StaticContainer::get('AnonymousPiwikUsageMeasurement.phpVersion')), array('id' => 3, 'name' => 'Num Users', 'value' => count($users)), array('id' => 4, 'name' => 'Num Websites', 'value' => count($websites)));
     $segmentClass = 'Piwik\\Plugins\\SegmentEditor\\Services\\StoredSegmentService';
     if (class_exists($segmentClass)) {
         $service = StaticContainer::get($segmentClass);
         $segments = $service->getAllSegmentsAndIgnoreVisibility();
         $customVars[] = array('id' => 5, 'name' => 'Num Segments', 'value' => count($segments));
     }
     return $customVars;
 }
Ejemplo n.º 10
0
 public function render()
 {
     $lastMinutes = Config::getInstance()->General[Controller::SIMPLE_VISIT_COUNT_WIDGET_LAST_MINUTES_CONFIG_KEY];
     $lastNData = Request::processRequest('Live.getCounters', array('lastMinutes' => $lastMinutes));
     $view = new View('@Live/getSimpleLastVisitCount');
     $view->lastMinutes = $lastMinutes;
     $view->visitors = MetricsFormatter::getPrettyNumber($lastNData[0]['visitors']);
     $view->visits = MetricsFormatter::getPrettyNumber($lastNData[0]['visits']);
     $view->actions = MetricsFormatter::getPrettyNumber($lastNData[0]['actions']);
     $view->refreshAfterXSecs = Config::getInstance()->General['live_widget_refresh_after_seconds'];
     $view->translations = array('one_visitor' => Piwik::translate('Live_NbVisitor'), 'visitors' => Piwik::translate('Live_NbVisitors'), 'one_visit' => Piwik::translate('General_OneVisit'), 'visits' => Piwik::translate('General_NVisits'), 'one_action' => Piwik::translate('General_OneAction'), 'actions' => Piwik::translate('VisitsSummary_NbActionsDescription'), 'one_minute' => Piwik::translate('General_OneMinute'), 'minutes' => Piwik::translate('General_NMinutes'));
     return $view->render();
 }
Ejemplo n.º 11
0
 public function getConversionForGoal($idGoal, $idSite, $period, $date)
 {
     if (!$period || !$date || !$idSite) {
         return false;
     }
     $datatable = Request::processRequest('Goals.get', array('idGoal' => $idGoal, 'period' => $period, 'date' => $date, 'idSite' => $idSite, 'serialize' => 0, 'segment' => false));
     // we ignore the segment even if there is one set. We still want to show conversion overview if there are conversions
     // in general but not for this segment
     $dataRow = $datatable->getFirstRow();
     if (!$dataRow) {
         return false;
     }
     return $dataRow->getColumn('nb_conversions');
 }
Ejemplo n.º 12
0
 public function getConversionsOverview()
 {
     $view = new View('@Ecommerce/conversionOverview');
     $idGoal = Common::getRequestVar('idGoal', null, 'string');
     $goalMetrics = Request::processRequest('Goals.get', array('idGoal' => $idGoal));
     $dataRow = $goalMetrics->getFirstRow();
     $view->idSite = Common::getRequestVar('idSite', null, 'int');
     $view->idGoal = $idGoal;
     if ($dataRow) {
         $view->revenue = $dataRow->getColumn('revenue');
         $view->revenue_subtotal = $dataRow->getColumn('revenue_subtotal');
         $view->revenue_tax = $dataRow->getColumn('revenue_tax');
         $view->revenue_shipping = $dataRow->getColumn('revenue_shipping');
         $view->revenue_discount = $dataRow->getColumn('revenue_discount');
     }
     return $view->render();
 }
Ejemplo n.º 13
0
 /**
  * Another example method that returns a data table.
  * @param int    $idSite
  * @param string $period
  * @param string $date
  * @param bool|string $segment
  * @return DataTable
  */
 public function getBannerstatistics($idSite, $period, $date, $segment = false, $idSubtable = false, $filter_limit = 10, $filter_sort_column = 'impressions', $filter_sort_order = 'desc', $filter_pattern = null)
 {
     $params = array('idSite' => $idSite, 'period' => $period, 'date' => $date, 'segment' => $segment, 'filter_limit' => $filter_limit, 'filter_sort_column' => $filter_sort_column, 'filter_sort_order' => $filter_sort_order, 'filter_pattern' => $filter_pattern);
     if ($idSubtable) {
         return $this->bannerStats($idSubtable, $params);
     }
     $contentNames = \Piwik\API\Request::processRequest('Contents.getContentNames', $params);
     $bannerTable = new Datatable();
     //$period = $dataTable->getMetadata(DataTableFactory::TABLE_METADATA_PERIOD_INDEX);
     //$bannerTable->setMetadataValues($contentNames->getAllTableMetadata());
     foreach ($contentNames->getRows() as $contentName) {
         $bannerName = $contentName->getColumn('label');
         $row = new Row(array(Row::COLUMNS => array('Name' => $bannerName, 'Visits' => $contentName->getColumn('nb_visits'), 'Impressions' => $contentName->getColumn('nb_impressions'), 'Interactions' => $contentName->getColumn('nb_interactions'), 'Conversion rate' => $contentName->getColumn('interaction_rate')), Row::DATATABLE_ASSOCIATED => $bannerName));
         $bannerTable->addRow($row);
     }
     return $bannerTable;
 }
 public function test_shouldTrackApiCall()
 {
     Request::processRequest('API.getPiwikVersion');
     Request::processRequest('API.getSettings');
     Request::processRequest('UsersManager.getUsers');
     Request::processRequest('API.getPiwikVersion');
     $profiles = new Profiles();
     $pushedProfiles = $profiles->popAll();
     foreach ($pushedProfiles as &$pushedProfile) {
         $this->assertNotEmpty($pushedProfile['creation_date']);
         unset($pushedProfile['creation_date']);
         $this->assertGreaterThanOrEqual(1, $pushedProfile['wall_time']);
         unset($pushedProfile['wall_time']);
     }
     $expected = array(array('category' => 'API', 'name' => 'API', 'action' => 'API.getPiwikVersion', 'count' => '2'), array('category' => 'API', 'name' => 'API', 'action' => 'API.getSettings', 'count' => '1'), array('category' => 'API', 'name' => 'UsersManager', 'action' => 'UsersManager.getUsers', 'count' => '1'));
     $this->assertEquals($expected, $pushedProfiles);
 }
Ejemplo n.º 15
0
 public function test_forceNewVisit_shouldNotForceANewVisitWhenNoKeywordIsSetAndReferrerHostChanges()
 {
     $dateTime = '2015-01-03';
     $idSite = self::$fixture->idSite;
     $t = Fixture::getTracker($idSite, $dateTime . ' 00:01:02', $defaultInit = true);
     // track a campaign that was opened directly (no referrer)
     $t->setUrlReferrer('http://www.google.com');
     $t->setUrl('http://piwik.net/?pk_campaign=adwbuccc');
     $t->doTrackPageView('My Title');
     // navigate to next page on same page
     $t->setUrlReferrer('http://piwik.net/?pk_campaign=adwbuccc');
     $t->setCustomTrackingParameter('_rcn', 'adwbuccc');
     // this parameter would be set by piwik.js from cookie / attributionInfo
     $t->setCustomTrackingParameter('_rck', '');
     // no keyword was used in previous tracking request
     $t->setUrl('http://piwik.net/page1');
     $t->doTrackPageView('Page 1');
     /** @var DataTable $visits */
     $visits = Request::processRequest('VisitsSummary.get', array('idSite' => 1, 'period' => 'day', 'date' => $dateTime));
     $this->assertEquals(1, $visits->getFirstRow()->getColumn('nb_visits'));
     $this->assertEquals(2, $visits->getFirstRow()->getColumn('nb_actions'));
 }
Ejemplo n.º 16
0
 protected function setSparklinesAndNumbers($view)
 {
     $view->urlSparklineNbVisits = $this->getUrlSparkline('getEvolutionGraph', array('columns' => $view->displayUniqueVisitors ? array('nb_visits', 'nb_uniq_visitors') : array('nb_visits')));
     $view->urlSparklineNbUsers = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_users')));
     $view->urlSparklineNbPageviews = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_pageviews', 'nb_uniq_pageviews')));
     $view->urlSparklineNbDownloads = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_downloads', 'nb_uniq_downloads')));
     $view->urlSparklineNbOutlinks = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_outlinks', 'nb_uniq_outlinks')));
     $view->urlSparklineAvgVisitDuration = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('avg_time_on_site')));
     $view->urlSparklineMaxActions = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('max_actions')));
     $view->urlSparklineActionsPerVisit = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_actions_per_visit')));
     $view->urlSparklineBounceRate = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('bounce_rate')));
     $view->urlSparklineAvgGenerationTime = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('avg_time_generation')));
     $idSite = Common::getRequestVar('idSite');
     $displaySiteSearch = Site::isSiteSearchEnabledFor($idSite);
     if ($displaySiteSearch) {
         $view->urlSparklineNbSearches = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_searches', 'nb_keywords')));
     }
     $view->displaySiteSearch = $displaySiteSearch;
     $dataTableVisit = self::getVisitsSummary();
     $dataRow = $dataTableVisit->getRowsCount() == 0 ? new Row() : $dataTableVisit->getFirstRow();
     $view->nbUniqVisitors = (int) $dataRow->getColumn('nb_uniq_visitors');
     $view->nbUsers = (int) $dataRow->getColumn('nb_users');
     $nbVisits = (int) $dataRow->getColumn('nb_visits');
     $view->nbVisits = $nbVisits;
     $view->averageVisitDuration = $dataRow->getColumn('avg_time_on_site');
     $view->bounceRate = $dataRow->getColumn('bounce_rate');
     $view->maxActions = (int) $dataRow->getColumn('max_actions');
     $view->nbActionsPerVisit = $dataRow->getColumn('nb_actions_per_visit');
     if (Common::isActionsPluginEnabled()) {
         $view->showActionsPluginReports = true;
         $dataTableActions = Request::processRequest("Actions.get", array('idSite' => $idSite, 'period' => Common::getRequestVar('period'), 'date' => Common::getRequestVar('date'), 'segment' => Request::getRawSegmentFromRequest()), $defaultParams = array());
         $dataActionsRow = $dataTableActions->getRowsCount() == 0 ? new Row() : $dataTableActions->getFirstRow();
         $view->nbPageviews = (int) $dataActionsRow->getColumn('nb_pageviews');
         $view->nbUniquePageviews = (int) $dataActionsRow->getColumn('nb_uniq_pageviews');
         $view->nbDownloads = (int) $dataActionsRow->getColumn('nb_downloads');
         $view->nbUniqueDownloads = (int) $dataActionsRow->getColumn('nb_uniq_downloads');
         $view->nbOutlinks = (int) $dataActionsRow->getColumn('nb_outlinks');
         $view->nbUniqueOutlinks = (int) $dataActionsRow->getColumn('nb_uniq_outlinks');
         $view->averageGenerationTime = $dataActionsRow->getColumn('avg_time_generation');
         if ($displaySiteSearch) {
             $view->nbSearches = (int) $dataActionsRow->getColumn('nb_searches');
             $view->nbKeywords = (int) $dataActionsRow->getColumn('nb_keywords');
         }
         // backward compatibility:
         // show actions if the finer metrics are not archived
         $view->showOnlyActions = false;
         if ($dataActionsRow->getColumn('nb_pageviews') + $dataActionsRow->getColumn('nb_downloads') + $dataActionsRow->getColumn('nb_outlinks') == 0 && $dataRow->getColumn('nb_actions') > 0) {
             $view->showOnlyActions = true;
             $view->nbActions = $dataRow->getColumn('nb_actions');
             $view->urlSparklineNbActions = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_actions')));
         }
     }
 }
Ejemplo n.º 17
0
 protected function getGoalReportView($idGoal = false)
 {
     $view = new View('@Goals/getGoalReportView');
     if ($idGoal == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER) {
         $goalDefinition['name'] = $this->translator->translate('Goals_Ecommerce');
         $goalDefinition['allow_multiple'] = true;
         $ecommerce = $view->ecommerce = true;
     } else {
         if (!isset($this->goals[$idGoal])) {
             Piwik::redirectToModule('Goals', 'index', array('idGoal' => null));
         }
         $goalDefinition = $this->goals[$idGoal];
     }
     $this->setGeneralVariablesView($view);
     $goal = $this->getMetricsForGoal($idGoal);
     foreach ($goal as $name => $value) {
         $view->{$name} = $value;
     }
     if ($idGoal == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER) {
         $goal = $this->getMetricsForGoal(Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART);
         foreach ($goal as $name => $value) {
             $name = 'cart_' . $name;
             $view->{$name} = $value;
         }
     }
     $view->showHeadline = false;
     $view->idGoal = $idGoal;
     $view->goalName = $goalDefinition['name'];
     $view->goalAllowMultipleConversionsPerVisit = $goalDefinition['allow_multiple'];
     $view->graphEvolution = $this->getEvolutionGraph(array(), $idGoal, array('nb_conversions'));
     $view->nameGraphEvolution = 'Goals.getEvolutionGraph' . $idGoal;
     $view->topDimensions = $this->getTopDimensions($idGoal);
     $goalMetrics = Request::processRequest('Goals.get', array('idGoal' => $idGoal));
     // conversion rate for new and returning visitors
     $view->conversion_rate_returning = $this->formatConversionRate($goalMetrics, 'conversion_rate_returning_visit');
     $view->conversion_rate_new = $this->formatConversionRate($goalMetrics, 'conversion_rate_new_visit');
     $view->goalReportsByDimension = $this->getGoalReportsByDimensionTable($view->nb_conversions, isset($ecommerce), !empty($view->cart_nb_conversions));
     return $view;
 }
Ejemplo n.º 18
0
 /**
  * Fetches the list of sites which names match the string pattern
  *
  * @param string $pattern
  * @param bool   $_restrictSitesToLogin
  * @return array|string
  */
 private function getSitesIdFromPattern($pattern, $_restrictSitesToLogin)
 {
     // First clear cache
     Site::clearCache();
     if (empty($pattern)) {
         /** @var Scheduler $scheduler */
         $scheduler = StaticContainer::getContainer()->get('Piwik\\Scheduler\\Scheduler');
         // Then, warm the cache with only the data we should have access to
         if (Piwik::hasUserSuperUserAccess() && !$scheduler->isRunningTask()) {
             APISitesManager::getInstance()->getAllSites();
         } else {
             APISitesManager::getInstance()->getSitesWithAtLeastViewAccess($limit = false, $_restrictSitesToLogin);
         }
     } else {
         $sites = Request::processRequest('SitesManager.getPatternMatchSites', array('pattern' => $pattern, 'showColumns' => '', 'hideColumns' => '', 'serialize' => 0, 'format' => 'original'));
         if (!empty($sites)) {
             $idSites = array();
             foreach ($sites as $site) {
                 $idSites[] = $site['idsite'];
             }
             $model = new ModelSitesManager();
             $sites = $model->getSitesFromIds($idSites);
             // getPatternMatchSites does not return all sites information...
             Site::setSitesFromArray($sites);
         }
     }
     // Both calls above have called Site::setSitesFromArray. We now get these sites:
     $sitesToProblablyAdd = Site::getSites();
     return $sitesToProblablyAdd;
 }
Ejemplo n.º 19
0
 private static function getSegmentWithVisitorId()
 {
     static $cached = null;
     if ($cached === null) {
         $segment = Request::getRawSegmentFromRequest();
         if (!empty($segment)) {
             $segment = urldecode($segment) . ';';
         }
         $idVisitor = Common::getRequestVar('visitorId', false);
         if ($idVisitor === false) {
             $idVisitor = Request::processRequest('Live.getMostRecentVisitorId');
         }
         $cached = urlencode($segment . 'visitorId==' . $idVisitor);
     }
     return $cached;
 }
Ejemplo n.º 20
0
 /**
  * Returns Goals data.
  *
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param bool $segment
  * @param bool|int $idGoal
  * @param array $columns Array of metrics to fetch: nb_conversions, conversion_rate, revenue
  * @return DataTable
  */
 public function get($idSite, $period, $date, $segment = false, $idGoal = false, $columns = array())
 {
     Piwik::checkUserHasViewAccess($idSite);
     /** @var DataTable|DataTable\Map $table */
     $table = null;
     $segments = array('' => false, '_new_visit' => 'visitorType%3D%3Dnew', '_returning_visit' => VisitFrequencyAPI::RETURNING_VISITOR_SEGMENT);
     foreach ($segments as $appendToMetricName => $predefinedSegment) {
         $segmentToUse = $this->appendSegment($predefinedSegment, $segment);
         /** @var DataTable|DataTable\Map $tableSegmented */
         $tableSegmented = Request::processRequest('Goals.getMetrics', array('segment' => $segmentToUse, 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'idGoal' => $idGoal, 'columns' => $columns, 'serialize' => '0', 'format_metrics' => 'bc'));
         $tableSegmented->filter('Piwik\\Plugins\\Goals\\DataTable\\Filter\\AppendNameToColumnNames', array($appendToMetricName));
         if (!isset($table)) {
             $table = $tableSegmented;
         } else {
             $merger = new MergeDataTables();
             $merger->mergeDataTables($table, $tableSegmented);
         }
     }
     return $table;
 }
Ejemplo n.º 21
0
 private function createStartTrackingSetting()
 {
     $goals = \Piwik\API\Request::processRequest('Goals.getGoals', array('idSite' => $this->matching_site->getValue()));
     $options = array();
     foreach ($goals as $goal) {
         $options[$goal['idgoal']] = $goal['name'];
     }
     $this->matching_goals = new SystemSetting('matching_goals', 'Goals to start scoring');
     //$this->matching_goals->readableByCurrentUser = true;
     $this->matching_goals->type = static::TYPE_ARRAY;
     $this->matching_goals->uiControlType = static::CONTROL_MULTI_SELECT;
     $this->matching_goals->description = 'Goals that match our visitor.';
     $this->matching_goals->availableValues = array('0' => 'None') + $options;
     $this->addSetting($this->matching_goals);
 }
Ejemplo n.º 22
0
 private function createPluginsOrThemesView($template, $themesOnly)
 {
     Piwik::checkUserHasSuperUserAccess();
     $view = $this->configureView('@CorePluginsAdmin/' . $template);
     $view->updateNonce = Nonce::getNonce(static::UPDATE_NONCE);
     $view->activateNonce = Nonce::getNonce(static::ACTIVATE_NONCE);
     $view->uninstallNonce = Nonce::getNonce(static::UNINSTALL_NONCE);
     $view->deactivateNonce = Nonce::getNonce(static::DEACTIVATE_NONCE);
     $view->pluginsInfo = $this->getPluginsInfo($themesOnly);
     $users = Request::processRequest('UsersManager.getUsers');
     $view->otherUsersCount = count($users) - 1;
     $view->themeEnabled = \Piwik\Plugin\Manager::getInstance()->getThemeEnabled()->getPluginName();
     $view->pluginNamesHavingSettings = $this->getPluginNamesHavingSettingsForCurrentUser();
     $view->isMarketplaceEnabled = CorePluginsAdmin::isMarketplaceEnabled();
     $view->isPluginsAdminEnabled = CorePluginsAdmin::isPluginsAdminEnabled();
     $view->pluginsHavingUpdate = array();
     $view->marketplacePluginNames = array();
     if (CorePluginsAdmin::isMarketplaceEnabled()) {
         try {
             $marketplace = new Marketplace();
             $view->marketplacePluginNames = $marketplace->getAvailablePluginNames($themesOnly);
             $pluginsHavingUpdate = $marketplace->getPluginsHavingUpdate(true);
             $themesHavingUpdate = $marketplace->getPluginsHavingUpdate(false);
             $view->pluginsHavingUpdate = $pluginsHavingUpdate + $themesHavingUpdate;
         } catch (Exception $e) {
             // curl exec connection error (ie. server not connected to internet)
         }
     }
     return $view;
 }
Ejemplo n.º 23
0
 /**
  * Fetches a subtable for the report represented by this instance.
  *
  * @param int $idSubtable The subtable ID.
  * @param array $paramOverride Query parameter overrides.
  * @return DataTable
  * @api
  */
 public function fetchSubtable($idSubtable, $paramOverride = array())
 {
     $paramOverride = array('idSubtable' => $idSubtable) + $paramOverride;
     list($module, $action) = $this->getSubtableApiMethod();
     return Request::processRequest($module . '.' . $action, $paramOverride);
 }
Ejemplo n.º 24
0
 private function requestProcessedGetReport()
 {
     return Request::processRequest('API.getProcessedReport', array('idSite' => 1, 'period' => 'day', 'date' => $this->date, 'apiModule' => 'VisitsSummary', 'apiAction' => 'get'));
 }
Ejemplo n.º 25
0
 /**
  * The "Manage Users and Permissions" Admin UI screen
  */
 function index()
 {
     Piwik::checkUserIsNotAnonymous();
     $view = new View('@UsersManager/index');
     $IdSitesAdmin = APISitesManager::getInstance()->getSitesIdWithAdminAccess();
     $idSiteSelected = 1;
     if (count($IdSitesAdmin) > 0) {
         $defaultWebsiteId = $IdSitesAdmin[0];
         $idSiteSelected = Common::getRequestVar('idSite', $defaultWebsiteId);
     }
     if ($idSiteSelected === 'all') {
         $usersAccessByWebsite = array();
         $defaultReportSiteName = $this->translator->translate('UsersManager_ApplyToAllWebsites');
     } else {
         $defaultReportSiteName = Site::getNameFor($idSiteSelected);
         try {
             $usersAccessByWebsite = Request::processRequest('UsersManager.getUsersAccessFromSite', array('idSite' => $idSiteSelected));
         } catch (NoAccessException $e) {
             return $this->noAdminAccessToWebsite($idSiteSelected, $defaultReportSiteName, $e->getMessage());
         }
     }
     // we dont want to display the user currently logged so that the user can't change his settings from admin to view...
     $currentlyLogged = Piwik::getCurrentUserLogin();
     $usersLogin = APIUsersManager::getInstance()->getUsersLogin();
     foreach ($usersLogin as $login) {
         if (!isset($usersAccessByWebsite[$login])) {
             $usersAccessByWebsite[$login] = 'noaccess';
         }
     }
     unset($usersAccessByWebsite[$currentlyLogged]);
     // $usersAccessByWebsite is not supposed to contain unexistant logins, but it does when upgrading from some old Piwik version
     foreach ($usersAccessByWebsite as $login => $access) {
         if (!in_array($login, $usersLogin)) {
             unset($usersAccessByWebsite[$login]);
             continue;
         }
     }
     ksort($usersAccessByWebsite);
     $users = array();
     $superUsers = array();
     $usersAliasByLogin = array();
     $formatter = new Formatter();
     if (Piwik::isUserHasSomeAdminAccess()) {
         $view->showLastSeen = true;
         $users = APIUsersManager::getInstance()->getUsers();
         foreach ($users as $index => $user) {
             $usersAliasByLogin[$user['login']] = $user['alias'];
             $lastSeen = LastSeenTimeLogger::getLastSeenTimeForUser($user['login']);
             $users[$index]['last_seen'] = $lastSeen == 0 ? false : $formatter->getPrettyTimeFromSeconds(time() - $lastSeen);
         }
         if (Piwik::hasUserSuperUserAccess()) {
             foreach ($users as $user) {
                 if ($user['superuser_access']) {
                     $superUsers[] = $user['login'];
                 }
             }
         }
     }
     $view->anonymousHasViewAccess = $this->hasAnonymousUserViewAccess($usersAccessByWebsite);
     $view->idSiteSelected = $idSiteSelected;
     $view->defaultReportSiteName = $defaultReportSiteName;
     $view->users = $users;
     $view->superUserLogins = $superUsers;
     $view->usersAliasByLogin = $usersAliasByLogin;
     $view->usersCount = count($users) - 1;
     $view->usersAccessByWebsite = $usersAccessByWebsite;
     $websites = APISitesManager::getInstance()->getSitesWithAdminAccess();
     uasort($websites, array('Piwik\\Plugins\\UsersManager\\Controller', 'orderByName'));
     $view->websites = $websites;
     $this->setBasicVariablesView($view);
     return $view->render();
 }
Ejemplo n.º 26
0
 /**
  * Fetches the list of sites which names match the string pattern
  *
  * @param $pattern
  * @return array|string
  */
 private function getSitesIdFromPattern($pattern)
 {
     $idSites = 'all';
     if (empty($pattern)) {
         return $idSites;
     }
     $idSites = array();
     $sites = Request::processRequest('SitesManager.getPatternMatchSites', array('pattern' => $pattern, 'serialize' => 0, 'format' => 'original'));
     if (!empty($sites)) {
         foreach ($sites as $site) {
             $idSites[] = $site['idsite'];
         }
     }
     return $idSites;
 }
Ejemplo n.º 27
0
 /**
  * Returns a numeric value from the API.
  * Works only for API methods that originally returns numeric values (there is no cast here)
  *
  * @param string $methodToCall Name of method to call, eg. Referrers.getNumberOfDistinctSearchEngines
  * @param bool|string $date A custom date to use when getting the value. If false, the 'date' query
  *                                          parameter is used.
  *
  * @return int|float
  */
 protected function getNumericValue($methodToCall, $date = false)
 {
     $params = $date === false ? array() : array('date' => $date);
     $return = Request::processRequest($methodToCall, $params);
     $columns = $return->getFirstRow()->getColumns();
     return reset($columns);
 }
Ejemplo n.º 28
0
 /**
  * Get a list of all available custom variable slots (scope + index) and which names have been used so far in
  * each slot since the beginning of the website.
  *
  * @param int $idSite
  * @return array
  */
 public function getUsagesOfSlots($idSite)
 {
     Piwik::checkUserHasAdminAccess($idSite);
     $numVars = CustomVariables::getNumUsableCustomVariables();
     $usedCustomVariables = array('visit' => array_fill(1, $numVars, array()), 'page' => array_fill(1, $numVars, array()));
     /** @var DataTable $customVarUsages */
     $today = StaticContainer::get('CustomVariables.today');
     $date = '2008-12-12,' . $today;
     $customVarUsages = Request::processRequest('CustomVariables.getCustomVariables', array('idSite' => $idSite, 'period' => 'range', 'date' => $date, 'format' => 'original'));
     foreach ($customVarUsages->getRows() as $row) {
         $slots = $row->getMetadata('slots');
         if (!empty($slots)) {
             foreach ($slots as $slot) {
                 $usedCustomVariables[$slot['scope']][$slot['index']][] = array('name' => $row->getColumn('label'), 'nb_visits' => $row->getColumn('nb_visits'), 'nb_actions' => $row->getColumn('nb_actions'));
             }
         }
     }
     $grouped = array();
     foreach ($usedCustomVariables as $scope => $scopes) {
         foreach ($scopes as $index => $cvars) {
             $grouped[] = array('scope' => $scope, 'index' => $index, 'usages' => $cvars);
         }
     }
     return $grouped;
 }
Ejemplo n.º 29
0
 protected function getReferrersVisitorsByType($date = false)
 {
     if ($date === false) {
         $date = Common::getRequestVar('date', false);
     }
     // we disable the queued filters because here we want to get the visits coming from search engines
     // if the filters were applied we would have to look up for a label looking like "Search Engines"
     // which is not good when we have translations
     $dataTableReferrersType = Request::processRequest("Referrers.getReferrerType", array('disable_queued_filters' => '1', 'date' => $date));
     $nameToColumnId = array('visitorsFromSearchEngines' => Common::REFERRER_TYPE_SEARCH_ENGINE, 'visitorsFromDirectEntry' => Common::REFERRER_TYPE_DIRECT_ENTRY, 'visitorsFromWebsites' => Common::REFERRER_TYPE_WEBSITE, 'visitorsFromCampaigns' => Common::REFERRER_TYPE_CAMPAIGN);
     $return = array();
     foreach ($nameToColumnId as $nameVar => $columnId) {
         $value = 0;
         $row = $dataTableReferrersType->getRowFromLabel($columnId);
         if ($row !== false) {
             $value = $row->getColumn(Metrics::INDEX_NB_VISITS);
         }
         $return[$nameVar] = $value;
     }
     return $return;
 }
Ejemplo n.º 30
0
 public function get($idSite, $period, $date, $apiModule, $apiAction, $graphType = false, $outputType = API::GRAPH_OUTPUT_INLINE, $columns = false, $labels = false, $showLegend = true, $width = false, $height = false, $fontSize = API::DEFAULT_FONT_SIZE, $legendFontSize = false, $aliasedGraph = true, $idGoal = false, $colors = false, $textColor = API::DEFAULT_TEXT_COLOR, $backgroundColor = API::DEFAULT_BACKGROUND_COLOR, $gridColor = API::DEFAULT_GRID_COLOR, $idSubtable = false, $legendAppendMetric = true, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // Health check - should we also test for GD2 only?
     if (!SettingsServer::isGdExtensionEnabled()) {
         throw new Exception('Error: To create graphs in Piwik, please enable GD php extension (with Freetype support) in php.ini,
         and restart your web server.');
     }
     $useUnicodeFont = array('am', 'ar', 'el', 'fa', 'fi', 'he', 'ja', 'ka', 'ko', 'te', 'th', 'zh-cn', 'zh-tw');
     $languageLoaded = Translate::getLanguageLoaded();
     $font = self::getFontPath(self::DEFAULT_FONT);
     if (in_array($languageLoaded, $useUnicodeFont)) {
         $unicodeFontPath = self::getFontPath(self::UNICODE_FONT);
         $font = file_exists($unicodeFontPath) ? $unicodeFontPath : $font;
     }
     // save original GET to reset after processing. Important for API-in-API-call
     $savedGET = $_GET;
     try {
         $apiParameters = array();
         if (!empty($idGoal)) {
             $apiParameters = array('idGoal' => $idGoal);
         }
         // Fetch the metadata for given api-action
         $parameters = array('idSite' => $idSite, 'apiModule' => $apiModule, 'apiAction' => $apiAction, 'apiParameters' => $apiParameters, 'language' => $languageLoaded, 'period' => $period, 'date' => $date, 'hideMetricsDoc' => false, 'showSubtableReports' => true);
         $metadata = Request::processRequest('API.getMetadata', $parameters);
         if (!$metadata) {
             throw new Exception('Invalid API Module and/or API Action');
         }
         $metadata = $metadata[0];
         $reportHasDimension = !empty($metadata['dimension']);
         $constantRowsCount = !empty($metadata['constantRowsCount']);
         $isMultiplePeriod = Period::isMultiplePeriod($date, $period);
         if (!$reportHasDimension && !$isMultiplePeriod) {
             throw new Exception('The graph cannot be drawn for this combination of \'date\' and \'period\' parameters.');
         }
         if (empty($legendFontSize)) {
             $legendFontSize = (int) $fontSize + self::DEFAULT_LEGEND_FONT_SIZE_OFFSET;
         }
         if (empty($graphType)) {
             if ($isMultiplePeriod) {
                 $graphType = StaticGraph::GRAPH_TYPE_BASIC_LINE;
             } else {
                 if ($constantRowsCount) {
                     $graphType = StaticGraph::GRAPH_TYPE_VERTICAL_BAR;
                 } else {
                     $graphType = StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR;
                 }
             }
             $reportUniqueId = $metadata['uniqueId'];
             if (isset(self::$DEFAULT_GRAPH_TYPE_OVERRIDE[$reportUniqueId][$isMultiplePeriod])) {
                 $graphType = self::$DEFAULT_GRAPH_TYPE_OVERRIDE[$reportUniqueId][$isMultiplePeriod];
             }
         } else {
             $availableGraphTypes = StaticGraph::getAvailableStaticGraphTypes();
             if (!in_array($graphType, $availableGraphTypes)) {
                 throw new Exception(Piwik::translate('General_ExceptionInvalidStaticGraphType', array($graphType, implode(', ', $availableGraphTypes))));
             }
         }
         $width = (int) $width;
         $height = (int) $height;
         if (empty($width)) {
             $width = self::$DEFAULT_PARAMETERS[$graphType][self::WIDTH_KEY];
         }
         if (empty($height)) {
             $height = self::$DEFAULT_PARAMETERS[$graphType][self::HEIGHT_KEY];
         }
         // Cap width and height to a safe amount
         $width = min($width, self::MAX_WIDTH);
         $height = min($height, self::MAX_HEIGHT);
         $reportColumns = array_merge(!empty($metadata['metrics']) ? $metadata['metrics'] : array(), !empty($metadata['processedMetrics']) ? $metadata['processedMetrics'] : array(), !empty($metadata['metricsGoal']) ? $metadata['metricsGoal'] : array(), !empty($metadata['processedMetricsGoal']) ? $metadata['processedMetricsGoal'] : array());
         $ordinateColumns = array();
         if (empty($columns)) {
             $ordinateColumns[] = empty($reportColumns[self::DEFAULT_ORDINATE_METRIC]) ? key($metadata['metrics']) : self::DEFAULT_ORDINATE_METRIC;
         } else {
             $ordinateColumns = explode(',', $columns);
             foreach ($ordinateColumns as $column) {
                 if (empty($reportColumns[$column])) {
                     throw new Exception(Piwik::translate('ImageGraph_ColumnOrdinateMissing', array($column, implode(',', array_keys($reportColumns)))));
                 }
             }
         }
         $ordinateLabels = array();
         foreach ($ordinateColumns as $column) {
             $ordinateLabels[$column] = $reportColumns[$column];
         }
         // sort and truncate filters
         $defaultFilterTruncate = self::$DEFAULT_PARAMETERS[$graphType][self::TRUNCATE_KEY];
         switch ($graphType) {
             case StaticGraph::GRAPH_TYPE_3D_PIE:
             case StaticGraph::GRAPH_TYPE_BASIC_PIE:
                 if (count($ordinateColumns) > 1) {
                     // pChart doesn't support multiple series on pie charts
                     throw new Exception("Pie charts do not currently support multiple series");
                 }
                 $_GET['filter_sort_column'] = reset($ordinateColumns);
                 $this->setFilterTruncate($defaultFilterTruncate);
                 break;
             case StaticGraph::GRAPH_TYPE_VERTICAL_BAR:
             case StaticGraph::GRAPH_TYPE_BASIC_LINE:
                 if (!$isMultiplePeriod && !$constantRowsCount) {
                     $this->setFilterTruncate($defaultFilterTruncate);
                 }
                 break;
         }
         $ordinateLogos = array();
         // row evolutions
         if ($isMultiplePeriod && $reportHasDimension) {
             $plottedMetric = reset($ordinateColumns);
             // when no labels are specified, getRowEvolution returns the top N=filter_limit row evolutions
             // rows are sorted using filter_sort_column (see DataTableGenericFilter for more info)
             if (!$labels) {
                 $savedFilterSortColumnValue = Common::getRequestVar('filter_sort_column', '');
                 $_GET['filter_sort_column'] = $plottedMetric;
                 $savedFilterLimitValue = Common::getRequestVar('filter_limit', -1, 'int');
                 if ($savedFilterLimitValue == -1 || $savedFilterLimitValue > self::MAX_NB_ROW_LABELS) {
                     $_GET['filter_limit'] = self::DEFAULT_NB_ROW_EVOLUTIONS;
                 }
             }
             $parameters = array('idSite' => $idSite, 'period' => $period, 'date' => $date, 'apiModule' => $apiModule, 'apiAction' => $apiAction, 'label' => $labels, 'segment' => $segment, 'column' => $plottedMetric, 'language' => $languageLoaded, 'idGoal' => $idGoal, 'legendAppendMetric' => $legendAppendMetric, 'labelUseAbsoluteUrl' => false);
             $processedReport = Request::processRequest('API.getRowEvolution', $parameters);
             //@review this test will need to be updated after evaluating the @review comment in API/API.php
             if (!$processedReport) {
                 throw new Exception(Piwik::translate('General_NoDataForGraph'));
             }
             // restoring generic filter parameters
             if (!$labels) {
                 $_GET['filter_sort_column'] = $savedFilterSortColumnValue;
                 if ($savedFilterLimitValue != -1) {
                     $_GET['filter_limit'] = $savedFilterLimitValue;
                 }
             }
             // retrieve metric names & labels
             $metrics = $processedReport['metadata']['metrics'];
             $ordinateLabels = array();
             // getRowEvolution returned more than one label
             if (!array_key_exists($plottedMetric, $metrics)) {
                 $ordinateColumns = array();
                 $i = 0;
                 foreach ($metrics as $metric => $info) {
                     $ordinateColumn = $plottedMetric . '_' . $i++;
                     $ordinateColumns[] = $metric;
                     $ordinateLabels[$ordinateColumn] = $info['name'];
                     if (isset($info['logo'])) {
                         $ordinateLogo = $info['logo'];
                         // @review pChart does not support gifs in graph legends, would it be possible to convert all plugin pictures (cookie.gif, flash.gif, ..) to png files?
                         if (!strstr($ordinateLogo, '.gif')) {
                             $absoluteLogoPath = self::getAbsoluteLogoPath($ordinateLogo);
                             if (file_exists($absoluteLogoPath)) {
                                 $ordinateLogos[$ordinateColumn] = $absoluteLogoPath;
                             }
                         }
                     }
                 }
             } else {
                 $ordinateLabels[$plottedMetric] = $processedReport['label'] . ' (' . $metrics[$plottedMetric]['name'] . ')';
             }
         } else {
             $parameters = array('idSite' => $idSite, 'period' => $period, 'date' => $date, 'apiModule' => $apiModule, 'apiAction' => $apiAction, 'segment' => $segment, 'apiParameters' => false, 'idGoal' => $idGoal, 'language' => $languageLoaded, 'showTimer' => true, 'hideMetricsDoc' => false, 'idSubtable' => $idSubtable, 'showRawMetrics' => false);
             $processedReport = Request::processRequest('API.getProcessedReport', $parameters);
         }
         // prepare abscissa and ordinate series
         $abscissaSeries = array();
         $abscissaLogos = array();
         $ordinateSeries = array();
         /** @var \Piwik\DataTable\Simple|\Piwik\DataTable\Map $reportData */
         $reportData = $processedReport['reportData'];
         $hasData = false;
         $hasNonZeroValue = false;
         if (!$isMultiplePeriod) {
             $reportMetadata = $processedReport['reportMetadata']->getRows();
             $i = 0;
             // $reportData instanceof DataTable
             foreach ($reportData->getRows() as $row) {
                 // $row instanceof Row
                 $rowData = $row->getColumns();
                 // Associative Array
                 $abscissaSeries[] = Common::unsanitizeInputValue($rowData['label']);
                 foreach ($ordinateColumns as $column) {
                     $parsedOrdinateValue = $this->parseOrdinateValue($rowData[$column]);
                     $hasData = true;
                     if ($parsedOrdinateValue != 0) {
                         $hasNonZeroValue = true;
                     }
                     $ordinateSeries[$column][] = $parsedOrdinateValue;
                 }
                 if (isset($reportMetadata[$i])) {
                     $rowMetadata = $reportMetadata[$i]->getColumns();
                     if (isset($rowMetadata['logo'])) {
                         $absoluteLogoPath = self::getAbsoluteLogoPath($rowMetadata['logo']);
                         if (file_exists($absoluteLogoPath)) {
                             $abscissaLogos[$i] = $absoluteLogoPath;
                         }
                     }
                 }
                 $i++;
             }
         } else {
             // $periodsData instanceof Simple[]
             $periodsData = array_values($reportData->getDataTables());
             $periodsCount = count($periodsData);
             for ($i = 0; $i < $periodsCount; $i++) {
                 // $periodsData[$i] instanceof Simple
                 // $rows instanceof Row[]
                 if (empty($periodsData[$i])) {
                     continue;
                 }
                 $rows = $periodsData[$i]->getRows();
                 if (array_key_exists(0, $rows)) {
                     $rowData = $rows[0]->getColumns();
                     // associative Array
                     foreach ($ordinateColumns as $column) {
                         if (!isset($rowData[$column])) {
                             continue;
                         }
                         $ordinateValue = $rowData[$column];
                         $parsedOrdinateValue = $this->parseOrdinateValue($ordinateValue);
                         $hasData = true;
                         if (!empty($parsedOrdinateValue)) {
                             $hasNonZeroValue = true;
                         }
                         $ordinateSeries[$column][] = $parsedOrdinateValue;
                     }
                 } else {
                     foreach ($ordinateColumns as $column) {
                         $ordinateSeries[$column][] = 0;
                     }
                 }
                 $rowId = $periodsData[$i]->getMetadata(DataTableFactory::TABLE_METADATA_PERIOD_INDEX)->getLocalizedShortString();
                 $abscissaSeries[] = Common::unsanitizeInputValue($rowId);
             }
         }
         if (!$hasData || !$hasNonZeroValue) {
             throw new Exception(Piwik::translate('General_NoDataForGraph'));
         }
         //Setup the graph
         $graph = StaticGraph::factory($graphType);
         $graph->setWidth($width);
         $graph->setHeight($height);
         $graph->setFont($font);
         $graph->setFontSize($fontSize);
         $graph->setLegendFontSize($legendFontSize);
         $graph->setOrdinateLabels($ordinateLabels);
         $graph->setShowLegend($showLegend);
         $graph->setAliasedGraph($aliasedGraph);
         $graph->setAbscissaSeries($abscissaSeries);
         $graph->setAbscissaLogos($abscissaLogos);
         $graph->setOrdinateSeries($ordinateSeries);
         $graph->setOrdinateLogos($ordinateLogos);
         $graph->setColors(!empty($colors) ? explode(',', $colors) : array());
         $graph->setTextColor($textColor);
         $graph->setBackgroundColor($backgroundColor);
         $graph->setGridColor($gridColor);
         // when requested period is day, x-axis unit is time and all date labels can not be displayed
         // within requested width, force labels to be skipped every 6 days to delimit weeks
         if ($period == 'day' && $isMultiplePeriod) {
             $graph->setForceSkippedLabels(6);
         }
         // render graph
         $graph->renderGraph();
     } catch (\Exception $e) {
         $graph = new \Piwik\Plugins\ImageGraph\StaticGraph\Exception();
         $graph->setWidth($width);
         $graph->setHeight($height);
         $graph->setFont($font);
         $graph->setFontSize($fontSize);
         $graph->setBackgroundColor($backgroundColor);
         $graph->setTextColor($textColor);
         $graph->setException($e);
         $graph->renderGraph();
     }
     // restoring get parameters
     $_GET = $savedGET;
     switch ($outputType) {
         case self::GRAPH_OUTPUT_FILE:
             if ($idGoal != '') {
                 $idGoal = '_' . $idGoal;
             }
             $fileName = self::$DEFAULT_PARAMETERS[$graphType][self::FILENAME_KEY] . '_' . $apiModule . '_' . $apiAction . $idGoal . ' ' . str_replace(',', '-', $date) . ' ' . $idSite . '.png';
             $fileName = str_replace(array(' ', '/'), '_', $fileName);
             if (!Filesystem::isValidFilename($fileName)) {
                 throw new Exception('Error: Image graph filename ' . $fileName . ' is not valid.');
             }
             return $graph->sendToDisk($fileName);
         case self::GRAPH_OUTPUT_PHP:
             return $graph->getRenderedImage();
         case self::GRAPH_OUTPUT_INLINE:
         default:
             $graph->sendToBrowser();
             exit;
     }
 }