Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Csv.php « Renderer « DataTable « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 03074897d4721f4988d76f48f5600fe3b8ecebe2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik
 * @package Piwik
 */
namespace Piwik\DataTable\Renderer;

use Piwik\DataTable\Simple;
use Piwik\DataTable\Renderer;
use Piwik\Period;
use Piwik\Period\Range;
use Piwik\Piwik;
use Piwik\Common;
use Piwik\Date;
use Piwik\DataTable;

/**
 * CSV export
 *
 * When rendered using the default settings, a CSV report has the following characteristics:
 * The first record contains headers for all the columns in the report.
 * All rows have the same number of columns.
 * The default field delimiter string is a comma (,).
 * Formatting and layout are ignored.
 *
 * @package Piwik
 * @subpackage DataTable
 */
class Csv extends Renderer
{
    /**
     * Column separator
     *
     * @var string
     */
    public $separator = ",";

    /**
     * Line end
     *
     * @var string
     */
    public $lineEnd = "\n";

    /**
     * 'metadata' columns will be exported, prefixed by 'metadata_'
     *
     * @var bool
     */
    public $exportMetadata = true;

    /**
     * Converts the content to unicode so that UTF8 characters (eg. chinese) can be imported in Excel
     *
     * @var bool
     */
    public $convertToUnicode = true;

    /**
     * idSubtable will be exported in a column called 'idsubdatatable'
     *
     * @var bool
     */
    public $exportIdSubtable = true;

    /**
     * Computes the dataTable output and returns the string/binary
     *
     * @return string
     */
    public function render()
    {
        $str = $this->renderTable($this->table);
        if (empty($str)) {
            return 'No data available';
        }

        $this->renderHeader();

        if ($this->convertToUnicode
            && function_exists('mb_convert_encoding')
        ) {
            $str = chr(255) . chr(254) . mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
        }
        return $str;
    }

    /**
     * Computes the exception output and returns the string/binary
     *
     * @return string
     */
    function renderException()
    {
        @header('Content-Type: text/html; charset=utf-8');
        $exceptionMessage = $this->getExceptionMessage();
        return 'Error: ' . $exceptionMessage;
    }

    /**
     * Enables / Disables unicode converting
     *
     * @param $bool
     */
    public function setConvertToUnicode($bool)
    {
        $this->convertToUnicode = $bool;
    }

    /**
     * Sets the column separator
     *
     * @param $separator
     */
    public function setSeparator($separator)
    {
        $this->separator = $separator;
    }

    /**
     * Computes the output of the given data table
     *
     * @param DataTable|array $table
     * @param array $allColumns
     * @return string
     */
    protected function renderTable($table, &$allColumns = array())
    {
        if (is_array($table)) // convert array to DataTable
        {
            $table = DataTable::makeFromSimpleArray($table);
        }

        if ($table instanceof DataTable\Map) {
            $str = $this->renderDataTableArray($table, $allColumns);
        } else {
            $str = $this->renderDataTable($table, $allColumns);
        }
        return $str;
    }

    /**
     * Computes the output of the given data table array
     *
     * @param DataTable\Map $table
     * @param array $allColumns
     * @return string
     */
    protected function renderDataTableArray($table, &$allColumns = array())
    {
        $str = '';
        foreach ($table->getArray() as $currentLinePrefix => $dataTable) {
            $returned = explode("\n", $this->renderTable($dataTable, $allColumns));

            // get rid of the columns names
            $returned = array_slice($returned, 1);

            // case empty datatable we dont print anything in the CSV export
            // when in xml we would output <result date="2008-01-15" />
            if (!empty($returned)) {
                foreach ($returned as &$row) {
                    $row = $currentLinePrefix . $this->separator . $row;
                }
                $str .= "\n" . implode("\n", $returned);
            }
        }

        // prepend table key to column list
        $allColumns = array_merge(array($table->getKeyName() => true), $allColumns);

        // add header to output string
        $str = $this->getHeaderLine(array_keys($allColumns)) . $str;

        return $str;
    }

