public function getSegmentToTest($calledDuringTest)
 {
     if ($this->segment) {
         return $this->segment;
     }
     // Segment matching NONE
     $segments = Piwik_API_API::getInstance()->getSegmentsMetadata($this->idSite);
     $segmentExpression = array();
     $seenVisitorId = false;
     foreach ($segments as $segment) {
         $value = 'campaign';
         if ($segment['segment'] == 'visitorId') {
             $seenVisitorId = true;
             $value = '34c31e04394bdc63';
         }
         if ($segment['segment'] == 'visitEcommerceStatus') {
             $value = 'none';
         }
         $segmentExpression[] = $segment['segment'] . '!=' . $value;
     }
     $this->segment = implode(";", $segmentExpression);
     // just checking that this segment was tested (as it has the only visible to admin flag)
     if ($calledDuringTest) {
         $this->assertTrue($seenVisitorId);
         $this->assertTrue(strlen($this->segment) > 100);
     }
     return $this->segment;
 }
예제 #2
0
파일: API.php 프로젝트: Gninety/Microweber
 /**
  * @return Piwik_API_API
  */
 public static function getInstance()
 {
     if (self::$instance == null) {
         self::$instance = new self();
     }
     return self::$instance;
 }
예제 #3
0
 public function index()
 {
     Piwik::checkUserIsNotAnonymous();
     $view = Piwik_View::factory('index');
     $this->setGeneralVariablesView($view);
     $view->currentUserEmail = Piwik::getCurrentUserEmail();
     $availableReports = Piwik_API_API::getInstance()->getReportMetadata($this->idSite);
     $reportsByCategory = array();
     foreach ($availableReports as $report) {
         $reportsByCategory[$report['category']][] = $report;
     }
     unset($reportsByCategory['API']);
     $reports = Piwik_PDFReports_API::getInstance()->getReports($this->idSite, $period = false, $idReport = false, $ifSuperUserReturnOnlySuperUserReports = true);
     $reportsById = array();
     foreach ($reports as &$report) {
         $report['additional_emails'] = str_replace(',', "\n", $report['additional_emails']);
         $report['reports'] = explode(',', str_replace('.', '_', $report['reports']));
         $reportsById[$report['idreport']] = $report;
     }
     $view->downloadOutputType = Piwik_PDFReports_API::OUTPUT_DOWNLOAD;
     $columnsCount = 2;
     $view->newColumnAfter = ceil(count($reportsByCategory) / $columnsCount);
     $view->reportsByCategory = $reportsByCategory;
     $view->reportsJSON = Piwik_Common::json_encode($reportsById);
     $view->periods = array_merge(array('never' => Piwik_Translate('General_Never')), Piwik_PDFReports_API::getPeriodToFrequency());
     $view->defaultFormat = Piwik_PDFReports::DEFAULT_FORMAT;
     $view->formats = Piwik_ReportRenderer::$availableReportRenderers;
     $view->aggregateReportsFormats = Piwik_PDFReports_API::getAggregateReportsFormats();
     $view->reports = $reports;
     $view->language = Piwik_LanguagesManager::getLanguageCodeForCurrentUser();
     echo $view->render();
 }
예제 #4
0
 protected function getCleanedExpression($expression)
 {
     if (empty($this->availableSegments)) {
         $this->availableSegments = Piwik_API_API::getInstance()->getSegmentsMetadata($this->idSites, $_hideImplementationData = false);
     }
     $name = $expression[0];
     $matchType = $expression[1];
     $value = $expression[2];
     $sqlName = '';
     foreach ($this->availableSegments as $segment) {
         if ($segment['segment'] != $name) {
             continue;
         }
         $sqlName = $segment['sqlSegment'];
         // check permission
         if (isset($segment['permission']) && $segment['permission'] != 1) {
             throw new Exception("You do not have enough permission to access the segment " . $name);
         }
         //            $this->segmentsHumanReadable[] = $segment['name'] . " " .
         //                                            $this->getNameForMatchType($matchType) .
         //                                            $value;
         // apply presentation filter
         if (isset($segment['sqlFilter']) && !empty($segment['sqlFilter'])) {
             $value = call_user_func($segment['sqlFilter'], $value, $segment['sqlSegment']);
         }
         break;
     }
     if (empty($sqlName)) {
         throw new Exception("Segment '{$name}' is not a supported segment.");
     }
     return array($sqlName, $expression[1], $value);
 }
