process() публичный Метод

Post-processing includes: - flattening if **flat** is 0 - running generic filters unless **disable_generic_filters** is set to 1 - URL decoding label column values - running queued filters unless **disable_queued_filters** is set to 1 - removing columns based on the values of the **hideColumns** and **showColumns** query parameters - filtering rows if the **label** query parameter is set - converting the result to the appropriate format (ie, XML, JSON, etc.) If 'original' is supplied for the output format, the result is returned as a PHP object.
public process ( ) : DataTable | Map | string
Результат Piwik\DataTable | Map | string The data resulting from the API call.
 /**
  * @depends      testApi
  * @dataProvider getAnotherApiForTesting
  */
 public function testAnotherApi($api, $params)
 {
     $idSite = self::$fixture->idSite;
     $idSite2 = self::$fixture->idSite2;
     // 1) Invalidate old reports for the 2 websites
     // Test invalidate 1 date only
     $r = new Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=4,5,6,55,-1,s',1&dates=2010-01-03");
     $this->assertApiResponseHasNoError($r->process());
     // Test invalidate comma separated dates
     $r = new Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . $idSite . "," . $idSite2 . "&dates=2010-01-06,2009-10-30");
     $this->assertApiResponseHasNoError($r->process());
     // test invalidate date in the past
     // Format=original will re-throw exception
     $r = new Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . $idSite2 . "&dates=2009-06-29&format=original");
     $this->assertApiResponseHasNoError($r->process());
     // invalidate a date more recent to check the date is only updated when it's earlier than current
     $r = new Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . $idSite2 . "&dates=2010-03-03");
     $this->assertApiResponseHasNoError($r->process());
     // Make an invalid call
     $idSiteNoAccess = 777;
     try {
         $request = new Request("module=API&method=CoreAdminHome.invalidateArchivedReports&idSites=" . $idSiteNoAccess . "&dates=2010-03-03&format=original");
         $request->process();
         $this->fail();
     } catch (Exception $e) {
     }
     // 2) Call API again, with an older date, which should now return data
     $this->runApiTests($api, $params);
 }