    /**
     * Converts the output of the given simple data table
     *
     * @param Simple $table
     * @param array $allColumns
     * @return string
     */
    protected function renderDataTable($table, &$allColumns = array())
    {
        if ($table instanceof Simple) {
            $row = $table->getFirstRow();
            if ($row !== false) {
                $columnNameToValue = $row->getColumns();
                if (count($columnNameToValue) == 1) {
                    // simple tables should only have one column, the value
                    $allColumns['value'] = true;

                    $value = array_values($columnNameToValue);
                    $str = 'value' . $this->lineEnd . $this->formatValue($value[0]);
                    return $str;
                }
            }
        }
        $csv = array();
        foreach ($table->getRows() as $row) {
            $csvRow = array();

            $columns = $row->getColumns();
            foreach ($columns as $name => $value) {
                //goals => array( 'idgoal=1' =>array(..), 'idgoal=2' => array(..))
                if (is_array($value)) {
                    foreach ($value as $key => $subValues) {
                        if (is_array($subValues)) {
                            foreach ($subValues as $subKey => $subValue) {
                                if ($this->translateColumnNames) {
                                    $subName = $name != 'goals' ? $name . ' ' . $key
                                        : Piwik_Translate('Goals_GoalX', $key);
                                    $columnName = $this->translateColumnName($subKey)
                                        . ' (' . $subName . ')';
                                } else {
                                    // goals_idgoal=1
                                    $columnName = $name . "_" . $key . "_" . $subKey;
                                }
                                $allColumns[$columnName] = true;
                                $csvRow[$columnName] = $subValue;
                            }
                        }
                    }
                } else {
                    $allColumns[$name] = true;
                    $csvRow[$name] = $value;
                }
            }

            if ($this->exportMetadata) {
                $metadata = $row->getMetadata();
                foreach ($metadata as $name => $value) {
                    if ($name == 'idsubdatatable_in_db') {
                        continue;
                    }
                    //if a metadata and a column have the same name make sure they dont overwrite
                    if ($this->translateColumnNames) {
                        $name = Piwik_Translate('General_Metadata') . ': ' . $name;
                    } else {
                        $name = 'metadata_' . $name;
                    }

                    $allColumns[$name] = true;
                    $csvRow[$name] = $value;
                }
            }

            if ($this->exportIdSubtable) {
                $idsubdatatable = $row->getIdSubDataTable();
                if ($idsubdatatable !== false
                    && $this->hideIdSubDatatable === false
                ) {
                    $csvRow['idsubdatatable'] = $idsubdatatable;
                }
            }

            $csv[] = $csvRow;
        }

        // now we make sure that all the rows in the CSV array have all the columns
        foreach ($csv as &$row) {
            foreach ($allColumns as $columnName => $true) {
                if (!isset($row[$columnName])) {
                    $row[$columnName] = '';
                }
            }
        }

        $str = '';

        // specific case, we have only one column and this column wasn't named properly (indexed by a number)
        // we don't print anything in the CSV file => an empty line
        if (sizeof($allColumns) == 1
            && reset($allColumns)
            && !is_string(key($allColumns))
        ) {
            $str .= '';
        } else {
            // render row names
            $str .= $this->getHeaderLine(array_keys($allColumns)) . $this->lineEnd;
        }

        // we render the CSV
        foreach ($csv as $theRow) {
            $rowStr = '';
            foreach ($allColumns as $columnName => $true) {
                $rowStr .= $this->formatValue($theRow[$columnName]) . $this->separator;
            }
            // remove the last separator
            $rowStr = substr_replace($rowStr, "", -strlen($this->separator));
            $str .= $rowStr . $this->lineEnd;
        }
        $str = substr($str, 0, -strlen($this->lineEnd));
        return $str;
    }

    /**
     * Returns the CSV header line for a set of metrics. Will translate columns if desired.
     *
     * @param array $columnMetrics
     * @return array
     */
    private function getHeaderLine($columnMetrics)
    {
        if ($this->translateColumnNames) {
            $columnMetrics = $this->translateColumnNames($columnMetrics);
        }
        return implode($this->separator, $columnMetrics);
    }

    /**
     * Formats/Escapes the given value
     *
     * @param mixed $value
     * @return string
     */
    protected function formatValue($value)
    {
        if (is_string($value)
            && !is_numeric($value)
        ) {
            $value = html_entity_decode($value, ENT_COMPAT, 'UTF-8');
        } elseif ($value === false) {
            $value = 0;
        }
        if (is_string($value)
            && (strpos($value, '"') !== false
                || strpos($value, $this->separator) !== false)
        ) {
            $value = '"' . str_replace('"', '""', $value) . '"';
        }

        // in some number formats (e.g. German), the decimal separator is a comma
        // we need to catch and replace this
        if (is_numeric($value)) {
            $value = (string)$value;
            $value = str_replace(',', '.', $value);
        }

        return $value;
    }

    /**
     * Sends the http headers for csv file
     */
    protected function renderHeader()
    {
        $fileName = 'Piwik ' . Piwik_Translate('General_Export');

        $period = Common::getRequestVar('period', false);
        $date = Common::getRequestVar('date', false);
        if ($period || $date) // in test cases, there are no request params set
        {
            if ($period == 'range') {
                $period = new Range($period, $date);
            } else if (strpos($date, ',') !== false) {
                $period = new Range('range', $date);
            } else {
                $period = Period::factory($period, Date::factory($date));
            }

            $prettyDate = $period->getLocalizedLongString();

            $meta = $this->getApiMetaData();

            $fileName .= ' _ ' . $meta['name']
                . ' _ ' . $prettyDate . '.csv';
        }

        // silent fail otherwise unit tests fail
        @header('Content-Type: application/vnd.ms-excel');
        @header('Content-Disposition: attachment; filename="' . $fileName . '"');
        Piwik::overrideCacheControlHeaders();
    }
}