예제 #5
0
 /** 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();
 }
예제 #6
0
 public function testAllSizes()
 {
     Piwik::checkUserIsSuperUser();
     $view = Piwik_View::factory('debug_graphs_all_sizes');
     $this->setGeneralVariablesView($view);
     $period = Piwik_Common::getRequestVar('period', 'day', 'string');
     $date = Piwik_Common::getRequestVar('date', 'today', 'string');
     $_GET['token_auth'] = Piwik::getCurrentUserTokenAuth();
     $availableReports = Piwik_API_API::getInstance()->getReportMetadata($this->idSite, $period, $date);
     $view->availableReports = $availableReports;
     $view->graphTypes = array('');
     $view->graphSizes = array(array(null, null), array(Piwik_ReportRenderer::IMAGE_GRAPH_WIDTH, Piwik_ReportRenderer::IMAGE_GRAPH_HEIGHT), array(460, 150), array(300, 150), array(240, 150), array(800, 150), array(600, 300, $fontSize = 18, 300, 150));
     echo $view->render();
 }
예제 #7
0
파일: Html.php 프로젝트: nnnnathann/piwik
 private function assignCommonParameters($smarty)
 {
     $smarty->assign("reportTitleTextColor", Piwik_ReportRenderer::REPORT_TITLE_TEXT_COLOR);
     $smarty->assign("reportTitleTextSize", self::REPORT_TITLE_TEXT_SIZE);
     $smarty->assign("reportTextColor", Piwik_ReportRenderer::REPORT_TEXT_COLOR);
     $smarty->assign("tableHeaderBgColor", Piwik_ReportRenderer::TABLE_HEADER_BG_COLOR);
     $smarty->assign("tableHeaderTextColor", Piwik_ReportRenderer::TABLE_HEADER_TEXT_COLOR);
     $smarty->assign("tableCellBorderColor", Piwik_ReportRenderer::TABLE_CELL_BORDER_COLOR);
     $smarty->assign("tableBgColor", Piwik_ReportRenderer::TABLE_BG_COLOR);
     $smarty->assign("reportTableHeaderTextSize", self::REPORT_TABLE_HEADER_TEXT_SIZE);
     $smarty->assign("reportTableRowTextSize", self::REPORT_TABLE_ROW_TEXT_SIZE);
     $smarty->assign("reportBackToTopTextSize", self::REPORT_BACK_TO_TOP_TEXT_SIZE);
     $smarty->assign("currentPath", Piwik::getPiwikUrl());
     $smarty->assign("logoHeader", Piwik_API_API::getInstance()->getHeaderLogoUrl());
 }
예제 #8
0
    public function listSegments()
    {
        $segments = Piwik_API_API::getInstance()->getSegmentsMetadata($this->idSite);
        $tableDimensions = $tableMetrics = '';
        $customVariables = 0;
        $lastCategory = array();
        foreach ($segments as $segment) {
            $onlyDisplay = array('customVariableName1', 'customVariableName2', 'customVariableValue1', 'customVariableValue2', 'customVariablePageName1', 'customVariablePageValue1');
            $customVariableWillBeDisplayed = in_array($segment['segment'], $onlyDisplay);
            // Don't display more than 4 custom variables name/value rows
            if ($segment['category'] == 'Custom Variables' && !$customVariableWillBeDisplayed) {
                continue;
            }
            $thisCategory = $segment['category'];
            $output = '';
            if (empty($lastCategory[$segment['type']]) || $lastCategory[$segment['type']] != $thisCategory) {
                $output .= '<tr><td class="segmentCategory" colspan="2"><b>' . $thisCategory . '</b></td></tr>';
            }
            $lastCategory[$segment['type']] = $thisCategory;
            $exampleValues = isset($segment['acceptedValues']) ? 'Example values: <code>' . $segment['acceptedValues'] . '</code>' : '';
            $restrictedToAdmin = isset($segment['permission']) ? '<br/>Note: This segment can only be used by an Admin user' : '';
            $output .= '<tr>
							<td class="segmentString">' . $segment['segment'] . '</td>
							<td class="segmentName">' . $segment['name'] . $restrictedToAdmin . '<br/>' . $exampleValues . ' </td>
						</tr>';
            // Show only 2 custom variables and display message for rest
            if ($customVariableWillBeDisplayed) {
                $customVariables++;
                if ($customVariables == count($onlyDisplay)) {
                    $output .= '<tr><td colspan="2"> There are 5 custom variables available, so you can segment across any segment name and value range.
    						<br/>For example, <code>customVariableName1==Type;customVariableValue1==Customer</code>
    						<br/>Returns all visitors that have the Custom Variable "Type" set to "Customer".
    						<br/>Custom Variables of scope "page" can be queried separately. For example, to query the Custom Variable of scope "page",
    						<br/>stored in index 1, you would use the segment <code>customVariablePageName1==ArticleLanguage;customVariablePageValue1==FR</code>
    						</td></tr>';
                }
            }
            if ($segment['type'] == 'dimension') {
                $tableDimensions .= $output;
            } else {
                $tableMetrics .= $output;
            }
        }
        echo "\n\t\t<b>Dimensions</b>\n\t\t<table>\n\t\t{$tableDimensions}\n\t\t</table>\n\t\t<br/>\n\t\t<b>Metrics</b>\n\t\t<table>\n\t\t{$tableMetrics}\n\t\t</table>\n\t\t";
    }
예제 #9
0
 protected function getCleanedExpression($expression)
 {
     if (empty($this->availableSegments)) {
         $this->availableSegments = Piwik_API_API::getInstance()->getSegmentsMetadata($this->idSites, $_hideImplementationData = false);
     }
     $name = $expression[0];
     $matchType = $expression[1];
     $value = $expression[2];
     $sqlName = '';
     foreach ($this->availableSegments as $segment) {
         if ($segment['segment'] != $name) {
             continue;
         }
         $sqlName = $segment['sqlSegment'];
         // check permission
         if (isset($segment['permission']) && $segment['permission'] != 1) {
             throw new Exception("You do not have enough permission to access the segment " . $name);
         }
         //            $this->segmentsHumanReadable[] = $segment['name'] . " " .
         //                                            $this->getNameForMatchType($matchType) .
         //                                            $value;
         // apply presentation filter
         if (isset($segment['sqlFilter']) && !empty($segment['sqlFilter'])) {
             $value = call_user_func($segment['sqlFilter'], $value, $segment['sqlSegment'], $matchType);
             // sqlFilter-callbacks might return arrays for more complex cases
             // e.g. see Piwik_Actions::getIdActionFromSegment()
             if (is_array($value) && isset($value['SQL'])) {
                 // Special case: returned value is a sub sql expression!
                 $matchType = Piwik_SegmentExpression::MATCH_ACTIONS_CONTAINS;
             }
         }
         break;
     }
     if (empty($sqlName)) {
         throw new Exception("Segment '{$name}' is not a supported segment.");
     }
     return array($sqlName, $matchType, $value);
 }
예제 #10
0
 private function checkAvailableReports($idSite, $reports)
 {
     $availableReports = Piwik_API_API::getInstance()->getReportMetadata($idSite);
     $availableReportIds = array();
     foreach ($availableReports as $report) {
         $availableReportIds[] = $report['uniqueId'];
     }
     $reports = explode(',', $reports);
     $reports = array_filter($reports, 'strlen');
     foreach ($reports as $report) {
         if (!in_array($report, $availableReportIds)) {
             throw new Exception("Report {$report} is unknown.");
         }
     }
     $reports = implode(',', $reports);
     return $reports;
 }
예제 #11
0
 /**
  * Prepare metrics toggles with spark lines
  * @param $controller
  * @return array
  */
 protected function getMetricsToggles($controller)
 {
     $chart = new Piwik_Visualization_Chart_Evolution();
     $colors = $chart->getSeriesColors();
     $i = 0;
     $metrics = array();
     foreach ($this->availableMetrics as $metric => $metricData) {
         $max = isset($metricData['max']) ? $metricData['max'] : 0;
         $min = isset($metricData['min']) ? $metricData['min'] : 0;
         $change = isset($metricData['change']) ? $metricData['change'] : false;
         $unit = Piwik_API_API::getUnit($metric, $this->idSite);
         $min .= $unit;
         $max .= $unit;
         $details = Piwik_Translate('RowEvolution_MetricBetweenText', array($min, $max));
         if ($change !== false) {
             $lowerIsBetter = Piwik_API_API::isLowerValueBetter($metric);
             if (substr($change, 0, 1) == '+') {
                 $changeClass = $lowerIsBetter ? 'bad' : 'good';
                 $changeImage = $lowerIsBetter ? 'arrow_up_red' : 'arrow_up';
             } else {
                 if (substr($change, 0, 1) == '-') {
                     $changeClass = $lowerIsBetter ? 'good' : 'bad';
                     $changeImage = $lowerIsBetter ? 'arrow_down_green' : 'arrow_down';
                 } else {
                     $changeClass = 'neutral';
                     $changeImage = false;
                 }
             }
             $change = '<span class="' . $changeClass . '">' . ($changeImage ? '<img src="plugins/MultiSites/images/' . $changeImage . '.png" /> ' : '') . $change . '</span>';
             $details .= ', ' . Piwik_Translate('RowEvolution_MetricChangeText', $change);
         }
         $color = $colors[$i % count($colors)];
         $newMetric = array('label' => $metricData['name'], 'color' => $color, 'details' => $details, 'sparkline' => $this->getSparkline($metric, $controller));
         // Multi Rows, each metric can be for a particular row and display an icon
         if (!empty($metricData['logo'])) {
             $newMetric['logo'] = $metricData['logo'];
         }
         $metrics[] = $newMetric;
         $i++;
     }
     return $metrics;
 }