Пример #2
0
 /** Render the area left of the iframe */
 public function renderSidebar()
 {
     $idSite = Common::getRequestVar('idSite');
     $period = Common::getRequestVar('period');
     $date = Common::getRequestVar('date');
     $currentUrl = Common::getRequestVar('currentUrl');
     $currentUrl = Common::unsanitizeInputValue($currentUrl);
     $normalizedCurrentUrl = PageUrl::excludeQueryParametersFromUrl($currentUrl, $idSite);
     $normalizedCurrentUrl = Common::unsanitizeInputValue($normalizedCurrentUrl);
     // load the appropriate row of the page urls report using the label filter
     ArchivingHelper::reloadConfig();
     $path = ArchivingHelper::getActionExplodedNames($normalizedCurrentUrl, Action::TYPE_PAGE_URL);
     $path = array_map('urlencode', $path);
     $label = implode('>', $path);
     $request = new Request('method=Actions.getPageUrls' . '&idSite=' . urlencode($idSite) . '&date=' . urlencode($date) . '&period=' . urlencode($period) . '&label=' . urlencode($label) . '&format=original' . '&format_metrics=0');
     $dataTable = $request->process();
     $formatter = new Metrics\Formatter\Html();
     $data = array();
     if ($dataTable->getRowsCount() > 0) {
         $row = $dataTable->getFirstRow();
         $translations = Metrics::getDefaultMetricTranslations();
         $showMetrics = array('nb_hits', 'nb_visits', 'nb_users', '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 == 'bounce_rate' || $metric == 'exit_rate') {
                 $value = $formatter->getPrettyPercentFromQuotient($value);
             } else {
                 if ($metric == 'avg_time_on_page') {
                     $value = $formatter->getPrettyTimeFromSeconds($value, $displayAsSentence = true);
                 }
             }
             $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 = new View('@Overlay/renderSidebar');
     $view->data = $data;
     $view->location = $page;
     $view->normalizedUrl = $normalizedCurrentUrl;
     $view->label = $label;
     $view->idSite = $idSite;
     $view->period = $period;
     $view->date = $date;
     $this->outputCORSHeaders();
     return $view->render();
 }
Пример #3
0
 public static function loadFromApi($params, $requestUrl)
 {
     $testRequest = new Request($requestUrl);
     // Cast as string is important. For example when calling
     // with format=original, objects or php arrays can be returned.
     $response = (string) $testRequest->process();
     return new Response($response, $params, $requestUrl);
 }
Пример #4
0
 public static function loadFromApi($params, $requestUrl)
 {
     $testRequest = new Request($requestUrl);
     // Cast as string is important. For example when calling
     // with format=original, objects or php arrays can be returned.
     // we also hide errors to prevent the 'headers already sent' in the ResponseBuilder (which sends Excel headers multiple times eg.)
     $response = (string) $testRequest->process();
     return new TestRequestResponse($response, $params, $requestUrl);
 }
Пример #5
0
 function index()
 {
     // when calling the API through http, we limit the number of returned results
     if (!isset($_GET['filter_limit'])) {
         $_GET['filter_limit'] = Config::getInstance()->General['API_datatable_default_limit'];
     }
     $request = new Request('token_auth=' . Common::getRequestVar('token_auth', 'anonymous', 'string'));
     return $request->process();
 }
Пример #6
0
 /**
  * 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 Request to call the API.
  * The requested DataTable object is stored in $this->dataTable.
  */
 public function loadDataTableFromAPI()
 {
     // we build the request (URL) to call the API
     $requestArray = $this->getRequestArray();
     // we make the request to the API
     $request = new ApiRequest($requestArray);
     // and get the DataTable structure
     $dataTable = $request->process();
     return $dataTable;
 }
Пример #7
0
 public function test_process_shouldKeepSuperUserPermission_IfAccessWasManuallySet()
 {
     $this->access->setSuperUserAccess(true);
     $this->assertAccessReloadedAndRestored('difFenrenT');
     $request = new Request(array('method' => 'API.getPiwikVersion', 'token_auth' => 'difFenrenT'));
     $request->process();
     // make sure token auth was restored after it was loaded with difFenrenT
     $this->assertSameUserAsBeforeIsAuthenticated();
     $this->assertTrue($this->access->hasSuperUserAccess());
 }
Пример #8
0
 /**
  * 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 Request to call the API.
  * The requested DataTable object is stored in $this->dataTable.
  */
 public function loadDataTableFromAPI($fixedRequestParams = array())
 {
     // we build the request (URL) to call the API
     $requestArray = $this->getRequestArray();
     foreach ($fixedRequestParams as $key => $value) {
         $requestArray[$key] = $value;
     }
     // we make the request to the API
     $request = new ApiRequest($requestArray);
     // and get the DataTable structure
     $dataTable = $request->process();
     return $dataTable;
 }
Пример #9
0
 public function getLastVisitsStart()
 {
     // hack, ensure we load today's visits by default
     $_GET['date'] = 'today';
     \Piwik\Period\Factory::checkPeriodIsEnabled('day');
     $_GET['period'] = 'day';
     $view = new View('@Live/getLastVisitsStart');
     $view->idSite = $this->idSite;
     $api = new 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);
 }
Пример #10
0
 public function requestReport($idSite, $period, $date, $reportUniqueId, $metric, $segment)
 {
     $report = $this->getReportByUniqueId($idSite, $reportUniqueId);
     $params = array('method' => $report['module'] . '.' . $report['action'], 'format' => 'original', 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'filter_limit' => 1000, 'showColumns' => $metric);
     if (!empty($segment)) {
         $params['segment'] = $segment;
     }
     if (!empty($report['parameters']) && is_array($report['parameters'])) {
         $params = array_merge($params, $report['parameters']);
     }
     $request = new ApiRequest($params);
     $table = $request->process();
     return $table;
 }
Пример #11
0
 function index()
 {
     $token = 'token_auth=' . Common::getRequestVar('token_auth', 'anonymous', 'string');
     // when calling the API through http, we limit the number of returned results
     if (!isset($_GET['filter_limit'])) {
         $_GET['filter_limit'] = Config::getInstance()->General['API_datatable_default_limit'];
         $token .= '&api_datatable_default_limit=' . $_GET['filter_limit'];
     }
     $request = new Request($token);
     $response = $request->process();
     if (is_array($response)) {
         $response = var_export($response, true);
     }
     return $response;
 }
