Passed
Push — dependabot/npm_and_yarn/nanoid... ( aaf2c9...c4aa90 )
by
unknown
14:37 queued 06:22
created

Export::arrayToCsvSimple()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
nc 9
nop 4
dl 0
loc 27
rs 9.4888
c 1
b 0
f 0
1
<?php
2
3
/* See license terms in /license.txt */
4
5
use PhpOffice\PhpSpreadsheet\Spreadsheet;
6
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
7
use Sonata\Exporter\Handler;
8
use Sonata\Exporter\Source\ArraySourceIterator;
9
use Sonata\Exporter\Writer\CsvWriter;
10
use Sonata\Exporter\Writer\XlsWriter;
11
use Symfony\Component\Filesystem\Filesystem;
12
13
/**
14
 *  This is the export library for Chamilo.
15
 *  Include/require it in your code to use its functionality.
16
 */
17
class Export
18
{
19
    /**
20
     * Constructor.
21
     */
22
    public function __construct()
23
    {
24
    }
25
26
    /**
27
     * Export tabular data to CSV-file.
28
     *
29
     * @return mixed csv raw data | false if no data to export | string file path if success in $writeOnly mode
30
     */
31
    public static function arrayToCsv(array $data, string $filename = 'export', bool $writeOnly = false, string $enclosure = '"')
32
    {
33
        if (empty($data)) {
34
            return false;
35
        }
36
37
        $enclosure = !empty($enclosure) ? $enclosure : '"';
38
        $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.csv';
39
        $writer = new CsvWriter($filePath, ';', $enclosure, true);
40
41
        $source = new ArraySourceIterator($data);
42
        $handler = Handler::create($source, $writer);
43
        $handler->export();
44
45
        if (!$writeOnly) {
46
            DocumentManager::file_send_for_download($filePath, true, $filename.'.csv');
47
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
48
        }
49
50
        return $filePath;
51
    }
52
53
    /**
54
     * Converts an array of data into a CSV file and optionally sends it for download.
55
     *
56
     * @return string|void Returns the file path if $writeOnly is true, otherwise sends the file for download and exits.
57
     */
58
    public static function arrayToCsvSimple(array $data, string $filename = 'export', bool $writeOnly = false, array $header = [])
59
    {
60
        $file = api_get_path(SYS_ARCHIVE_PATH) . uniqid('') . '.csv';
61
62
        $handle = fopen($file, 'w');
63
64
        if ($handle === false) {
65
            throw new \RuntimeException("Unable to create or open the file: $file");
66
        }
67
68
        if (!empty($header)) {
69
            fputcsv($handle, $header, ';');
70
        }
71
72
        foreach ($data as $row) {
73
            fputcsv($handle, (array)$row, ';');
74
        }
75
76
        fclose($handle);
77
78
        if (!$writeOnly) {
79
            DocumentManager::file_send_for_download($file, true, $filename . '.csv');
80
            unlink($file);
81
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
82
        }
83
84
        return $file;
85
    }
86
87
    /**
88
     * Export tabular data to XLS-file.
89
     */
90
    public static function arrayToXls(array $data, string $filename = 'export')
91
    {
92
        if (empty($data)) {
93
            return false;
94
        }
95
96
        $spreadsheet = new Spreadsheet();
97
        $sheet = $spreadsheet->getActiveSheet();
98
        $rowNumber = 1;
99
        foreach ($data as $row) {
100
            $colNumber = 'A';
101
            foreach ($row as $cell) {
102
                $sheet->setCellValue($colNumber . $rowNumber, $cell);
103
                $colNumber++;
104
            }
105
            $rowNumber++;
106
        }
107
108
        $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.xlsx';
109
        $writer = new Xlsx($spreadsheet);
110
        $writer->save($filePath);
111
112
        DocumentManager::file_send_for_download($filePath, true, $filename.'.xlsx');
113
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
114
    }
115
116
    /**
117
     * Export tabular data to XLS-file (as html table).
118
     *
119
     * @param array  $data
120
     * @param string $filename
121
     */
122
    public static function export_table_xls_html($data, $filename = 'export', $encoding = 'utf-8')
123
    {
124
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.xls';
125
        $handle = fopen($file, 'a+');
126
        $systemEncoding = api_get_system_encoding();
127
        fwrite($handle, '<!DOCTYPE html><html><meta http-equiv="Content-Type" content="text/html" charset="'.$encoding.'" /><body><table>');
128
        foreach ($data as $id => $row) {
129
            foreach ($row as $id2 => $row2) {
130
                $data[$id][$id2] = api_htmlentities($row2);
131
            }
132
        }
133
        foreach ($data as $row) {
134
            $string = implode("</td><td>", $row);
135
            $string = '<tr><td>'.$string.'</td></tr>';
136
            if ('utf-8' != $encoding) {
137
                $string = api_convert_encoding($string, $encoding, $systemEncoding);
138
            }
139
            fwrite($handle, $string."\n");
140
        }
141
        fwrite($handle, '</table></body></html>');
142
        fclose($handle);
143
        DocumentManager::file_send_for_download($file, true, $filename.'.xls');
144
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
145
    }
146
147
    /**
148
     * Export tabular data to XML-file.
149
     *
150
     * @param array  Simple array of data to put in XML
151
     * @param string Name of file to be given to the user
152
     * @param string Name of common tag to place each line in
153
     * @param string Name of the root element. A root element should always be given.
154
     * @param string Encoding in which the data is provided
155
     */
156
    public static function arrayToXml(
157
        $data,
158
        $filename = 'export',
159
        $item_tagname = 'item',
160
        $wrapper_tagname = null,
161
        $encoding = null
162
    ) {
163
        if (empty($encoding)) {
164
            $encoding = api_get_system_encoding();
165
        }
166
        $file = api_get_path(SYS_ARCHIVE_PATH).'/'.uniqid('').'.xml';
167
        $handle = fopen($file, 'a+');
168
        fwrite($handle, '<?xml version="1.0" encoding="'.$encoding.'"?>'."\n");
169
        if (!is_null($wrapper_tagname)) {
170
            fwrite($handle, "\t".'<'.$wrapper_tagname.'>'."\n");
171
        }
172
        foreach ($data as $row) {
173
            fwrite($handle, '<'.$item_tagname.'>'."\n");
174
            foreach ($row as $key => $value) {
175
                fwrite($handle, "\t\t".'<'.$key.'>'.$value.'</'.$key.'>'."\n");
176
            }
177
            fwrite($handle, "\t".'</'.$item_tagname.'>'."\n");
178
        }
179
        if (!is_null($wrapper_tagname)) {
180
            fwrite($handle, '</'.$wrapper_tagname.'>'."\n");
181
        }
182
        fclose($handle);
183
        DocumentManager::file_send_for_download($file, true, $filename.'.xml');
184
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
185
    }
186
187
    /**
188
     * @param array $data table to be read with the HTML_table class
189
     */
190
    public static function export_table_pdf($data, $params = [])
191
    {
192
        $table_html = self::convert_array_to_html($data, $params);
193
        $params['format'] = isset($params['format']) ? $params['format'] : 'A4';
194
        $params['orientation'] = isset($params['orientation']) ? $params['orientation'] : 'P';
195
196
        $pdf = new PDF($params['format'], $params['orientation'], $params);
197
        $pdf->html_to_pdf_with_template($table_html);
198
    }
199
200
    /**
201
     * @param string $html
202
     * @param array  $params
203
     */
204
    public static function export_html_to_pdf($html, $params = [])
205
    {
206
        $params['format'] = isset($params['format']) ? $params['format'] : 'A4';
207
        $params['orientation'] = isset($params['orientation']) ? $params['orientation'] : 'P';
208
209
        $pdf = new PDF($params['format'], $params['orientation'], $params);
210
        $pdf->html_to_pdf_with_template($html);
211
    }
212
213
    /**
214
     * @param array $data
215
     * @param array $params
216
     *
217
     * @return string
218
     */
219
    public static function convert_array_to_html($data, $params = [])
220
    {
221
        $headers = $data[0];
222
        unset($data[0]);
223
224
        $header_attributes = isset($params['header_attributes']) ? $params['header_attributes'] : [];
225
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table', 'repeat_header' => '1']);
226
        $row = 0;
227
        $column = 0;
228
        foreach ($headers as $header) {
229
            $table->setHeaderContents($row, $column, $header);
230
            $attributes = [];
231
            if (isset($header_attributes) && isset($header_attributes[$column])) {
232
                $attributes = $header_attributes[$column];
233
            }
234
            if (!empty($attributes)) {
235
                $table->updateCellAttributes($row, $column, $attributes);
236
            }
237
            $column++;
238
        }
239
        $row++;
240
        foreach ($data as &$printable_data_row) {
241
            $column = 0;
242
            foreach ($printable_data_row as &$printable_data_cell) {
243
                $table->setCellContents($row, $column, $printable_data_cell);
244
                //$table->updateCellAttributes($row, $column, $atributes);
245
                $column++;
246
            }
247
            $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
248
            $row++;
249
        }
250
251
        return $table->toHtml();
252
    }
253
254
    /**
255
     * Export HTML content in a ODF document.
256
     *
257
     * @param string $html
258
     * @param string $name
259
     * @param string $format
260
     *
261
     * @return bool
262
     */
263
    public static function htmlToOdt($html, $name, $format = 'odt')
264
    {
265
        $unoconv = api_get_setting('platform.unoconv_binaries');
266
267
        if (empty($unoconv)) {
268
            return false;
269
        }
270
271
        if (!empty($html)) {
272
            /*$fs = new Filesystem();
273
            $paths = [
274
                'root_sys' => api_get_path(SYS_PATH),
275
                'path.temp' => api_get_path(SYS_ARCHIVE_PATH),
276
            ];
277
            $connector = new Connector();
278
279
            $drivers = new DriversContainer();
280
            $drivers['configuration'] = [
281
                'unoconv.binaries' => $unoconv,
282
                'unoconv.timeout' => 60,
283
            ];
284
285
            $tempFilesystem = TemporaryFilesystem::create();
286
            $manager = new Manager($tempFilesystem, $fs);
287
            $alchemyst = new Alchemyst($drivers, $manager);
288
289
            $dataFileSystem = new Data($paths, $fs, $connector, $alchemyst);
290
            $content = $dataFileSystem->convertRelativeToAbsoluteUrl($html);
291
            $filePath = $dataFileSystem->putContentInTempFile(
292
                $content,
293
                api_replace_dangerous_char($name),
294
                'html'
295
            );
296
297
            $try = true;
298
299
            while ($try) {
300
                try {
301
                    $convertedFile = $dataFileSystem->transcode(
302
                        $filePath,
303
                        $format
304
                    );
305
306
                    $try = false;
307
                    DocumentManager::file_send_for_download(
308
                        $convertedFile,
309
                        false,
310
                        $name.'.'.$format
311
                    );
312
                } catch (Exception $e) {
313
                    // error_log($e->getMessage());
314
                }
315
            }*/
316
        }
317
    }
318
}
319