예제 #12
0
 /**
  * Inits the object given the $currentControllerName, $currentControllerAction of 
  * the calling controller action, eg. 'Referers' 'getLongListOfKeywords'.
  * The initialization also requires the $apiMethodToRequestDataTable of the API method 
  * to call in order to get the DataTable, eg. 'Referers.getKeywords'.
  * The optional $controllerActionCalledWhenRequestSubTable defines the method name of the API to call when there is a idSubtable.
  * This value would be used by the javascript code building the GET request to the API.
  * 
  * Example: 
  * 	For the keywords listing, a click on the row loads the subTable of the Search Engines for this row.
  *  In this case $controllerActionCalledWhenRequestSubTable = 'getSearchEnginesFromKeywordId'.
  *  The GET request will hit 'Referers.getSearchEnginesFromKeywordId'.
  *
  * @param string $currentControllerName eg. 'Referers'
  * @param string $currentControllerAction eg. 'getKeywords'
  * @param string $apiMethodToRequestDataTable eg. 'Referers.getKeywords'
  * @param string $controllerActionCalledWhenRequestSubTable eg. 'getSearchEnginesFromKeywordId'
  */
 public function init($currentControllerName, $currentControllerAction, $apiMethodToRequestDataTable, $controllerActionCalledWhenRequestSubTable = null)
 {
     $this->currentControllerName = $currentControllerName;
     $this->currentControllerAction = $currentControllerAction;
     $this->apiMethodToRequestDataTable = $apiMethodToRequestDataTable;
     $this->controllerActionCalledWhenRequestSubTable = $controllerActionCalledWhenRequestSubTable;
     $this->idSubtable = Piwik_Common::getRequestVar('idSubtable', false, 'int');
     $this->viewProperties['show_goals'] = false;
     $this->viewProperties['show_search'] = Piwik_Common::getRequestVar('show_search', true);
     $this->viewProperties['show_table'] = Piwik_Common::getRequestVar('show_table', true);
     $this->viewProperties['show_table_all_columns'] = Piwik_Common::getRequestVar('show_table_all_columns', true);
     $this->viewProperties['show_all_views_icons'] = Piwik_Common::getRequestVar('show_all_views_icons', true);
     $this->viewProperties['show_export_as_image_icon'] = Piwik_Common::getRequestVar('show_export_as_image_icon', false);
     $this->viewProperties['show_export_as_rss_feed'] = Piwik_Common::getRequestVar('show_export_as_rss_feed', true);
     $this->viewProperties['show_exclude_low_population'] = Piwik_Common::getRequestVar('show_exclude_low_population', true);
     $this->viewProperties['show_offset_information'] = Piwik_Common::getRequestVar('show_offset_information', true);
     $this->viewProperties['show_pagination_control'] = Piwik_Common::getRequestVar('show_pagination_control', true);
     $this->viewProperties['show_footer'] = Piwik_Common::getRequestVar('show_footer', true);
     $this->viewProperties['show_footer_icons'] = $this->idSubtable == false;
     $this->viewProperties['apiMethodToRequestDataTable'] = $this->apiMethodToRequestDataTable;
     $this->viewProperties['uniqueId'] = $this->getUniqueIdViewDataTable();
     $standardColumnNameToTranslation = array_merge(Piwik_API_API::getInstance()->getDefaultMetrics(), Piwik_API_API::getInstance()->getDefaultProcessedMetrics());
     $this->setColumnsTranslations($standardColumnNameToTranslation);
 }
예제 #13
0
 protected function deriveUnitsFromRequestedColumnNames($requestedColumnNames, $idSite)
 {
     $units = array();
     foreach ($requestedColumnNames as $columnName) {
         $derivedUnit = Piwik_API_API::getUnit($columnName, $idSite);
         $units[$columnName] = empty($derivedUnit) ? false : $derivedUnit;
     }
     return $units;
 }
