function test_callableApiMethods_doNotFail() { Piwik::createConfigObject(); Piwik_Config::getInstance()->setTestEnvironment(); Piwik::createLogObject(); Piwik::createAccessObject(); Piwik::createDatabaseObject(); Piwik::setUserIsSuperUser(); Piwik_Translate::getInstance()->loadEnglishTranslation(); $pluginsManager = Piwik_PluginsManager::getInstance(); $pluginsManager->loadPlugins(Piwik_Config::getInstance()->Plugins['Plugins']); Piwik_SitesManager_API::getInstance()->addSite("name", "http://example.org"); $apiGenerator = new Piwik_API_DocumentationGenerator_CallAllMethods(); $requestUrls = $apiGenerator->getAllRequestsWithParameters(); $this->assertTrue(count($requestUrls) > 20); foreach ($requestUrls as $url) { $call = new Piwik_API_Request($url); $output = $call->process(); // var_dump($url); // var_dump($output); $this->assertTrue(!empty($output)); } Piwik_Translate::getInstance()->unloadEnglishTranslation(); $this->pass(); }
/** * Add the main metrics (pageviews, exits, bounces) to the full report. * Data is loaded from Actions.getPageUrls using the label filter. */ private function addMainPageMetricsToReport(&$report, $pageUrl, $idSite, $period, $date, $segment) { $label = Piwik_Actions::getActionExplodedNames($pageUrl, Piwik_Tracker_Action::TYPE_ACTION_URL); if (count($label) == 1) { $label = $label[0]; } else { $label = array_map('urlencode', $label); $label = implode('>', $label); } $parameters = array('method' => 'Actions.getPageUrls', 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'label' => $label, 'format' => 'original', 'serialize' => '0', 'expanded' => '0'); if (!empty($segment)) { $parameters['segment'] = $segment; } $url = Piwik_Url::getQueryStringFromParameters($parameters); $request = new Piwik_API_Request($url); try { /** @var $dataTable Piwik_DataTable */ $dataTable = $request->process(); } catch (Exception $e) { throw new Exception("Actions.getPageUrls returned an error: " . $e->getMessage() . "\n"); } if ($dataTable->getRowsCount() == 0) { throw new Exception("The label '{$label}' could not be found in Actions.getPageUrls\n"); } $row = $dataTable->getFirstRow(); if ($row !== false) { $report['pageMetrics'] = array('pageviews' => intval($row->getColumn('nb_hits')), 'exits' => intval($row->getColumn('exit_nb_visits')), 'bounces' => intval($row->getColumn('entry_bounce_count'))); } else { $report['pageMetrics'] = array('pageviews' => 0, 'exits' => 0, 'bounces' => 0); } }
function worldMap() { if (!Piwik_PluginsManager::getInstance()->isPluginActivated('UserCountry')) { return ''; } $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); Piwik::checkUserHasViewAccess($idSite); $period = Piwik_Common::getRequestVar('period'); $date = Piwik_Common::getRequestVar('date'); $token_auth = Piwik::getCurrentUserTokenAuth(); $view = Piwik_View::factory('worldmap'); $view->dataUrl = "?module=API" . "&method=API.getProcessedReport&format=XML" . "&apiModule=UserCountry&apiAction=getCountry" . "&idSite=" . $idSite . "&period=" . $period . "&date=" . $date . "&token_auth=" . $token_auth . "&segment=" . Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('segment', '')) . "&filter_limit=-1"; // definition of the color scale $view->hueMin = 218; $view->hueMax = 216; $view->satMin = "0.285"; $view->satMax = "0.9"; $view->lgtMin = ".97"; $view->lgtMax = ".44"; $request = new Piwik_API_Request('method=API.getMetadata&format=PHP' . '&apiModule=UserCountry&apiAction=getCountry' . '&idSite=' . $idSite . '&period=' . $period . '&date=' . $date . '&token_auth=' . $token_auth . '&filter_limit=-1'); $metaData = $request->process(); $metrics = array(); foreach ($metaData[0]['metrics'] as $id => $val) { if (Piwik_Common::getRequestVar('period') == 'day' || $id != 'nb_uniq_visitors') { $metrics[] = array($id, $val); } } foreach ($metaData[0]['processedMetrics'] as $id => $val) { $metrics[] = array($id, $val); } $view->metrics = $metrics; $view->defaultMetric = 'nb_visits'; echo $view->render(); }
function index() { $view = new Piwik_View('Goals/templates/overview.tpl'); $view->currency = Piwik::getCurrency(); $view->title = 'All goals - evolution'; $view->graphEvolution = $this->getEvolutionGraph(true, array(Piwik_Goals::getRecordName('nb_conversions'))); $view->nameGraphEvolution = 'GoalsgetEvolutionGraph'; // sparkline for the historical data of the above values $view->urlSparklineConversions = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array(Piwik_Goals::getRecordName('nb_conversions')))); $view->urlSparklineConversionRate = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array(Piwik_Goals::getRecordName('conversion_rate')))); $view->urlSparklineRevenue = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array(Piwik_Goals::getRecordName('revenue')))); $request = new Piwik_API_Request("method=Goals.get&format=original"); $datatable = $request->process(); $dataRow = $datatable->getFirstRow(); $view->nb_conversions = $dataRow->getColumn('Goal_nb_conversions'); $view->conversion_rate = $dataRow->getColumn('Goal_conversion_rate'); $view->revenue = $dataRow->getColumn('Goal_revenue'); $goalMetrics = array(); foreach ($this->goals as $idGoal => $goal) { $goalMetrics[$idGoal] = $this->getMetricsForGoal($idGoal); $goalMetrics[$idGoal]['name'] = $goal['name']; } $view->goalMetrics = $goalMetrics; $view->goals = $this->goals; $view->goalsJSON = json_encode($this->goals); $view->userCanEditGoals = Piwik::isUserHasAdminAccess($this->idSite); echo $view->render(); }
function _processRequest($request) { $token_auth = self::_getToken(); $request = new Piwik_API_Request($request . "&format=php&token_auth=" . $token_auth); $result = $request->process(); $content = unserialize($result); return $content; }
static public function getVisits() { $requestString = "method=VisitsSummary.getVisits". "&format=original". "&disable_generic_filters=1"; $request = new Piwik_API_Request($requestString); return $request->process(); }
function index() { // when calling the API through http, we limit the number of returned results if (!isset($_GET['filter_limit'])) { $_GET['filter_limit'] = Zend_Registry::get('config')->General->API_datatable_default_limit; } $request = new Piwik_API_Request('token_auth=' . Piwik_Common::getRequestVar('token_auth', 'anonymous', 'string')); echo $request->process(); }
public function getLastVisitsStart($fetch = false) { // hack, ensure we load today's visits by default $_GET['date'] = 'today'; $_GET['period'] = 'day'; $view = Piwik_View::factory('lastVisits'); $view->idSite = $this->idSite; $api = new Piwik_API_Request("method=Live.getLastVisitsDetails&idSite={$this->idSite}&filter_limit=10&format=php&serialize=0&disable_generic_filters=1"); $visitors = $api->process(); $view->visitors = $visitors; return $this->render($view, $fetch); }
/** Render the area left of the iframe */ public function renderSidebar() { $idSite = Piwik_Common::getRequestVar('idSite'); $period = Piwik_Common::getRequestVar('period'); $date = Piwik_Common::getRequestVar('date'); $currentUrl = Piwik_Common::getRequestVar('currentUrl'); $currentUrl = Piwik_Common::unsanitizeInputValue($currentUrl); $normalizedCurrentUrl = Piwik_Tracker_Action::excludeQueryParametersFromUrl($currentUrl, $idSite); $normalizedCurrentUrl = Piwik_Common::unsanitizeInputValue($normalizedCurrentUrl); // load the appropriate row of the page urls report using the label filter Piwik_Actions_ArchivingHelper::reloadConfig(); $path = Piwik_Actions_ArchivingHelper::getActionExplodedNames($normalizedCurrentUrl, Piwik_Tracker_Action::TYPE_ACTION_URL); $path = array_map('urlencode', $path); $label = implode('>', $path); $request = new Piwik_API_Request('method=Actions.getPageUrls' . '&idSite=' . urlencode($idSite) . '&date=' . urlencode($date) . '&period=' . urlencode($period) . '&label=' . urlencode($label) . '&format=original'); $dataTable = $request->process(); $data = array(); if ($dataTable->getRowsCount() > 0) { $row = $dataTable->getFirstRow(); $translations = Piwik_API_API::getDefaultMetricTranslations(); $showMetrics = array('nb_hits', 'nb_visits', 'nb_uniq_visitors', 'bounce_rate', 'exit_rate', 'avg_time_on_page'); foreach ($showMetrics as $metric) { $value = $row->getColumn($metric); if ($value === false) { // skip unique visitors for period != day continue; } if ($metric == 'avg_time_on_page') { $value = Piwik::getPrettyTimeFromSeconds($value); } $data[] = array('name' => $translations[$metric], 'value' => $value); } } // generate page url string foreach ($path as &$part) { $part = preg_replace(';^/;', '', urldecode($part)); } $page = '/' . implode('/', $path); $page = preg_replace(';/index$;', '/', $page); if ($page == '/') { $page = '/index'; } // render template $view = Piwik_View::factory('sidebar'); $view->data = $data; $view->location = $page; $view->normalizedUrl = $normalizedCurrentUrl; $view->label = $label; $view->idSite = $idSite; $view->period = $period; $view->date = $date; echo $view->render(); }
protected function buildView() { // access control $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); Piwik_API_Request::reloadAuthUsingTokenAuth(); if (!Piwik::isUserHasViewAccess($idSite)) { throw new Exception(Piwik_TranslateException('General_ExceptionPrivilegeAccessWebsite', array("'view'", $idSite))); } // collect data $this->parametersToModify['action'] = $this->currentControllerAction; $this->parametersToModify = array_merge($this->variablesDefault, $this->parametersToModify); $this->graphData = $this->getGraphData(); // build view $view = new Piwik_View($this->dataTableTemplate); $view->width = $this->width; $view->height = $this->height; $view->chartDivId = $this->getUniqueIdViewDataTable() . "Chart"; $view->graphType = $this->graphType; $view->data = $this->graphData; $view->isDataAvailable = strpos($this->graphData, '"series":[]') === false; $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet(); $view->properties = $this->getViewProperties(); $view->reportDocumentation = $this->getReportDocumentation(); return $view; }
protected function buildView() { $view = new Piwik_View($this->dataTableTemplate); $this->uniqueIdViewDataTable = $this->getUniqueIdViewDataTable(); $view->graphType = $this->graphType; $this->chartDivId = $this->uniqueIdViewDataTable . "Chart_swf"; $this->parametersToModify['action'] = $this->currentControllerAction; $this->parametersToModify = array_merge($this->variablesDefault, $this->parametersToModify); $url = Piwik_Url::getCurrentQueryStringWithParametersModified($this->parametersToModify); $this->includeData = !Zend_Registry::get('config')->Debug->disable_merged_requests; $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); Piwik_API_Request::reloadAuthUsingTokenAuth(); if (!Piwik::isUserHasViewAccess($idSite)) { throw new Exception(Piwik_TranslateException('General_ExceptionPrivilegeAccessWebsite', array("'view'", $idSite))); } if ($this->includeData) { $this->chartData = $this->getFlashData(); } else { $this->chartData = null; } $view->flashParameters = $this->getFlashParameters(); $view->urlGraphData = $url; $view->chartDivId = $this->chartDivId; $view->formEmbedId = "formEmbed" . $this->uniqueIdViewDataTable; $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet(); $view->properties = $this->getViewProperties(); return $view; }
function getLastVisits($fetch = false) { $idSite = Piwik_Common::getRequestVar('idSite', null, 'int'); $minIdVisit = Piwik_Common::getRequestVar('minIdVisit', 0, 'int'); $limit = 10; $api = new Piwik_API_Request("method=Live.getLastVisits&idSite={$idSite}&limit={$limit}&minIdVisit={$minIdVisit}&format=php&serialize=0&disable_generic_filters=1"); $view = new Piwik_View('Live/templates/lastVisits.tpl'); $visitors = $api->process(); if ($minIdVisit == 0) { $visitors = array_slice($visitors, 3); } $view->visitors = $visitors; $rendered = $view->render($fetch); if ($fetch) { return $rendered; } echo $rendered; }
public function oneClickResults() { Piwik_API_Request::reloadAuthUsingTokenAuth($_POST); Piwik::checkUserIsSuperUser(); $view = Piwik_View::factory('update_one_click_results'); $view->coreError = Piwik_Common::getRequestVar('error', '', 'string', $_POST); $view->feedbackMessages = safe_unserialize(Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('messages', '', 'string', $_POST))); echo $view->render(); }
/** * @depends testApi * @dataProvider getAnotherApiForTesting * @group Integration * @group VisitsInPast_InvalidateOldReports */ public function testAnotherApi($api, $params) { // 1) Invalidate old reports for the 2 websites // Test invalidate 1 date only $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=4,5,6,55,-1,s',1&dates=2010-01-03"); $r->process(); // Test invalidate comma separated dates $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . self::$idSite . "," . self::$idSite2 . "&dates=2010-01-06,2009-10-30"); $r->process(); // test invalidate date in the past $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . self::$idSite2 . "&dates=2009-06-29"); $r->process(); // invalidate a date more recent to check the date is only updated when it's earlier than current $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . self::$idSite2 . "&dates=2010-03-03"); $r->process(); // 2) Call API again, with an older date, which should now return data $this->runApiTests($api, $params); }
function test_callableApiMethods_doNotFail() { Piwik::createConfigObject(); Piwik::createLogObject(); Piwik::createAccessObject(); Piwik::createDatabaseObject(); Piwik::setUserIsSuperUser(); $pluginsManager = Piwik_PluginsManager::getInstance(); $pluginsManager->setPluginsToLoad(Zend_Registry::get('config')->Plugins->Plugins->toArray()); $apiGenerator = new Piwik_API_DocumentationGenerator_CallAllMethods(); $requestUrls = $apiGenerator->getAllRequestsWithParameters(); $this->assertTrue(count($requestUrls) > 20); foreach ($requestUrls as $url) { $call = new Piwik_API_Request($url); $output = $call->process(); // var_dump($url); // var_dump($output); $this->assertTrue(!empty($output)); } $this->pass(); }
/** * This is called after getApiToTest() * WE invalidate old reports and check that data is now returned for old dates */ public function getAnotherApiToTest() { // 1) Invalidate old reports for the 2 websites // Test invalidate 1 date only $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports\n\t\t\t&idSites=4,5,6,55,-1,s',1&dates=2010-01-03"); $r->process(); // Test invalidate comma separated dates $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports\n\t\t\t&idSites=" . $this->idSite . "," . $this->idSite2 . "&dates=2010-01-06,2009-10-30"); $r->process(); // test invalidate date in the past $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports\n\t\t\t&idSites=" . $this->idSite2 . "&dates=2009-06-29"); $r->process(); // invalidate a date more recent to check the date is only updated when it's earlier than current $r = new Piwik_API_Request("module=API&method=CoreAdminHome.invalidateArchivedReports\n\t\t\t&idSites=" . $this->idSite2 . "&dates=2010-03-03"); $r->process(); // 2) Call API again, with an older date, which should now return data // website 1 $this->tests[0][1]['testSuffix'] = 'Website' . $this->idSite . '_OldReportsShouldAppear'; // website2 $this->tests[1][1]['testSuffix'] = 'Website' . $this->idSite2 . '_OldReportsShouldAppear'; return $this->tests; }
function iframe() { Piwik_API_Request::reloadAuthUsingTokenAuth(); $this->init(); $controllerName = Piwik_Common::getRequestVar('moduleToWidgetize'); $actionName = Piwik_Common::getRequestVar('actionToWidgetize'); $parameters = array ( $fetch = true ); $outputDataTable = Piwik_FrontController::getInstance()->fetchDispatch( $controllerName, $actionName, $parameters); $view = Piwik_View::factory('iframe'); $this->setGeneralVariablesView($view); $view->content = $outputDataTable; echo $view->render(); }
/** * Hook called after the dataTable has been loaded from the API * Can be used to add, delete or modify the data freshly loaded */ protected function postDataTableLoadedFromAPI() { if (empty($this->dataTable)) { return false; } // First, filters that delete rows foreach ($this->queuedFiltersPriority as $filter) { $filterName = $filter[0]; $filterParameters = $filter[1]; $this->dataTable->filter($filterName, $filterParameters); } if (0 == Piwik_Common::getRequestVar('disable_generic_filters', '0', 'string')) { // Second, generic filters (Sort, Limit, Replace Column Names, etc.) $requestString = $this->getRequestString(); $request = Piwik_API_Request::getRequestArrayFromString($requestString); if (!empty($this->variablesDefault['enable_sort']) && $this->variablesDefault['enable_sort'] === 'false') { $request['filter_sort_column'] = $request['filter_sort_order'] = ''; } $genericFilter = new Piwik_API_DataTableGenericFilter($request); $genericFilter->filter($this->dataTable); } // Finally, apply datatable filters that were queued (should be 'presentation' filters that do not affect the number of rows) foreach ($this->queuedFilters as $filter) { $filterName = $filter[0]; $filterParameters = $filter[1]; $this->dataTable->filter($filterName, $filterParameters); } }
/** * 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. Referers.getNumberOfDistinctSearchEngines * @return int|float */ protected function getNumericValue($methodToCall) { $requestString = 'method=' . $methodToCall . '&format=original'; $request = new Piwik_API_Request($requestString); return $request->process(); }
/** @return Piwik_DataTable_Array */ private function loadRowEvolutionData($idSite, $period, $date, $apiModule, $apiAction, $label, $segment) { if ($period == 'range') { // load days in the range $period = 'day'; } $parameters = array('method' => $apiModule . '.' . $apiAction, 'label' => $label, 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'format' => 'original', 'serialize' => '0', 'segment' => $segment); // add "processed metrics" like actions per visit or bounce rate if ($apiModule != 'Actions') { $parameters['filter_add_columns_when_show_all_columns'] = '1'; } $url = Piwik_Url::getQueryStringFromParameters($parameters); $request = new Piwik_API_Request($url); try { $dataTable = $request->process(); } catch (Exception $e) { throw new Exception("API returned an error: " . $e->getMessage() . "\n"); } if (!$dataTable instanceof Piwik_DataTable_Array) { throw new Exception("API didn't return a DataTable array. Maybe you used " . "a single date (i.e. not YYYY-MM-DD,YYYY-MM-DD)"); } return $dataTable; }
/** * Installation Step 7: Configure first web-site */ public function firstWebsiteSetup() { $this->checkPreviousStepIsValid( __FUNCTION__ ); $view = new Piwik_Installation_View( $this->pathView . 'firstWebsiteSetup.tpl', $this->getInstallationSteps(), __FUNCTION__ ); $this->skipThisStep( __FUNCTION__ ); $form = new Piwik_Installation_FormFirstWebsiteSetup(); if( !isset($this->session->generalSetupSuccessMessage)) { $view->displayGeneralSetupSuccess = true; $this->session->generalSetupSuccessMessage = true; } $this->initObjectsToCallAPI(); if($form->validate()) { $name = urlencode($form->getSubmitValue('siteName')); $url = urlencode($form->getSubmitValue('url')); $ecommerce = (int)$form->getSubmitValue('ecommerce'); $request = new Piwik_API_Request(" method=SitesManager.addSite &siteName=$name &urls=$url &ecommerce=$ecommerce &format=original "); try { $result = $request->process(); $this->session->site_idSite = $result; $this->session->site_name = $name; $this->session->site_url = $url; $this->redirectToNextStep( __FUNCTION__ ); } catch(Exception $e) { $view->errorMessage = $e->getMessage(); } } $view->addForm($form); echo $view->render(); }
protected function loadEvolutionReport($column = false) { list($apiModule, $apiAction) = explode('.', $this->apiMethod); $parameters = array('method' => 'API.getRowEvolution', 'label' => $this->label, 'apiModule' => $apiModule, 'apiAction' => $apiAction, 'idSite' => $this->idSite, 'period' => $this->period, 'date' => $this->date, 'format' => 'original', 'serialize' => '0'); if (!empty($this->segment)) { $parameters['segment'] = $this->segment; } if ($column !== false) { $parameters['column'] = $column; } $url = Piwik_Url::getQueryStringFromParameters($parameters); $request = new Piwik_API_Request($url); $report = $request->process(); $this->extractEvolutionReport($report); }
protected function getSummary() { $requestString = "method=VisitFrequency.get&format=original"; $request = new Piwik_API_Request($requestString); return $request->process(); }
/** * Performs multiple API requests at once and returns every result. * * @param array $urls The array of API requests. */ public function getBulkRequest($urls) { if (empty($urls)) { return array(); } $urls = Piwik_Common::unsanitizeInputValues($urls); $result = array(); foreach ($urls as $url) { $req = new Piwik_API_Request($url); $result[] = $req->process(); } return $result; }
protected function getMetricsForFunnel($idFunnel) { $request = new Piwik_API_Request("method=Funnels.get&format=original&idFunnel={$idFunnel}"); $dataTable = $request->process(); $dataRow = $dataTable->getFirstRow(); return $dataRow; }
public function getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters = false, $idGoal = false, $language = false, $showTimer = true) { $timer = new Piwik_Timer(); if ($apiParameters === false) { $apiParameters = array(); } if (!empty($idGoal) && empty($apiParameters['idGoal'])) { $apiParameters['idGoal'] = $idGoal; } // Is this report found in the Metadata available reports? $reportMetadata = $this->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, $period, $date); if (empty($reportMetadata)) { throw new Exception("Requested report {$apiModule}.{$apiAction} for Website id={$idSite} not found in the list of available reports. \n"); } $reportMetadata = reset($reportMetadata); // Generate Api call URL passing custom parameters $parameters = array_merge($apiParameters, array('method' => $apiModule . '.' . $apiAction, 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'format' => 'original', 'serialize' => '0', 'language' => $language)); if (!empty($segment)) { $parameters['segment'] = $segment; } $url = Piwik_Url::getQueryStringFromParameters($parameters); $request = new Piwik_API_Request($url); try { /** @var Piwik_DataTable */ $dataTable = $request->process(); } catch (Exception $e) { throw new Exception("API returned an error: " . $e->getMessage() . "\n"); } list($newReport, $columns, $rowsMetadata) = $this->handleTableReport($idSite, $dataTable, $reportMetadata, isset($reportMetadata['dimension'])); foreach ($columns as $columnId => &$name) { $name = ucfirst($name); } $website = new Piwik_Site($idSite); // $segment = new Piwik_Segment($segment, $idSite); if (Piwik_Archive::isMultiplePeriod($date, $period)) { $period = new Piwik_Period_Range($period, $date); } else { if ($period == 'range') { $period = new Piwik_Period_Range($period, $date); } else { $period = Piwik_Period::factory($period, Piwik_Date::factory($date)); } } $period = $period->getLocalizedLongString(); $return = array('website' => $website->getName(), 'prettyDate' => $period, 'metadata' => $reportMetadata, 'columns' => $columns, 'reportData' => $newReport, 'reportMetadata' => $rowsMetadata); if ($showTimer) { $return['timerMillis'] = $timer->getTimeMs(0); } return $return; }
protected function buildView() { // access control $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); Piwik_API_Request::reloadAuthUsingTokenAuth(); if (!Piwik::isUserHasViewAccess($idSite)) { throw new Exception(Piwik_TranslateException('General_ExceptionPrivilegeAccessWebsite', array("'view'", $idSite))); } // collect data $this->parametersToModify['action'] = $this->currentControllerAction; $this->parametersToModify = array_merge($this->variablesDefault, $this->parametersToModify); $this->graphData = $this->getGraphData(); // build view $view = new Piwik_View($this->dataTableTemplate); $view->width = $this->width; $view->height = $this->height; $view->chartDivId = $this->getUniqueIdViewDataTable() . "Chart"; $view->graphType = $this->graphType; $view->data = $this->graphData; $view->isDataAvailable = strpos($this->graphData, '"series":[]') === false; $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet(); $view->properties = $this->getViewProperties(); $view->reportDocumentation = $this->getReportDocumentation(); // if it's likely that the report data for this data table has been purged, // set whether we should display a message to that effect. $view->showReportDataWasPurgedMessage = $this->hasReportBeenPurged(); $view->deleteReportsOlderThan = Piwik_GetOption('delete_reports_older_than'); return $view; }
<?php // if you don't include 'index.php', you must also define PIWIK_DOCUMENT_ROOT // and include "libs/upgradephp/upgrade.php" and "core/Loader.php" define('PIWIK_INCLUDE_PATH', realpath('..')); define('PIWIK_USER_PATH', realpath('..')); define('PIWIK_ENABLE_DISPATCH', false); define('PIWIK_ENABLE_ERROR_HANDLER', false); define('PIWIK_ENABLE_SESSION_START', false); require_once PIWIK_INCLUDE_PATH . "/index.php"; require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php"; Piwik_FrontController::getInstance()->init(); // This inits the API Request with the specified parameters $request = new Piwik_API_Request(' method=UserSettings.getResolution &idSite=7 &date=yesterday &period=week &format=XML &filter_limit=3 &token_auth=anonymous '); // Calls the API and fetch XML data back $result = $request->process(); echo $result;
protected function getReferersVisitorsByType() { // 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 $requestString = "method=Referers.getRefererType\n\t\t\t\t\t\t&format=original\n\t\t\t\t\t\t&disable_queued_filters=1"; $request = new Piwik_API_Request($requestString); $dataTableReferersType = $request->process(); $nameToColumnId = array('visitorsFromSearchEngines' => Piwik_Common::REFERER_TYPE_SEARCH_ENGINE, 'visitorsFromDirectEntry' => Piwik_Common::REFERER_TYPE_DIRECT_ENTRY, 'visitorsFromWebsites' => Piwik_Common::REFERER_TYPE_WEBSITE, 'visitorsFromCampaigns' => Piwik_Common::REFERER_TYPE_CAMPAIGN); $return = array(); foreach ($nameToColumnId as $nameVar => $columnId) { $value = 0; $row = $dataTableReferersType->getRowFromLabel($columnId); if ($row !== false) { $value = $row->getColumn(Piwik_Archive::INDEX_NB_VISITS); } $return[$nameVar] = $value; } return $return; }
/** * Function called by the ViewDataTable objects in order to fetch data from the API. * The function init() must have been called before, so that the object knows which API module and action to call. * It builds the API request string and uses Piwik_API_Request to call the API. * The requested Piwik_DataTable object is stored in $this->dataTable. * @return void */ protected function loadDataTableFromAPI() { // we build the request string (URL) to call the API $requestString = $this->getRequestString(); // we make the request to the API $request = new Piwik_API_Request($requestString); // and get the DataTable structure $dataTable = $request->process(); $this->dataTable = $dataTable; }