Пример #12
0
 public function beforeRender()
 {
     if ($this->requestConfig->idSubtable && $this->config->show_embedded_subtable) {
         $this->config->show_visualization_only = true;
     }
     // we do not want to get a datatable\map
     $period = Common::getRequestVar('period', 'day', 'string');
     if (Period\Range::parseDateRange($period)) {
         $period = 'range';
     }
     if ($this->dataTable->getRowsCount()) {
         $request = new ApiRequest(array('method' => 'API.get', 'module' => 'API', 'action' => 'get', 'format' => 'original', 'filter_limit' => '-1', 'disable_generic_filters' => 1, 'expanded' => 0, 'flat' => 0, 'filter_offset' => 0, 'period' => $period, 'showColumns' => implode(',', $this->config->columns_to_display), 'columns' => implode(',', $this->config->columns_to_display), 'pivotBy' => ''));
         $dataTable = $request->process();
         $this->assignTemplateVar('siteSummary', $dataTable);
     }
 }
Пример #13
0
 /**
  * @depends      testApi
  * @dataProvider getAnotherApiForTesting
  * @group        Integration
  */
 public function testAnotherApi($api, $params)
 {
     // Get the top segment value
     $request = new Request('method=API.getSuggestedValuesForSegment' . '&segmentName=' . $params['segmentToComplete'] . '&idSite=' . $params['idSite'] . '&format=php&serialize=0');
     $response = $request->process();
     $this->checkRequestResponse($response);
     $topSegmentValue = @$response[0];
     if ($topSegmentValue !== false && !is_null($topSegmentValue)) {
         // Now build the segment request
         $segmentValue = rawurlencode(html_entity_decode($topSegmentValue));
         $params['segment'] = $params['segmentToComplete'] . '==' . $segmentValue;
         unset($params['segmentToComplete']);
         $this->runApiTests($api, $params);
         self::$processed++;
     } else {
         self::$skipped[] = $params['segmentToComplete'];
     }
 }
 /**
  * @depends      testApi
  * @dataProvider getAnotherApiForTesting
  */
 public function testAnotherApi($api, $params)
 {
     // Get the top segment value
     $request = new Request('method=API.getSuggestedValuesForSegment' . '&segmentName=' . $params['segmentToComplete'] . '&idSite=' . $params['idSite'] . '&format=php&serialize=0');
     $response = $request->process();
     $this->assertApiResponseHasNoError($response);
     $topSegmentValue = @$response[0];
     if ($topSegmentValue !== false && !is_null($topSegmentValue)) {
         if (is_numeric($topSegmentValue) || is_float($topSegmentValue) || preg_match('/^\\d*?,\\d*$/', $topSegmentValue)) {
             $topSegmentValue = Common::forceDotAsSeparatorForDecimalPoint($topSegmentValue);
         }
         // Now build the segment request
         $segmentValue = rawurlencode(html_entity_decode($topSegmentValue));
         $params['segment'] = $params['segmentToComplete'] . '==' . $segmentValue;
         unset($params['segmentToComplete']);
         $this->runApiTests($api, $params);
         self::$processed++;
     } else {
         self::$skipped[] = $params['segmentToComplete'];
     }
 }