예제 #14
0
 public function renderFrontPage($websiteName, $prettyDate, $description, $reportMetadata)
 {
     $websiteTitle = $this->formatText(Piwik_Translate('General_Website') . " " . $websiteName);
     $dateRange = $this->formatText(Piwik_Translate('General_DateRange') . " " . $prettyDate);
     //Setup Footer font and data
     $this->TCPDF->SetFooterFont(array($this->reportFont, $this->reportFontStyle, $this->reportSimpleFontSize));
     $this->TCPDF->SetFooterContent($websiteTitle . " | " . $dateRange . " | ");
     $this->TCPDF->setPrintHeader(false);
     //		$this->SetMargins($left = , $top, $right=-1, $keepmargins=true)
     $this->TCPDF->AddPage(self::PORTRAIT);
     $this->TCPDF->AddFont($this->reportFont, '', '', false);
     $this->TCPDF->SetFont($this->reportFont, $this->reportFontStyle, $this->reportSimpleFontSize);
     //Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false) {
     $this->TCPDF->Bookmark(Piwik_Translate('PDFReports_FrontPage'));
     $this->TCPDF->Image(Piwik_API_API::getInstance()->getLogoUrl(true), $this->logoImagePosition[0], $this->logoImagePosition[1], 180 / ($factor = 2), 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300);
     $this->TCPDF->Ln(8);
     $this->TCPDF->SetFont($this->reportFont, '', $this->reportHeaderFontSize + 5);
     $this->TCPDF->SetTextColor($this->headerTextColor[0], $this->headerTextColor[1], $this->headerTextColor[2]);
     $this->TCPDF->Cell(40, 210, $websiteTitle);
     $this->TCPDF->Ln(8 * 4);
     $this->TCPDF->SetFont($this->reportFont, '', $this->reportHeaderFontSize);
     $this->TCPDF->SetTextColor($this->reportTextColor[0], $this->reportTextColor[1], $this->reportTextColor[2]);
     $this->TCPDF->Cell(40, 210, $dateRange);
     $this->TCPDF->Ln(8 * 20);
     $this->TCPDF->Write(1, $this->formatText($description));
     $this->TCPDF->Ln(8);
     $this->TCPDF->SetFont($this->reportFont, '', $this->reportHeaderFontSize);
     $this->TCPDF->Ln();
 }
예제 #15
0
 /**
  * @param Piwik_Event_Notification $notification notification object
  */
 function getReportMetadata($notification)
 {
     if (self::manageEvent($notification)) {
         $reportMetadata =& $notification->getNotificationObject();
         $notificationInfo = $notification->getNotificationInfo();
         $idSite = $notificationInfo[Piwik_PDFReports_API::ID_SITE_INFO_KEY];
         $availableReportMetadata = Piwik_API_API::getInstance()->getReportMetadata($idSite);
         $filteredReportMetadata = array();
         foreach ($availableReportMetadata as $reportMetadata) {
             // removing reports from the API category and MultiSites.getOne
             if ($reportMetadata['category'] == 'API' || $reportMetadata['category'] == Piwik_Translate('General_MultiSitesSummary') && $reportMetadata['name'] == Piwik_Translate('General_SingleWebsitesDashboard')) {
                 continue;
             }
             $filteredReportMetadata[] = $reportMetadata;
         }
         $reportMetadata = $filteredReportMetadata;
     }
 }
예제 #16
0
 function getVisitEcommerceStatus()
 {
     return Piwik_API_API::getVisitEcommerceStatusFromId($this->details['visit_goal_buyer']);
 }
