Skip to content
Extraits de code Groupes Projets
ViewDataTable.php 59,4 ko
Newer Older
  • Learn to ignore specific revisions
  •      * Do not sort this table, leave it as it comes out of the API
         */
        public function disableSort()
        {
    
            $this->viewProperties['enable_sort'] = false;
    
        }
    
        /**
         * Do not show the footer icons (show all columns icon, "plus" icon)
         */
        public function disableFooterIcons()
        {
            $this->viewProperties['show_footer_icons'] = false;
        }
    
        /**
    
         * When this method is called, the output will not include the template datatable_footer
    
         */
        public function disableFooter()
        {
            $this->viewProperties['show_footer'] = false;
        }
    
        /**
         * The "Include low population" link won't be displayed under this table
         */
        public function disableExcludeLowPopulation()
        {
            $this->viewProperties['show_exclude_low_population'] = false;
        }
    
        /**
         * Whether or not to show the "View table" icon
         */
        public function disableShowTable()
        {
            $this->viewProperties['show_table'] = false;
        }
    
        /**
         * Whether or not to show the "View more data" icon
         */
        public function disableShowAllColumns()
        {
            $this->viewProperties['show_table_all_columns'] = false;
        }
    
        /**
         * Whether or not to show the tag cloud,  pie charts, bar chart icons
         */
        public function disableShowAllViewsIcons()
        {
            $this->viewProperties['show_all_views_icons'] = false;
        }
    
        /**
         * Whether or not to hide view icons altogether.
         * The difference to disableShowAllViewsIcons is that not even the single icon
         * will be shown. This icon might cause trouble because it reloads the graph on click.
         */
        public function hideAllViewsIcons()
        {
            $this->viewProperties['show_all_views_icons'] = false;
            $this->viewProperties['hide_all_views_icons'] = true;
        }
    
        /**
         * Whether or not to show the annotations view. This method has no effect if
         * the Annotations plugin is not loaded.
         */
        public function showAnnotationsView()
        {
            if (!Piwik_PluginsManager::getInstance()->isPluginLoaded('Annotations')) {
                return;
            }
    
            $this->viewProperties['hide_annotations_view'] = false;
        }
    
        /**
         * Whether or not to show the bar chart icon.
         */
        public function disableShowBarChart()
        {
            $this->viewProperties['show_bar_chart'] = false;
        }
    
        /**
         * Whether or not to show the pie chart icon.
         */
        public function disableShowPieChart()
        {
            $this->viewProperties['show_pie_chart'] = false;
        }
    
        /**
         * Whether or not to show the tag cloud icon.
         */
        public function disableTagCloud()
        {
            $this->viewProperties['show_tag_cloud'] = false;
        }
    
        /**
         * Whether or not to show related reports in the footer
         */
        public function disableShowRelatedReports()
        {
            $this->viewProperties['show_related_reports'] = false;
        }
    
        /**
         * Whether or not to show the export to RSS feed icon
         */
        public function disableShowExportAsRssFeed()
        {
            $this->viewProperties['show_export_as_rss_feed'] = false;
        }
    
        /**
         * Whether or not to show the "goal" icon
         */
        public function enableShowGoals()
        {
            if (Piwik_PluginsManager::getInstance()->isPluginActivated('Goals')) {
                $this->viewProperties['show_goals'] = true;
            }
        }
    
        /**
         * Whether or not to show the "Ecommerce orders/cart" icons
         */
        public function enableShowEcommerce()
        {
            $this->viewProperties['show_ecommerce'] = true;
        }
    
        /**
         * Whether or not to show the summary row on every page of results. The default behavior
         * is to treat the summary row like any other row.
         */
        public function alwaysShowSummaryRow()
        {
    
            $this->viewProperties['keep_summary_row'] = true;
    
        }
    
        /**
         * Sets the value to use for the Exclude low population filter.
         *
         * @param int|float If a row value is less than this value, it will be removed from the dataTable
         * @param string The name of the column for which we compare the value to $minValue
         */
        public function setExcludeLowPopulation($columnName = null, $minValue = null)
        {
            if (is_null($columnName)) {
                $columnName = 'nb_visits';
            }
    
            $this->viewProperties['filter_excludelowpop'] = $columnName;
            $this->viewProperties['filter_excludelowpop_value'] = $minValue;
    
        }
    
        /**
         * Sets the pattern to look for in the table (only rows matching the pattern will be kept)
         *
         * @param string $pattern to look for
         * @param string $column to compare the pattern to
         */
        public function setSearchPattern($pattern, $column)
        {
    
            $this->viewProperties['filter_pattern'] = $pattern;
            $this->viewProperties['filter_column'] = $column;
    
        }
    
        /**
         * Sets the maximum number of rows of the table
         *
         * @param int $limit
         */
        public function setLimit($limit)
        {
            if ($limit !== 0) {
    
                $this->viewProperties['filter_limit'] = $limit;
    
            }
        }
    
        /**
         * Will display a message in the DataTable footer.
         *
         * @param string $message Message
         */
        public function setFooterMessage($message)
        {
            $this->viewProperties['show_footer_message'] = $message;
        }
    
        /**
         * Sets the dataTable column to sort by. This sorting will be applied before applying the (offset, limit) filter.
         *
    
         * @param int|string $columnId eg. 'nb_visits' for some tables, or Piwik_Metrics::INDEX_NB_VISITS for others
    
         * @param string $order desc or asc
         */
        public function setSortedColumn($columnId, $order = 'desc')
        {
    
            $this->viewProperties['filter_sort_column'] = $columnId;
            $this->viewProperties['filter_sort_order'] = $order;
    
        }
    
        /**
         * Returns the column name on which the table will be sorted
         *
         * @return string
         */
        public function getSortedColumn()
        {
    
            return isset($this->viewProperties['filter_sort_column']) ? $this->viewProperties['filter_sort_column'] : false;
    
        }
    
        /**
         * Sets translation string for given column
         *
         * @param string $columnName column name
         * @param string $columnTranslation column name translation
         * @throws Exception
         */
        public function setColumnTranslation($columnName, $columnTranslation)
        {
    
            $this->viewProperties['translations'][$columnName] = $columnTranslation;
    
        }
    
        /**
         * Returns column translation if available, in other case given column name
         *
         * @param string $columnName column name
         * @return string
         */
        public function getColumnTranslation($columnName)
        {
    
            if (isset($this->viewProperties['translations'][$columnName])) {
                return $this->viewProperties['translations'][$columnName];
    
            }
            return $columnName;
        }
    
        /**
         * Set the documentation of a metric used in the report.
         * Please note, that the default way of doing this is by using
         * getReportMetadata. Only use this method, if you have a good
         * reason to do so.
         *
         * @param string $metricIdentifier The idenentifier string of
         *                    the metric
         * @param string $documentation The metric documentation as a
         *                    translated string
         */
        public function setMetricDocumentation($metricIdentifier, $documentation)
        {
    
            $this->viewProperties['metrics_documentation'][$metricIdentifier] = $documentation;
    
        }
    
        /**
         * Returns metric documentation, or false
         *
         * @param string $columnName column name
         * @return bool
         */
        public function getMetricDocumentation($columnName)
        {
    
            if (empty($this->viewProperties['metrics_documentation'])) {
    
            if (!empty($this->viewProperties['metrics_documentation'][$columnName])) {
                return $this->viewProperties['metrics_documentation'][$columnName];
    
            }
    
            return false;
        }
    
        /**
         * Set the documentation of the report.
         * Please note, that the default way of doing this is by using
         * getReportMetadata. Only use this method, if you have a good
         * reason to do so.
         *
         * @param string $documentation The report documentation as a
         *                    translated string
         */
        public function setReportDocumentation($documentation)
        {
    
            $this->viewProperties['documentation'] = $documentation;
    
        }
    
        /**
         * Returns report documentation, or false
         * @return array|bool
         */
        public function getReportDocumentation()
        {
    
            return $this->viewProperties['documentation'];
    
        }
    
        /** Load documentation from the API */
        private function loadDocumentation()
        {
    
            $this->viewProperties['metrics_documentation'] = array();
    
    
            $report = Piwik_API_API::getInstance()->getMetadata(0, $this->currentControllerName, $this->currentControllerAction);
            $report = $report[0];
    
            if (isset($report['metricsDocumentation'])) {
    
                $this->viewProperties['metrics_documentation'] = $report['metricsDocumentation'];
    
                $this->viewProperties['documentation'] = $report['documentation'];
    
            }
        }
    
        /**
         * Sets the columns that will be displayed in the HTML output
         * By default all columns are displayed ($columnsNames = array() will display all columns)
         *
         * @param array $columnsNames Array of column names eg. array('nb_visits','nb_hits')
         */
        public function setColumnsToDisplay($columnsNames)
        {
            if (!is_array($columnsNames)) {
                if (strpos($columnsNames, ',') !== false) {
                    // array values are comma separated
                    $columnsNames = explode(',', $columnsNames);
                } else {
                    $columnsNames = array($columnsNames);
                }
            }
    
            $this->viewProperties['columns_to_display'] = array_filter($columnsNames);
    
        }
    
        /**
         * Returns columns names to display, in order.
         * If no columns were specified to be displayed, return all columns found in the first row.
         * If the data table has empty_columns meta data set, those columns will be removed.
         * @param array PHP array conversion of the data table
         * @return array
         */
        public function getColumnsToDisplay()
        {
    
            if (empty($this->viewProperties['columns_to_display'])) {
    
                $row = $this->dataTable->getFirstRow();
                if (empty($row)) {
                    return array();
                }
    
                return array_keys($row->getColumns());
            }
    
    
            $this->viewProperties['columns_to_display'] = array_filter($this->viewProperties['columns_to_display']);
    
            $this->removeEmptyColumnsFromDisplay();
    
    
            return $this->viewProperties['columns_to_display'];
    
        }
    
        private function removeEmptyColumnsFromDisplay()
        {
    
    mattab's avatar
    mattab a validé
            if(empty($this->dataTable)) {
                return;
            }
    
            if ($this->dataTable instanceof Piwik_DataTable_Array) {
                $emptyColumns = $this->dataTable->getMetadataIntersectArray(Piwik_DataTable::EMPTY_COLUMNS_METADATA_NAME);
            } else {
                $emptyColumns = $this->dataTable->getMetadata(Piwik_DataTable::EMPTY_COLUMNS_METADATA_NAME);
            }
            if (is_array($emptyColumns)) {
                foreach ($emptyColumns as $emptyColumn) {
    
                    $key = array_search($emptyColumn, $this->viewProperties['columns_to_display']);
    
                        unset($this->viewProperties['columns_to_display'][$key]);
    
                $this->viewProperties['columns_to_display'] = array_values($this->viewProperties['columns_to_display']);
    
            }
        }
    
        /**
         * Set whether to highlight the summary row or not. If not highlighted, it will
         * look like every other row.
         */
        public function setHighlightSummaryRow($highlightSummaryRow)
        {
            $this->viewProperties['highlight_summary_row'] = $highlightSummaryRow;
        }
    
        /**
         * Sets the name of the metadata to use for a custom tooltip.
         */
        public function setTooltipMetadataName($metadataName)
        {
            $this->viewProperties['tooltip_metadata_name'] = $metadataName;
        }
    
        /**
         * Sets columns translations array.
         *
         * @param array $columnsTranslations An associative array indexed by column names, eg. array('nb_visit'=>"Numer of visits")
         */
        public function setColumnsTranslations($columnsTranslations)
        {
    
            $this->viewProperties['translations'] += $columnsTranslations;
    
        }
    
        /**
         * Sets a custom parameter, that will be printed in the javascript array associated with each datatable
         *
         * @param string $parameter name
         * @param mixed $value
         * @throws Exception
         */
        public function setCustomParameter($parameter, $value)
        {
    
            if (isset($this->viewProperties['custom_parameters'][$parameter])) {
    
                throw new Exception("$parameter is already defined for this DataTable.");
            }
    
            $this->viewProperties['custom_parameters'][$parameter] = $value;
    
        }
    
        /**
         * Queues a Datatable filter, that will be applied once the datatable is loaded from the API.
         * Useful when the controller needs to add columns, or decorate existing columns, when these filters don't
         * necessarily make sense directly in the API.
         *
         * @param string $filterName
         * @param mixed $parameters
         * @param bool $runBeforeGenericFilters Set to true if the filter will delete rows from the table,
         *                                    and should therefore be ran before Sort, Limit, etc.
         * @return void
         */
    
        public function queueFilter($filterName, $parameters = array(), $runBeforeGenericFilters = false)
    
        {
            if ($runBeforeGenericFilters) {
                $this->queuedFiltersPriority[] = array($filterName, $parameters);
            } else {
                $this->queuedFilters[] = array($filterName, $parameters);
            }
        }
    
        /**
         * Adds one report to the set of reports that are related to this one. Related reports
         * are displayed in the footer as links. When they are clicked, the report will change to
         * the related report.
         *
         * Make sure to call setReportTitle so this report will be displayed correctly.
         *
         * @param string $module The report's controller name, ie, 'UserSettings'.
         * @param string $action The report's controller action, ie, 'getBrowser'.
         * @param string $title The text used to describe the related report.
         * @param array $queryParams Any specific query params to use when loading the report.
         *                           This can be used to, for example, make a goal report a related
         *                           report (by adding an idGoal parameter).
         */
        public function addRelatedReport($module, $action, $title, $queryParams = array())
        {
            // don't add the related report if it references this report
            if ($this->currentControllerName == $module && $this->currentControllerAction == $action) {
                return;
            }
    
            $url = $this->getBaseReportUrl($module, $action, $queryParams);
            $this->viewProperties['relatedReports'][$url] = $title;
        }
    
        /**
         * Adds a set of reports that are related to this one. Related reports are displayed in
         * the footer as links. When they are clicked, the report will change to the related report.
         *
         * If you need to associate specific query params with a report, use the addRelatedReport
         * method instead of this one.
         *
         * @param string $thisReportTitle The title of this report.
         * @param array $relatedReports An array mapping report IDs ('Controller.methodName') with
         *                              display text.
         */
        public function addRelatedReports($thisReportTitle, $relatedReports)
        {
    
            if (!empty($thisReportTitle)) {
                $this->setReportTitle($thisReportTitle);
            }
            
    
            foreach ($relatedReports as $report => $title) {
                list($module, $action) = explode('.', $report);
                $this->addRelatedReport($module, $action, $title);
            }
        }
    
        /**
         * Sets the title of this report.
         *
         * @param string $title
         */
        public function setReportTitle($title)
        {
            $this->viewProperties['title'] = $title;
        }
    
        /**
         * Sets a custom URL to use to reference this report.
         *
    
    sgiehl's avatar
    sgiehl a validé
         * @param string  $module
         * @param string  $action
         * @param array   $queryParams
    
         */
        public function setReportUrl($module, $action, $queryParams = array())
        {
            $this->viewProperties['self_url'] = $this->getBaseReportUrl($module, $action, $queryParams);
        }
    
        /**
         * Returns true if it is likely that the data for this report has been purged and if the
         * user should be told about that.
         *
         * In order for this function to return true, the following must also be true:
         * - The data table for this report must either be empty or not have been fetched.
         * - The period of this report is not a multiple period.
         * - The date of this report must be older than the delete_reports_older_than config option.
         * @return bool
         */
        public function hasReportBeenPurged()
        {
            $strPeriod = Piwik_Common::getRequestVar('period', false);
            $strDate = Piwik_Common::getRequestVar('date', false);
    
            if ($strPeriod !== false
                && $strDate !== false
                && (is_null($this->dataTable) || $this->dataTable->getRowsCount() == 0)
            ) {
                // if range, only look at the first date
                if ($strPeriod == 'range') {
                    $idSite = Piwik_Common::getRequestVar('idSite', '');
                    if (intval($idSite) != 0) {
                        $site = new Piwik_Site($idSite);
                        $timezone = $site->getTimezone();
                    } else {
                        $timezone = 'UTC';
                    }
    
                    $period = new Piwik_Period_Range('range', $strDate, $timezone);
                    $reportDate = $period->getDateStart();
                } // if a multiple period, this function is irrelevant
    
                else if (Piwik_Period::isMultiplePeriod($strDate, $strPeriod)) {
    
                    return false;
                } // otherwise, use the date as given
                else {
                    $reportDate = Piwik_Date::factory($strDate);
                }
    
                $reportYear = $reportDate->toString('Y');
                $reportMonth = $reportDate->toString('m');
    
                if (class_exists('Piwik_PrivacyManager')
                    && Piwik_PrivacyManager::shouldReportBePurged($reportYear, $reportMonth)
                ) {
                    return true;
                }
            }
    
            return false;
        }
    
        /**
         * Returns URL for this report w/o any filter parameters.
         *
         * @param string $module
         * @param string $action
         * @param array $queryParams
    
    sgiehl's avatar
    sgiehl a validé
         * @return string
    
         */
        private function getBaseReportUrl($module, $action, $queryParams = array())
        {
            $params = array_merge($queryParams, array('module' => $module, 'action' => $action));
    
            return Piwik_API_Request::getCurrentUrlWithoutGenericFilters($params);
        }
        
        /**
         * Convenience method that creates and renders a ViewDataTable for a API method.
         * 
         * @param string $pluginName The name of the plugin (eg, UserSettings).
         * @param string $apiAction The name of the API action (eg, getResolution).
         * @param bool $fetch If true, the result is returned, if false it is echo'd.
         * @return string|null See $fetch.
         */
        static public function render($pluginName, $apiAction, $fetch = true)
        {
            $apiClassName = 'Piwik_'.$pluginName.'_API';
            if (!method_exists($apiClassName::getInstance(), $apiAction)) {
                throw new Exception("Invalid action name '$apiAction' for '$pluginName' plugin.");
            }
            
            $view = self::factory(null, $pluginName.'.'.$apiAction);
            $view->main();
            $rendered = $view->getView()->render();
            
            if ($fetch) {
                return $rendered;
            } else {
                echo $rendered;
    
        
        /**
         * Returns whether the DataTable result will have to be expanded for the
         * current request before rendering.
         * 
         * @return bool
         */
        public static function shouldLoadExpanded()
        {
            // if filter_column_recursive & filter_pattern_recursive are supplied, and flat isn't supplied
            // we have to load all the child subtables.
            return Piwik_Common::getRequestVar('filter_column_recursive', false) !== false
                 && Piwik_Common::getRequestVar('filter_pattern_recursive', false) !== false
                 && Piwik_Common::getRequestVar('flat', false) === false;
        }
    
        
        /**
         * Returns true if the first array contains one or more of the specified
         * column names or their associated integer INDEX_ value.
         * 
         * @param array $columns Piwik_DataTable_Row columns.
         * @param array|string $columnsToCheckFor eg, array('nb_visits', 'nb_uniq_visitors')
         * @return bool
         */
        private function dataTableColumnsContains($columns, $columnsToCheckFor)
        {
            if (!is_array($columnsToCheckFor)) {
                $columnsToCheckFor = array($columnsToCheckFor);
            }
            
            foreach ($columnsToCheckFor as $columnToCheckFor) {
                foreach ($columns as $column) {
                    // check for the column name and its associated integer INDEX_ value
                    if ($column == $columnToCheckFor
                        || (isset(Piwik_Metrics::$mappingFromNameToId[$columnToCheckFor])
                            && $column == Piwik_Metrics::$mappingFromNameToId[$columnToCheckFor])
                    ) {
                        return true;
                    }
                }
            }
            
            return false;
        }
    
    
        protected function buildView($visualization, $template = false)
        {
            if ($template === false) {
                $template = $this->dataTableTemplate;
            }
    
            $view = new Piwik_View($template);
    
            if (!empty($this->loadingError)) {
                $view->error = $this->loadingError;
            }
    
            $view->visualization = $visualization;
            
            if (!$this->isDataAvailable) {
                $view->dataTable = null;
            } else {
                $view->dataTable = $this->dataTable;
    
                // if it's likely that the report data for this data table has been purged,
                // set whether we should display a message to that effect.
                $view->showReportDataWasPurgedMessage = $this->hasReportBeenPurged();
                $view->deleteReportsOlderThan = Piwik_GetOption('delete_reports_older_than');
            }
            $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet();
            $view->properties = $this->getViewProperties();
            return $view;
        }
    
        public function getDefaultDataTableCssClass()
        {
            return false;
        }
    
    mattpiwik's avatar
     
    mattpiwik a validé
    }