Пример #15
0
 protected function getMetricsForGoal($idGoal)
 {
     $request = new Request("method=Goals.get&format=original&idGoal={$idGoal}");
     $datatable = $request->process();
     $dataRow = $datatable->getFirstRow();
     $nbConversions = $dataRow->getColumn('nb_conversions');
     $nbVisitsConverted = $dataRow->getColumn('nb_visits_converted');
     // Backward compatibilty before 1.3, this value was not processed
     if (empty($nbVisitsConverted)) {
         $nbVisitsConverted = $nbConversions;
     }
     $revenue = $dataRow->getColumn('revenue');
     $return = array('id' => $idGoal, 'nb_conversions' => (int) $nbConversions, 'nb_visits_converted' => (int) $nbVisitsConverted, 'conversion_rate' => $this->formatConversionRate($dataRow->getColumn('conversion_rate')), 'revenue' => $revenue ? $revenue : 0, 'urlSparklineConversions' => $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_conversions'), 'idGoal' => $idGoal)), 'urlSparklineConversionRate' => $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('conversion_rate'), 'idGoal' => $idGoal)), 'urlSparklineRevenue' => $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('revenue'), 'idGoal' => $idGoal)));
     if ($idGoal == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER) {
         $items = $dataRow->getColumn('items');
         $aov = $dataRow->getColumn('avg_order_revenue');
         $return = array_merge($return, array('revenue_subtotal' => $dataRow->getColumn('revenue_subtotal'), 'revenue_tax' => $dataRow->getColumn('revenue_tax'), 'revenue_shipping' => $dataRow->getColumn('revenue_shipping'), 'revenue_discount' => $dataRow->getColumn('revenue_discount'), 'items' => $items ? $items : 0, 'avg_order_revenue' => $aov ? $aov : 0, 'urlSparklinePurchasedProducts' => $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('items'), 'idGoal' => $idGoal)), 'urlSparklineAverageOrderValue' => $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('avg_order_revenue'), 'idGoal' => $idGoal))));
     }
     return $return;
 }
Пример #16
0
 /**
  * @dataProvider getPermissionsFailData
  */
 public function testMethodPermissions($hasAdminAccess, $hasViewAccess, $request, $checkException, $failMessage)
 {
     // create fake access that denies user access
     FakeAccess::$superUser = false;
     FakeAccess::$idSitesAdmin = $hasAdminAccess ? array(self::$fixture->idSite1) : array();
     FakeAccess::$idSitesView = $hasViewAccess ? array(self::$fixture->idSite1) : array();
     if ($checkException) {
         try {
             $request = new Request($request);
             $request->process();
             $this->fail($failMessage);
         } catch (Exception $ex) {
             // pass
         }
     } else {
         $request = new Request($request);
         $request->process();
     }
 }
Пример #17
0
 protected function loadEvolutionReport($column = false)
 {
     list($apiModule, $apiAction) = explode('.', $this->apiMethod);
     // getQueryStringFromParameters expects sanitised query parameter values
     $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 = Url::getQueryStringFromParameters($parameters);
     $request = new Request($url);
     $report = $request->process();
     $this->extractEvolutionReport($report);
 }
 private function invalidateTestArchive($idSite, $period, $dateTime)
 {
     $dates = new \DateTime($dateTime);
     $dates = $dates->format('Y-m-d');
     $r = new Request("module=API&method=CoreAdminHome.invalidateArchivedReports&period={$period}&idSites={$idSite}&dates={$dates}");
     $this->assertApiResponseHasNoError($r->process());
 }
Пример #19
0
 protected function getSummary()
 {
     $requestString = "method=VisitFrequency.get&format=original";
     $request = new Request($requestString);
     return $request->process();
 }
Пример #20
0
 private function requestInsights($requestParams)
 {
     $params = array('method' => 'Insights.getInsights', 'idSite' => self::$fixture->idSite, 'date' => self::$fixture->date1, 'period' => 'day', 'format' => 'original', 'reportUniqueId' => 'Actions_getPageUrls');
     if (!empty($requestParams)) {
         foreach ($requestParams as $key => $value) {
             $params[$key] = $value;
         }
     }
     $request = new ApiRequest($params);
     return $request->process();
 }