예제 #17
0
 public function get($idSite, $period, $date, $apiModule, $apiAction, $graphType = false, $outputType = Piwik_ImageGraph_API::GRAPH_OUTPUT_INLINE, $columns = false, $labels = false, $showLegend = true, $width = false, $height = false, $fontSize = Piwik_ImageGraph_API::DEFAULT_FONT_SIZE, $legendFontSize = false, $aliasedGraph = true, $idGoal = false, $colors = false, $idSubtable = false, $legendAppendMetric = true)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // Health check - should we also test for GD2 only?
     if (!Piwik::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 = Piwik_Translate::getInstance()->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
         $metadata = Piwik_API_API::getInstance()->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $languageLoaded, $period, $date, $hideMetricsDoc = false, $showSubtableReports = true);
         if (!$metadata) {
             throw new Exception('Invalid API Module and/or API Action');
         }
         $metadata = $metadata[0];
         $reportHasDimension = !empty($metadata['dimension']);
         $constantRowsCount = !empty($metadata['constantRowsCount']);
         $isMultiplePeriod = Piwik_Archive::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 = $fontSize + self::DEFAULT_LEGEND_FONT_SIZE_OFFSET;
         }
         if (empty($graphType)) {
             if ($isMultiplePeriod) {
                 $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_LINE;
             } else {
                 if ($constantRowsCount) {
                     $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_VERTICAL_BAR;
                 } else {
                     $graphType = Piwik_ImageGraph_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 = Piwik_ImageGraph_StaticGraph::getAvailableStaticGraphTypes();
             if (!in_array($graphType, $availableGraphTypes)) {
                 throw new Exception(Piwik_TranslateException('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 Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_3D_PIE:
             case Piwik_ImageGraph_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 Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_VERTICAL_BAR:
             case Piwik_ImageGraph_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 Piwik_API_DataTableGenericFilter for more info)
             if (!$labels) {
                 $savedFilterSortColumnValue = Piwik_Common::getRequestVar('filter_sort_column', '');
                 $_GET['filter_sort_column'] = $plottedMetric;
                 $savedFilterLimitValue = Piwik_Common::getRequestVar('filter_limit', -1, 'int');
                 if ($savedFilterLimitValue == -1 || $savedFilterLimitValue > self::MAX_NB_ROW_LABELS) {
                     $_GET['filter_limit'] = self::DEFAULT_NB_ROW_EVOLUTIONS;
                 }
             }
             $processedReport = Piwik_API_API::getInstance()->getRowEvolution($idSite, $period, $date, $apiModule, $apiAction, $labels, $segment = false, $plottedMetric, $languageLoaded, $idGoal, $legendAppendMetric, $labelUseAbsoluteUrl = false);
             //@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 {
             $processedReport = Piwik_API_API::getInstance()->getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters = false, $idGoal, $languageLoaded, $showTimer = true, $hideMetricsDoc = false, $idSubtable);
         }
         // prepare abscissa and ordinate series
         $abscissaSeries = array();
         $abscissaLogos = array();
         $ordinateSeries = array();
         $reportData = $processedReport['reportData'];
         $hasData = false;
         $hasNonZeroValue = false;
         if (!$isMultiplePeriod) {
             $reportMetadata = $processedReport['reportMetadata']->getRows();
             $i = 0;
             // $reportData instanceof Piwik_DataTable
             foreach ($reportData->getRows() as $row) {
                 // $row instanceof Piwik_DataTable_Row
                 $rowData = $row->getColumns();
                 // Associative Array
                 $abscissaSeries[] = Piwik_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 {
             // $reportData instanceof Piwik_DataTable_Array
             $periodsMetadata = array_values($reportData->metadata);
             // $periodsData instanceof Piwik_DataTable_Simple[]
             $periodsData = array_values($reportData->getArray());
             $periodsCount = count($periodsMetadata);
             for ($i = 0; $i < $periodsCount; $i++) {
                 // $periodsData[$i] instanceof Piwik_DataTable_Simple
                 // $rows instanceof Piwik_DataTable_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) {
                         $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 = $periodsMetadata[$i]['period']->getLocalizedShortString();
                 $abscissaSeries[] = Piwik_Common::unsanitizeInputValue($rowId);
             }
         }
         if (!$hasData || !$hasNonZeroValue) {
             throw new Exception(Piwik_Translate('General_NoDataForGraph'));
         }
         //Setup the graph
         $graph = Piwik_ImageGraph_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());
         if ($period == 'day') {
             $graph->setForceSkippedLabels(6);
         }
         // render graph
         $graph->renderGraph();
     } catch (Exception $e) {
         $graph = new Piwik_ImageGraph_StaticGraph_Exception();
         $graph->setWidth($width);
         $graph->setHeight($height);
         $graph->setFont($font);
         $graph->setFontSize($fontSize);
         $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 (!Piwik_Common::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;
     }
 }
예제 #18
0
 public function get($idSite, $period, $date, $apiModule, $apiAction, $graphType = false, $outputType = Piwik_ImageGraph_API::GRAPH_OUTPUT_INLINE, $column = false, $showMetricTitle = true, $width = false, $height = false, $fontSize = Piwik_ImageGraph_API::DEFAULT_FONT_SIZE, $aliasedGraph = true, $colors = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // Health check - should we also test for GD2 only?
     if (!Piwik::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 = Piwik_Translate::getInstance()->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 {
         //Fetch the metadata for given api-action
         $metadata = Piwik_API_API::getInstance()->getMetadata($idSite, $apiModule, $apiAction, $apiParameters = array(), $languageLoaded, $period, $date);
         if (!$metadata) {
             throw new Exception('Invalid API Module and/or API Action');
         }
         $metadata = $metadata[0];
         $reportHasDimension = !empty($metadata['dimension']);
         $constantRowsCount = !empty($metadata['constantRowsCount']);
         $isMultiplePeriod = Piwik_Archive::isMultiplePeriod($date, $period);
         if ($reportHasDimension && $isMultiplePeriod || !$reportHasDimension && !$isMultiplePeriod) {
             throw new Exception('The graph cannot be drawn for this combination of \'date\' and \'period\' parameters.');
         }
         if (empty($graphType)) {
             if ($reportHasDimension) {
                 if ($constantRowsCount) {
                     $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_VERTICAL_BAR;
                 } else {
                     $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_HORIZONTAL_BAR;
                 }
             } else {
                 $graphType = Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_LINE;
             }
             $reportUniqueId = $metadata['uniqueId'];
             if (isset(self::$DEFAULT_GRAPH_TYPE_OVERRIDE[$reportUniqueId])) {
                 $graphType = self::$DEFAULT_GRAPH_TYPE_OVERRIDE[$reportUniqueId];
             }
         } else {
             $availableGraphTypes = Piwik_ImageGraph_StaticGraph::getAvailableStaticGraphTypes();
             if (!in_array($graphType, $availableGraphTypes)) {
                 throw new Exception(Piwik_TranslateException('General_ExceptionInvalidStaticGraphType', array($graphType, implode(', ', $availableGraphTypes))));
             }
         }
         if (empty($width)) {
             $width = self::$DEFAULT_PARAMETERS[$graphType][self::WIDTH_KEY];
         }
         if (empty($height)) {
             $height = self::$DEFAULT_PARAMETERS[$graphType][self::HEIGHT_KEY];
         }
         if ($reportHasDimension) {
             $abscissaColumn = 'label';
         } else {
             // if it's a dimension-less report, the abscissa column can only be the date-index
             $abscissaColumn = 'date';
         }
         $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());
         $ordinateColumn = $column;
         if (empty($ordinateColumn)) {
             $ordinateColumn = self::DEFAULT_ORDINATE_METRIC;
             // if default ordinate metric not available for this report
             if (empty($reportColumns[$ordinateColumn])) {
                 // take the first metric returned in the metadata
                 $ordinateColumn = key($metadata['metrics']);
             }
         }
         // if we still don't have an ordinate column or the one provided by the API caller is invalid
         if (empty($ordinateColumn) || empty($reportColumns[$ordinateColumn])) {
             throw new Exception(Piwik_Translate('ImageGraph_ColumnOrdinateMissing', $ordinateColumn));
         }
         $ordinateLabel = $reportColumns[$ordinateColumn];
         // sort and truncate filters
         $defaultFilterTruncate = self::$DEFAULT_PARAMETERS[$graphType][self::TRUNCATE_KEY];
         switch ($graphType) {
             case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_3D_PIE:
             case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_PIE:
                 $_GET['filter_sort_column'] = $ordinateColumn;
                 $this->setFilterTruncate($defaultFilterTruncate);
                 break;
             case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_VERTICAL_BAR:
             case Piwik_ImageGraph_StaticGraph::GRAPH_TYPE_BASIC_LINE:
                 if ($reportHasDimension && !$constantRowsCount) {
                     $this->setFilterTruncate($defaultFilterTruncate);
                 }
                 break;
         }
         $processedReport = Piwik_API_API::getInstance()->getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters = false, $idGoal = false, $languageLoaded);
         // prepare abscissa and ordinate series
         $abscissaSerie = array();
         $ordinateSerie = array();
         $ordinateLogos = array();
         $reportData = $processedReport['reportData'];
         $hasData = false;
         $hasNonZeroValue = false;
         if ($reportHasDimension) {
             $reportMetadata = $processedReport['reportMetadata']->getRows();
             $i = 0;
             // $reportData instanceof Piwik_DataTable
             foreach ($reportData->getRows() as $row) {
                 // $row instanceof Piwik_DataTable_Row
                 $rowData = $row->getColumns();
                 // Associative Array
                 $abscissaSerie[] = Piwik_Common::unsanitizeInputValue($rowData[$abscissaColumn]);
                 $parsedOrdinateValue = $this->parseOrdinateValue($rowData[$ordinateColumn]);
                 $hasData = true;
                 if ($parsedOrdinateValue != 0) {
                     $hasNonZeroValue = true;
                 }
                 $ordinateSerie[] = $parsedOrdinateValue;
                 if (isset($reportMetadata[$i])) {
                     $rowMetadata = $reportMetadata[$i]->getColumns();
                     if (isset($rowMetadata['logo'])) {
                         $ordinateLogos[$i] = $rowMetadata['logo'];
                     }
                 }
                 $i++;
             }
         } else {
             // $reportData instanceof Piwik_DataTable_Array
             $periodsMetadata = array_values($reportData->metadata);
             // $periodsData instanceof Piwik_DataTable_Simple[]
             $periodsData = array_values($reportData->getArray());
             $periodsCount = count($periodsMetadata);
             for ($i = 0; $i < $periodsCount; $i++) {
                 // $periodsData[$i] instanceof Piwik_DataTable_Simple
                 // $rows instanceof Piwik_DataTable_Row[]
                 $rows = $periodsData[$i]->getRows();
                 if (array_key_exists(0, $rows)) {
                     $rowData = $rows[0]->getColumns();
                     // associative Array
                     $ordinateValue = $rowData[$ordinateColumn];
                     $parsedOrdinateValue = $this->parseOrdinateValue($ordinateValue);
                     $hasData = true;
                     if ($parsedOrdinateValue != 0) {
                         $hasNonZeroValue = true;
                     }
                 } else {
                     $parsedOrdinateValue = 0;
                 }
                 $rowId = $periodsMetadata[$i]['period']->getLocalizedShortString();
                 $abscissaSerie[] = Piwik_Common::unsanitizeInputValue($rowId);
                 $ordinateSerie[] = $parsedOrdinateValue;
             }
         }
         if (!$hasData || !$hasNonZeroValue) {
             throw new Exception(Piwik_Translate('General_NoDataForGraph'));
         }
         //Setup the graph
         $graph = Piwik_ImageGraph_StaticGraph::factory($graphType);
         $graph->setWidth($width);
         $graph->setHeight($height);
         $graph->setFont($font);
         $graph->setFontSize($fontSize);
         $graph->setMetricTitle($ordinateLabel);
         $graph->setShowMetricTitle($showMetricTitle);
         $graph->setAliasedGraph($aliasedGraph);
         $graph->setAbscissaSerie($abscissaSerie);
         $graph->setOrdinateSerie($ordinateSerie);
         $graph->setOrdinateLogos($ordinateLogos);
         $graph->setColors(!empty($colors) ? explode(',', $colors) : array());
         // render graph
         $graph->renderGraph();
     } catch (Exception $e) {
         $graph = new Piwik_ImageGraph_StaticGraph_Exception();
         $graph->setWidth($width);
         $graph->setHeight($height);
         $graph->setFont($font);
         $graph->setFontSize($fontSize);
         $graph->setException($e);
         $graph->renderGraph();
     }
     // restoring get parameters
     $_GET = $savedGET;
     switch ($outputType) {
         case self::GRAPH_OUTPUT_FILE:
             // adding the idGoal to the filename
             $idGoal = Piwik_Common::getRequestVar('idGoal', '', 'string');
             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 (!Piwik_Common::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;
     }
 }
예제 #19
0
 /** Load documentation from the API */
 private function loadDocumentation()
 {
     $this->metricsDocumentation = array();
     $report = Piwik_API_API::getInstance()->getMetadata(0, $this->currentControllerName, $this->currentControllerAction);
     $report = $report[0];
     if (isset($report['metricsDocumentation'])) {
         $this->metricsDocumentation = $report['metricsDocumentation'];
     }
     if (isset($report['documentation'])) {
         $this->documentation = $report['documentation'];
     }
 }
예제 #20
0
 /** 
  * Get a combined report of the *.get API methods. 
  */
 public function get($idSite, $period, $date, $segment = false, $columns = false)
 {
     $columns = Piwik::getArrayFromApiParameter($columns);
     // build columns map for faster checks later on
     $columnsMap = array();
     foreach ($columns as $column) {
         $columnsMap[$column] = true;
     }
     // find out which columns belong to which plugin
     $columnsByPlugin = array();
     $meta = Piwik_API_API::getInstance()->getReportMetadata($idSite, $period, $date);
     foreach ($meta as $reportMeta) {
         // scan all *.get reports
         if ($reportMeta['action'] == 'get' && !isset($reportMeta['parameters']) && $reportMeta['module'] != 'API') {
             $plugin = $reportMeta['module'];
             foreach ($reportMeta['metrics'] as $column => $columnTranslation) {
                 // a metric from this report has been requested
                 if (isset($columnsMap[$column]) || empty($columnsMap)) {
                     $columnsByPlugin[$plugin][] = $column;
                 }
             }
         }
     }
     krsort($columnsByPlugin);
     $mergedDataTable = false;
     $params = compact('idSite', 'period', 'date', 'segment', 'idGoal');
     foreach ($columnsByPlugin as $plugin => $columns) {
         // load the data
         $className = 'Piwik_' . $plugin . '_API';
         $params['columns'] = implode(',', $columns);
         $dataTable = Piwik_API_Proxy::getInstance()->call($className, 'get', $params);
         // make sure the table has all columns
         $array = $dataTable instanceof Piwik_DataTable_Array ? $dataTable->getArray() : array($dataTable);
         foreach ($array as $table) {
             // we don't support idSites=all&date=DATE1,DATE2
             if ($table instanceof Piwik_DataTable) {
                 $firstRow = $table->getFirstRow();
                 if (!$firstRow) {
                     $firstRow = new Piwik_DataTable_Row();
                     $table->addRow($firstRow);
                 }
                 foreach ($columns as $column) {
                     if ($firstRow->getColumn($column) === false) {
                         $firstRow->setColumn($column, 0);
                     }
                 }
             }
         }
         // merge reports
         if ($mergedDataTable === false) {
             $mergedDataTable = $dataTable;
         } else {
             $this->mergeDataTables($mergedDataTable, $dataTable);
         }
     }
     return $mergedDataTable;
 }
예제 #21
0
	/**
	 * Set the minimal variables in the view object
	 * 
	 * @param Piwik_View $view
	 */
	protected function setBasicVariablesView($view)
	{
		$view->topMenu = Piwik_GetTopMenu();
		$view->debugTrackVisitsInsidePiwikUI = Zend_Registry::get('config')->Debug->track_visits_inside_piwik_ui;
		$view->isSuperUser = Zend_Registry::get('access')->isSuperUser();
		$view->isCustomLogo = Zend_Registry::get('config')->branding->use_custom_logo;
		$view->logoHeader = Piwik_API_API::getInstance()->getHeaderLogoUrl();
		$view->logoLarge = Piwik_API_API::getInstance()->getLogoUrl();
	}
예제 #22
0
 protected function getApiMetaData()
 {
     if ($this->apiMetaData === null) {
         list($apiModule, $apiAction) = explode('.', $this->apiMethod);
         if (!$apiModule || !$apiAction) {
             $this->apiMetaData = false;
         }
         $api = Piwik_API_API::getInstance();
         $meta = $api->getMetadata($this->idSite, $apiModule, $apiAction);
         if (is_array($meta[0])) {
             $meta = $meta[0];
         }
         $this->apiMetaData =& $meta;
     }
     return $this->apiMetaData;
 }
예제 #23
0
 /** Get available metrics from metadata API */
 protected function getAvailableMetrics()
 {
     list($apiModule, $apiAction) = explode('.', $this->apiMethod);
     $this->metaData = Piwik_API_API::getInstance()->getMetadata($this->idSite, $apiModule, $apiAction, array(), false, $this->period);
     $this->metaData = $this->metaData[0];
     $availableMetrics = $this->metaData['metrics'];
     if (isset($this->metaData['processedMetrics'])) {
         $availableMetrics += $this->metaData['processedMetrics'];
     }
     return $availableMetrics;
 }
예제 #24
0
 /**
  * Set the minimal variables in the view object
  * 
  * @param Piwik_View  $view
  */
 protected function setBasicVariablesView($view)
 {
     $view->topMenu = Piwik_GetTopMenu();
     $view->debugTrackVisitsInsidePiwikUI = Piwik_Config::getInstance()->Debug['track_visits_inside_piwik_ui'];
     $view->isSuperUser = Zend_Registry::get('access')->isSuperUser();
     $view->isCustomLogo = Piwik_Config::getInstance()->branding['use_custom_logo'];
     $view->logoHeader = Piwik_API_API::getInstance()->getHeaderLogoUrl();
     $view->logoLarge = Piwik_API_API::getInstance()->getLogoUrl();
     $view->enableFrames = Piwik_Config::getInstance()->General['enable_framed_pages'] || @Piwik_Config::getInstance()->General['enable_framed_logins'];
     if (!$view->enableFrames) {
         $view->setXFrameOptions('sameorigin');
     }
     self::setHostValidationVariablesView($view);
 }
 private function getApiMethodForSubtable()
 {
     if (!$this->apiMethodForSubtable) {
         $meta = Piwik_API_API::getInstance()->getMetadata('all', $this->apiModule, $this->apiMethod);
         if (isset($meta[0]['actionToLoadSubTables'])) {
             $this->apiMethodForSubtable = $meta[0]['actionToLoadSubTables'];
         } else {
             $this->apiMethodForSubtable = $this->apiMethod;
         }
     }
     return $this->apiMethodForSubtable;
 }
예제 #26
0
파일: API.php 프로젝트: nnnnathann/piwik
 /**
  * Generates a report file.
  *
  * @param int $idReport ID of the report to generate.
  * @param string $date YYYY-MM-DD
  * @param bool|false|string $language If not passed, will use default language.
  * @param bool|false|int $outputType 1 = download report, 2 = save report to disk, 3 = output report in browser, 4 = return report content to caller, defaults to download
  * @param bool|false|string $period Defaults to 'day'. If not specified, will default to the report's period set when creating the report
  * @param bool|false|string $reportFormat 'pdf', 'html' or any other format provided via the PDFReports.getReportFormats hook
  * @param bool|false|array $parameters array of parameters
  * @return array|void
  */
 public function generateReport($idReport, $date, $language = false, $outputType = false, $period = false, $reportFormat = false, $parameters = false)
 {
     Piwik::checkUserIsNotAnonymous();
     // load specified language
     if (empty($language)) {
         $language = Piwik_Translate::getInstance()->getLanguageDefault();
     }
     Piwik_Translate::getInstance()->reloadLanguage($language);
     $reports = $this->getReports($idSite = false, $_period = false, $idReport);
     $report = reset($reports);
     $idSite = $report['idsite'];
     $reportType = $report['type'];
     // override report period
     if (empty($period)) {
         $period = $report['period'];
     }
     // override report format
     if (!empty($reportFormat)) {
         self::validateReportFormat($reportType, $reportFormat);
         $report['format'] = $reportFormat;
     } else {
         $reportFormat = $report['format'];
     }
     // override report parameters
     if (!empty($parameters)) {
         $report['parameters'] = Piwik_Common::json_decode(self::validateReportParameters($reportType, $parameters), true);
     } else {
         $parameters = $report['parameters'];
     }
     // decode report list
     $reportUniqueIds = $report['reports'];
     // available reports
     $availableReportMetadata = Piwik_API_API::getInstance()->getReportMetadata($idSite);
     // we need to lookup which reports metadata are registered in this report
     $reportMetadata = array();
     foreach ($availableReportMetadata as $metadata) {
         if (in_array($metadata['uniqueId'], $reportUniqueIds)) {
             $reportMetadata[] = $metadata;
         }
     }
     // the report will be rendered with the first 23 rows and will aggregate other rows in a summary row
     // 23 rows table fits in one portrait page
     $initialFilterTruncate = Piwik_Common::getRequestVar('filter_truncate', false);
     $_GET['filter_truncate'] = self::REPORT_TRUNCATE;
     $prettyDate = null;
     $processedReports = array();
     foreach ($reportMetadata as $action) {
         $apiModule = $action['module'];
         $apiAction = $action['action'];
         $apiParameters = array();
         if (isset($action['parameters'])) {
             $apiParameters = $action['parameters'];
         }
         $mustRestoreGET = false;
         // all Websites dashboard should not be truncated in the report
         if ($apiModule == 'MultiSites') {
             $mustRestoreGET = $_GET;
             $_GET['enhanced'] = true;
             if ($apiAction == 'getAll') {
                 $_GET['filter_truncate'] = false;
                 // when a view/admin user created a report, workaround the fact that "Super User"
                 // is enforced in Scheduled tasks, and ensure Multisites.getAll only return the websites that this user can access
                 if (!empty($userLogin) && $userLogin != Piwik_Config::getInstance()->superuser['login']) {
                     $_GET['_restrictSitesToLogin'] = $userLogin;
                 }
             }
         }
         $processedReport = Piwik_API_API::getInstance()->getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters, $idGoal = false, $language);
         // TODO add static method getPrettyDate($period, $date) in Piwik_Period
         $prettyDate = $processedReport['prettyDate'];
         if ($mustRestoreGET) {
             $_GET = $mustRestoreGET;
         }
         $processedReports[] = $processedReport;
     }
     // restore filter truncate parameter value
     if ($initialFilterTruncate !== false) {
         $_GET['filter_truncate'] = $initialFilterTruncate;
     }
     $notificationInfo = array(self::REPORT_TYPE_INFO_KEY => $reportType, self::REPORT_KEY => $report);
     // allow plugins to alter processed reports
     Piwik_PostEvent(self::PROCESS_REPORTS_EVENT, $processedReports, $notificationInfo);
     // retrieve report renderer instance
     $reportRenderer = null;
     Piwik_PostEvent(self::GET_RENDERER_INSTANCE_EVENT, $reportRenderer, $notificationInfo);
     // init report renderer
     $reportRenderer->setLocale($language);
     $reportRenderer->setRenderImageInline($outputType != self::OUTPUT_SAVE_ON_DISK);
     // render report
     $websiteName = Piwik_Site::getNameFor($idSite);
     $description = str_replace(array("\r", "\n"), ' ', $report['description']);
     $reportRenderer->renderFrontPage($websiteName, $prettyDate, $description, $reportMetadata);
     array_walk($processedReports, array($reportRenderer, 'renderReport'));
     switch ($outputType) {
         case self::OUTPUT_SAVE_ON_DISK:
             $outputFilename = strtoupper($reportFormat) . ' ' . ucfirst($reportType) . ' Report - ' . $idReport . '.' . $date . '.' . $idSite . '.' . $language;
             $outputFilename = $reportRenderer->sendToDisk($outputFilename);
             $additionalFiles = array();
             if ($reportRenderer instanceof Piwik_ReportRenderer_Html) {
                 foreach ($processedReports as &$report) {
                     if ($report['displayGraph']) {
                         $additionalFile = array();
                         $additionalFile['filename'] = $report['metadata']['name'] . '.png';
                         $additionalFile['cid'] = $report['metadata']['uniqueId'];
                         $additionalFile['content'] = Piwik_ReportRenderer::getStaticGraph($report['metadata']['imageGraphUrl'], Piwik_ReportRenderer_Html::IMAGE_GRAPH_WIDTH, Piwik_ReportRenderer_Html::IMAGE_GRAPH_HEIGHT);
                         $additionalFile['mimeType'] = 'image/png';
                         $additionalFile['encoding'] = Zend_Mime::ENCODING_BASE64;
                         $additionalFiles[] = $additionalFile;
                     }
                 }
             }
             return array($outputFilename, $prettyDate, $websiteName, $additionalFiles);
             break;
         case self::OUTPUT_INLINE:
             $reportRenderer->sendToBrowserInline("{$websiteName} - {$prettyDate} - {$description}");
             break;
         case self::OUTPUT_RETURN:
             return $reportRenderer->getRenderedReport();
             break;
         default:
         case self::OUTPUT_DOWNLOAD:
             $reportRenderer->sendToBrowserDownload("{$websiteName} - {$prettyDate} - {$description}");
             break;
     }
 }
예제 #27
0
 /**
  * @param Piwik_Event_Notification $notification notification object
  */
 function getReportMetadata($notification)
 {
     if (self::manageEvent($notification)) {
         $availableReportMetadata =& $notification->getNotificationObject();
         $notificationInfo = $notification->getNotificationInfo();
         $idSite = $notificationInfo[Piwik_PDFReports_API::ID_SITE_INFO_KEY];
         foreach (self::$availableReports as $availableReport) {
             $reportMetadata = Piwik_API_API::getInstance()->getMetadata($idSite, $availableReport['module'], $availableReport['action']);
             if ($reportMetadata != null) {
                 $reportMetadata = reset($reportMetadata);
                 $availableReportMetadata[] = $reportMetadata;
             }
         }
     }
 }