Пример #21
0
 public function getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters = false, $idGoal = false, $language = false, $showTimer = true, $hideMetricsDoc = false, $idSubtable = false, $showRawMetrics = false, $formatMetrics = null)
 {
     $timer = new Timer();
     if (empty($apiParameters)) {
         $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, $hideMetricsDoc, $showSubtableReports = true);
     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, 'idSubtable' => $idSubtable));
     if (!empty($segment)) {
         $parameters['segment'] = $segment;
     }
     if (!empty($reportMetadata['processedMetrics']) && !empty($reportMetadata['metrics']['nb_visits']) && @$reportMetadata['category'] != Piwik::translate('Goals_Ecommerce') && $apiModule !== 'MultiSites') {
         $deleteRowsWithNoVisits = empty($reportMetadata['constantRowsCount']) ? '1' : '0';
         $parameters['filter_add_columns_when_show_all_columns'] = $deleteRowsWithNoVisits;
     }
     $url = Url::getQueryStringFromParameters($parameters);
     $request = new Request($url);
     try {
         /** @var DataTable */
         $dataTable = $request->process();
     } catch (Exception $e) {
         throw new Exception("API returned an error: " . $e->getMessage() . " at " . basename($e->getFile()) . ":" . $e->getLine() . "\n");
     }
     list($newReport, $columns, $rowsMetadata, $totals) = $this->handleTableReport($idSite, $dataTable, $reportMetadata, $showRawMetrics, $formatMetrics);
     foreach ($columns as &$name) {
         $name = ucfirst($name);
     }
     $website = new Site($idSite);
     $period = Period\Factory::build($period, $date);
     $period = $period->getLocalizedLongString();
     $return = array('website' => $website->getName(), 'prettyDate' => $period, 'metadata' => $reportMetadata, 'columns' => $columns, 'reportData' => $newReport, 'reportMetadata' => $rowsMetadata, 'reportTotal' => $totals);
     if ($showTimer) {
         $return['timerMillis'] = $timer->getTimeMs(0);
     }
     return $return;
 }
Пример #22
0
 public static function getStaticGraph($reportMetadata, $width, $height, $evolution, $segment)
 {
     $imageGraphUrl = $reportMetadata['imageGraphUrl'];
     if ($evolution && !empty($reportMetadata['imageGraphEvolutionUrl'])) {
         $imageGraphUrl = $reportMetadata['imageGraphEvolutionUrl'];
     }
     $requestGraph = $imageGraphUrl . '&outputType=' . API::GRAPH_OUTPUT_PHP . '&format=original&serialize=0' . '&filter_truncate=' . '&width=' . $width . '&height=' . $height . ($segment != null ? '&segment=' . urlencode($segment['definition']) : '');
     $request = new Request($requestGraph);
     try {
         $imageGraph = $request->process();
         // Get image data as string
         ob_start();
         imagepng($imageGraph);
         $imageGraphData = ob_get_contents();
         ob_end_clean();
         imagedestroy($imageGraph);
         return $imageGraphData;
     } catch (Exception $e) {
         throw new Exception("ImageGraph API returned an error: " . $e->getMessage() . "\n");
     }
 }
Пример #23
0
 private function requestApiMethod($method, $idSite, $period, $date, $reportId, $segment, $additionalParams)
 {
     $params = array('method' => 'Insights.' . $method, 'idSite' => $idSite, 'date' => $date, 'period' => $period, 'format' => 'original', 'reportUniqueId' => $reportId);
     if (!empty($segment)) {
         $params['segment'] = $segment;
     }
     if (!empty($additionalParams)) {
         foreach ($additionalParams as $key => $value) {
             $params[$key] = $value;
         }
     }
     $request = new ApiRequest($params);
     return $request->process();
 }
Пример #24
0
 private function getSuggestedValuesForSegmentName($idSite, $segment, $maxSuggestionsToReturn)
 {
     $startDate = Date::now()->subDay(60)->toString();
     $requestLastVisits = "method=Live.getLastVisitsDetails\n        &idSite={$idSite}\n        &period=range\n        &date={$startDate},today\n        &format=original\n        &serialize=0\n        &flat=1";
     $segmentName = $segment['segment'];
     // Select non empty fields only
     // Note: this optimization has only a very minor impact
     $requestLastVisits .= "&segment={$segmentName}" . urlencode('!=');
     // By default Live fetches all actions for all visitors, but we'd rather do this only when required
     if ($this->doesSegmentNeedActionsData($segmentName)) {
         $requestLastVisits .= "&filter_limit=400";
     } else {
         $requestLastVisits .= "&doNotFetchActions=1";
         $requestLastVisits .= "&filter_limit=800";
     }
     $request = new Request($requestLastVisits);
     $table = $request->process();
     if (empty($table)) {
         throw new \Exception("There was no data to suggest for {$segmentName}");
     }
     if (isset($segment['suggestedValuesCallback']) && $this->doesSuggestedValuesCallbackNeedData($segment['suggestedValuesCallback'])) {
         $values = call_user_func($segment['suggestedValuesCallback'], $idSite, $maxSuggestionsToReturn, $table);
     } else {
         $values = $this->getSegmentValuesFromVisitorLog($segmentName, $table);
     }
     return $values;
 }
Пример #25
0
 public static function getVisits()
 {
     $requestString = "method=VisitsSummary.getVisits" . "&format=original" . "&disable_generic_filters=1";
     $request = new Request($requestString);
     return $request->process();
 }
Пример #26
0
 private function getMetrics($idSite, $period, $date, $token_auth)
 {
     $request = new Request('method=API.getMetadata&format=PHP' . '&apiModule=UserCountry&apiAction=getCountry' . '&idSite=' . $idSite . '&period=' . $period . '&date=' . $date . '&token_auth=' . $token_auth . '&filter_limit=-1');
     $metaData = unserialize($request->process());
     $metrics = array();
     if (!empty($metaData[0]['metrics']) && is_array($metaData[0]['metrics'])) {
         foreach ($metaData[0]['metrics'] as $id => $val) {
             // todo: should use SettingsPiwik::isUniqueVisitorsEnabled ?
             if (Common::getRequestVar('period') == 'day' || $id != 'nb_uniq_visitors') {
                 $metrics[] = array($id, $val);
             }
         }
     }
     if (!empty($metaData[0]['processedMetrics']) && is_array($metaData[0]['processedMetrics'])) {
         foreach ($metaData[0]['processedMetrics'] as $id => $val) {
             $metrics[] = array($id, $val);
         }
     }
     return $metrics;
 }
Пример #27
0
 /**
  * Given a list of default parameters to set, returns the URLs of APIs to call
  * If any API was specified in $this->apiNotToCall we ensure only these are tested.
  * If any API is set as excluded (see list below) then it will be ignored.
  *
  * @param array $parametersToSet Parameters to set in api call
  * @param array $formats         Array of 'format' to fetch from API
  * @param array $periods         Array of 'period' to query API
  * @param bool  $supertableApi
  * @param bool  $setDateLastN    If set to true, the 'date' parameter will be rewritten to query instead a range of dates, rather than one period only.
  * @param bool|string $language        2 letter language code, defaults to default piwik language
  * @param bool|string $fileExtension
  *
  * @throws Exception
  *
  * @return array of API URLs query strings
  */
 protected function generateApiUrlPermutations($parametersToSet)
 {
     $formats = array($this->testConfig->format);
     $originalDate = $parametersToSet['date'];
     $requestUrls = array();
     $apiMetadata = new DocumentationGenerator();
     // Get the URLs to query against the API for all functions starting with get*
     foreach ($this->getAllApiMethods() as $apiMethodInfo) {
         list($class, $moduleName, $methodName) = $apiMethodInfo;
         $apiId = $moduleName . '.' . $methodName;
         foreach ($this->testConfig->periods as $period) {
             $parametersToSet['period'] = $period;
             // If date must be a date range, we process this date range by adding 6 periods to it
             if ($this->testConfig->setDateLastN) {
                 if (!isset($parametersToSet['dateRewriteBackup'])) {
                     $parametersToSet['dateRewriteBackup'] = $parametersToSet['date'];
                 }
                 $lastCount = $this->testConfig->setDateLastN;
                 $secondDate = date('Y-m-d', strtotime("+{$lastCount} " . $period . "s", strtotime($originalDate)));
                 $parametersToSet['date'] = $originalDate . ',' . $secondDate;
             }
             // Set response language
             if ($this->testConfig->language !== false) {
                 $parametersToSet['language'] = $this->testConfig->language;
             }
             // set idSubtable if subtable API is set
             if ($this->testConfig->supertableApi !== false) {
                 $request = new Request(array('module' => 'API', 'method' => $this->testConfig->supertableApi, 'idSite' => $parametersToSet['idSite'], 'period' => $parametersToSet['period'], 'date' => $parametersToSet['date'], 'format' => 'php', 'serialize' => 0));
                 $content = $request->process();
                 SystemTestCase::assertApiResponseHasNoError($content);
                 // find first row w/ subtable
                 foreach ($content as $row) {
                     if (isset($row['idsubdatatable'])) {
                         $parametersToSet['idSubtable'] = $row['idsubdatatable'];
                         break;
                     }
                 }
                 // if no subtable found, throw
                 if (!isset($parametersToSet['idSubtable'])) {
                     throw new Exception("Cannot find subtable to load for {$apiId} in {$this->testConfig->supertableApi}.");
                 }
             }
             // Generate for each specified format
             foreach ($formats as $format) {
                 $parametersToSet['format'] = $format;
                 $parametersToSet['hideIdSubDatable'] = 1;
                 $parametersToSet['serialize'] = 1;
                 $exampleUrl = $apiMetadata->getExampleUrl($class, $methodName, $parametersToSet);
                 if ($exampleUrl === false) {
                     continue;
                 }
                 // Remove the first ? in the query string
                 $exampleUrl = substr($exampleUrl, 1);
                 $apiRequestId = $apiId;
                 if (strpos($exampleUrl, 'period=') !== false) {
                     $apiRequestId .= '_' . $period;
                 }
                 $apiRequestId .= '.' . $format;
                 if ($this->testConfig->fileExtension) {
                     $apiRequestId .= '.' . $this->testConfig->fileExtension;
                 }
                 $requestUrls[$apiRequestId] = UrlHelper::getArrayFromQueryString($exampleUrl);
             }
         }
     }
     return $requestUrls;
 }
Пример #28
0
 /**
  * Helper method that processes an API request in one line using the variables in `$_GET`
  * and `$_POST`.
  *
  * @param string $method The API method to call, ie, `'Actions.getPageTitles'`.
  * @param array $paramOverride The parameter name-value pairs to use instead of what's
  *                             in `$_GET` & `$_POST`.
  * @return mixed The result of the API request. See {@link process()}.
  */
 public static function processRequest($method, $paramOverride = array())
 {
     $params = array();
     $params['format'] = 'original';
     $params['module'] = 'API';
     $params['method'] = $method;
     $params = $paramOverride + $params;
     // process request
     $request = new Request($params);
     return $request->process();
 }
Пример #29
0
 /**
  * @param array $metadata see getRowEvolutionMetaData()
  * @param int $idSite
  * @param string $period
  * @param string $date
  * @param string $apiModule
  * @param string $apiAction
  * @param string|bool $label
  * @param string|bool $segment
  * @param int|bool $idGoal
  * @throws Exception
  * @return DataTable\Map|DataTable
  */
 private function loadRowEvolutionDataFromAPI($metadata, $idSite, $period, $date, $apiModule, $apiAction, $label = false, $segment = false, $idGoal = false)
 {
     if (!is_array($label)) {
         $label = array($label);
     }
     $label = array_map('rawurlencode', $label);
     $parameters = array('method' => $apiModule . '.' . $apiAction, 'label' => $label, 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'format' => 'original', 'serialize' => '0', 'segment' => $segment, 'idGoal' => $idGoal, 'filter_limit' => -1, 'labelFilterAddLabelIndex' => count($label) > 1 ? 1 : 0);
     // add "processed metrics" like actions per visit or bounce rate
     // note: some reports should not be filtered with AddColumnProcessedMetrics
     // specifically, reports without the Metrics::INDEX_NB_VISITS metric such as Goals.getVisitsUntilConversion & Goal.getDaysToConversion
     // this is because the AddColumnProcessedMetrics filter removes all datable rows lacking this metric
     if (isset($metadata['metrics']['nb_visits']) && !empty($label)) {
         $parameters['filter_add_columns_when_show_all_columns'] = '1';
     }
     $url = Url::getQueryStringFromParameters($parameters);
     $request = new Request($url);
     try {
         $dataTable = $request->process();
     } catch (Exception $e) {
         throw new Exception("API returned an error: " . $e->getMessage() . "\n");
     }
     return $dataTable;
 }
Пример #30
0
 private function assertHasNoDownload($period)
 {
     $api = new Request($this->getDownloadApiRequestUrl($period));
     $table = $api->process();
     $this->assertEquals(0, $table->getRowsCount(), $period . ' should not have a download but has one');
 }